//! Finding 2 of the native realtime audit: display positions are mapped by //! walking the tree, not by building the projection. The walk must agree, //! position by position, with the projection-based mapping it replaced //! (support::oracle), on edited documents and on every kind of node. mod support; use docs_native_crdt::Editor; use serde_json::{json, Value}; use support::{generate, oracle, oracle_locate, Random}; fn open(bytes: &[u8], client: u64) -> Editor { let editor = Editor::new("large-document", client); editor.apply(bytes).unwrap(); editor } /// The display text, rendered from the projection the way the apps do. fn render(value: &Value, out: &mut Vec) { match value["type"].as_str().unwrap_or("") { "text" => for run in value["runs"].as_array().into_iter().flatten() { out.extend(run["insert"].as_str().unwrap().encode_utf16()); }, "hard_break" => out.push(0x2028), "image" => out.push(0xFFFC), "horizontal_rule" => out.extend([0xFFFC, 10]), tag => { for child in value["children"].as_array().into_iter().flatten() { render(child, out); } if ["paragraph", "heading", "code_block"].contains(&tag) { out.push(10); } }, } } fn display(editor: &Editor) -> Vec { let mut out = Vec::new(); for child in editor.projection()["children"].as_array().unwrap() { render(child, &mut out); } out } fn check_every_position(editor: &Editor, step: u32) { let projection = editor.projection(); let (ranges, total) = oracle(&projection); assert_eq!(editor.display_length(), total); assert_eq!(display(editor).len() as u32, total); let mut at = 0; while at <= total + 1 { for length in [0, 1, 3, 40] { let expected = oracle_locate(&ranges, at, length); let actual = editor.display_locate(at, length).ok(); assert_eq!(actual, expected, "locate({at}, {length})"); } let anchor = editor.anchor(at).unwrap(); let expected = match oracle_locate(&ranges, at, 0) { Some((node, local)) => { let span = ranges.iter().find(|r| r.node == node).unwrap(); assert_eq!(anchor["node"], node); span.start + local.min(span.length) }, None => at.min(total.saturating_sub(1)), }; assert_eq!(editor.resolve(&anchor).unwrap(), expected, "resolve(anchor({at}))"); at += step; } } #[test] fn walk_matches_the_projection_mapping_on_edited_documents() { for (pages, edits, step) in [(1, 0, 1), (2, 120, 1), (8, 900, 7)] { let editor = open(&generate(pages, edits, 11), 101); check_every_position(&editor, step); } } #[test] fn walk_matches_on_every_kind_of_node() { let mut editor = Editor::new("kinds", 201); editor.command(&json!({"op":"insert_element","at":0,"type":"paragraph"})).unwrap(); editor.command(&json!({"op":"display_paste","at":0,"length":0,"blocks":[ {"type":"heading","attrs":{"level":"1"},"children":[{"type":"text","runs":[{"insert":"Title 😀","marks":{"strong":{}}}]}]}, {"type":"paragraph","children":[]}, {"type":"paragraph","children":[{"type":"text","runs":[{"insert":"before","marks":{}}]},{"type":"hard_break"},{"type":"text","runs":[{"insert":"after","marks":{"em":{}}}]},{"type":"image","attrs":{"src":"https://example.com/a.png"}}]}, {"type":"horizontal_rule"}, {"type":"code_block","children":[{"type":"text","runs":[{"insert":"let x = 1;\nlet y = 2;","marks":{}}]}]}, {"type":"blockquote","children":[{"type":"paragraph","children":[{"type":"text","runs":[{"insert":"quoted","marks":{}}]}]}]}, {"type":"bullet_list","children":[ {"type":"list_item","children":[{"type":"paragraph","children":[{"type":"text","runs":[{"insert":"one","marks":{}}]}]}, {"type":"ordered_list","children":[{"type":"list_item","children":[{"type":"paragraph","children":[]}]}]}]}, {"type":"list_item","children":[{"type":"paragraph","children":[{"type":"text","runs":[{"insert":"two","marks":{}}]}]}]} ]}, {"type":"image","attrs":{"src":"https://example.com/b.png"}}, {"type":"paragraph","children":[{"type":"hard_break"},{"type":"hard_break"}]} ]})).unwrap(); check_every_position(&editor, 1); // Empty text nodes, as an edit next to an inline atom leaves them. let length = editor.display_length(); for at in (0..length).rev().step_by(3) { let _ = editor.command(&json!({"op":"display_edit","at":at,"length":0,"text":"z"})); } check_every_position(&editor, 1); } #[test] fn typing_anywhere_edits_exactly_that_display_position() { let mut editor = open(&generate(6, 600, 12), 301); let mut random = Random::new(5); for round in 0..200 { let before = display(&editor); let total = before.len() as u32; let at = random.below(total as u64) as u32; // Stay inside one text: never across a block end or an atom. let length = if round % 3 == 0 { (1..=3).take_while(|n| at + n < total && !before[(at as usize)..(at + n) as usize].iter().any(|u| [10, 0x2028, 0xFFFC].contains(u))).last().unwrap_or(0) } else { 0 }; if at > 0 && (0xDC00..0xE000).contains(&before[at as usize]) { continue; } if (0xDC00..0xE000).contains(&before[(at + length) as usize]) { continue; } let text = ["k", "é", "😀", "two words"][round % 4]; editor.command(&json!({"op":"display_edit","at":at,"length":length,"text":text})).unwrap_or_else(|e| panic!("edit {at}+{length}: {e}")); let mut expected = before[..at as usize].to_vec(); expected.extend(text.encode_utf16()); expected.extend(&before[(at + length) as usize..]); assert_eq!(display(&editor), expected, "round {round}: {at}+{length} {text}"); } } #[test] fn a_text_holding_an_embed_maps_one_position_per_unit() { // Yjs editors never embed values in a text, but a peer can. The display // shows the embed as one U+FFFC, so display offsets stay yrs offsets. use yrs::{Any, Doc, ReadTxn, StateVector, Text, Transact, XmlElementPrelim, XmlFragment, XmlTextPrelim, XmlOut}; let doc = Doc::with_options({ let mut o = yrs::Options::with_guid_and_client_id("embed".into(), 7); o.offset_kind = yrs::OffsetKind::Utf16; o }); let root = doc.get_or_insert_xml_fragment("prosemirror"); { let mut txn = doc.transact_mut(); let paragraph = root.insert(&mut txn, 0, XmlElementPrelim::empty("paragraph")); let text = paragraph.insert(&mut txn, 0, XmlTextPrelim::new("abcd")); text.insert_embed(&mut txn, 2, Any::from(std::collections::HashMap::from([("k".to_owned(), Any::from("v"))]))); let _ = XmlOut::Text(text); } let bytes = doc.transact().encode_state_as_update_v1(&StateVector::default()); let mut editor = Editor::new("embed", 8); editor.apply(&bytes).unwrap(); assert_eq!(display(&editor), "ab\u{FFFC}cd\n".encode_utf16().collect::>()); assert_eq!(editor.display_length(), 6); check_every_position(&editor, 1); editor.command(&json!({"op":"display_edit","at":4,"length":0,"text":"X"})).unwrap(); assert_eq!(display(&editor), "ab\u{FFFC}cXd\n".encode_utf16().collect::>()); } #[test] fn projection_is_unchanged_for_documents_without_embeds() { for (pages, edits) in [(1, 0), (3, 300), (10, 1200)] { let bytes = generate(pages, edits, 13); let editor = open(&bytes, 401); assert_eq!(editor.projection()["children"], support::legacy_projection(&editor.snapshot())["children"], "{pages} pages, {edits} edits"); } }