use docs_core::abi::{ build_slice, doc_free, doc_new, json_string, ERR_BUILD_LIMIT, ERR_BUILD_MALFORMED, ERR_BUILD_NOT_EMPTY, ERR_NO_DOC, }; use docs_core::build::{build, BuildError, MAX_BLOCKS, VERSION}; use docs_core::{apply_update, fragment_html, fragment_json, snapshot_bytes, FRAGMENT_ROOT}; use yrs::branch::{Branch, BranchPtr}; use yrs::{Any, Doc, Map, MapRef, Options, Out, Text, Transact, XmlFragment, XmlOut}; fn fresh() -> Doc { Doc::with_options(Options::with_guid_and_client_id("build-test".into(), 9)) } /// A run: its marks and its text. type Run<'a> = (&'a [&'a str], &'a str); /// A block: its kind, its level (headings only) and its runs. type Block<'a> = (u8, u8, &'a [Run<'a>]); /// The instruction list for `blocks`. fn ops(blocks: &[Block]) -> Vec { let mut out = vec![VERSION]; out.extend((blocks.len() as u32).to_le_bytes()); for (kind, level, runs) in blocks { out.push(*kind); if *kind == 2 { out.push(*level); } out.extend((runs.len() as u32).to_le_bytes()); for (marks, text) in runs.iter() { out.push(marks.len() as u8); for m in marks.iter() { out.push(m.len() as u8); out.extend(m.as_bytes()); } out.extend((text.len() as u32).to_le_bytes()); out.extend(text.as_bytes()); } } out } #[test] fn builds_paragraphs_headings_and_marks() { let doc = fresh(); build( &doc, &ops(&[ (2, 2, &[(&[], "Title")]), ( 1, 0, &[ (&[], "Plain "), (&["strong"], "bold"), (&[], " then "), (&["em", "font_sans", "size_14"], "styled"), ], ), (1, 0, &[]), ]), ) .unwrap(); assert_eq!( fragment_json(&doc), r#"{"type":"doc","content":[{"type":"heading","attrs":{"level":2},"content":[{"type":"text","text":"Title"}]},{"type":"paragraph","content":[{"type":"text","text":"Plain "},{"type":"text","text":"bold","marks":[{"type":"strong"}]},{"type":"text","text":" then "},{"type":"text","text":"styled","marks":[{"type":"font_sans"},{"type":"size_14"},{"type":"em"}]}]},{"type":"paragraph","content":[]}]}"# ); assert_eq!( fragment_html(&doc), "

Title

Plain bold then styled

" ); } /// y-prosemirror writes a heading's level as a number and the editor's /// schema validates it as one; a string level is what yrs' own XML /// attribute calls would have written. #[test] fn a_heading_level_is_a_number() { let doc = fresh(); build(&doc, &ops(&[(2, 3, &[(&[], "H")])])).unwrap(); let root = doc.get_or_insert_xml_fragment(FRAGMENT_ROOT); let txn = doc.transact(); let Some(XmlOut::Element(h)) = root.get(&txn, 0) else { panic!("no heading") }; let level = MapRef::from(BranchPtr::from(AsRef::::as_ref(&h))).get(&txn, "level"); assert!( matches!(level, Some(Out::Any(Any::Number(n))) if n == 3.0), "level {level:?}" ); } /// An empty block has no child at all, as y-prosemirror writes one; and /// a block's runs share one XmlText. #[test] fn one_text_per_block_and_none_when_empty() { let doc = fresh(); build( &doc, &ops(&[(1, 0, &[(&[], "a"), (&["strong"], "b")]), (1, 0, &[])]), ) .unwrap(); let root = doc.get_or_insert_xml_fragment(FRAGMENT_ROOT); let txn = doc.transact(); let lens: Vec = root .children(&txn) .map(|c| match c { XmlOut::Element(e) => e.len(&txn), _ => panic!("not an element"), }) .collect(); assert_eq!(lens, vec![1, 0]); } #[test] fn an_unmarked_run_after_a_marked_one_inherits_nothing() { let doc = fresh(); build( &doc, &ops(&[(1, 0, &[(&["strong"], "a"), (&[], "b"), (&["em"], "c")])]), ) .unwrap(); assert_eq!(fragment_html(&doc), "

abc

"); } #[test] fn adjacent_runs_with_the_same_marks_merge() { let doc = fresh(); build( &doc, &ops(&[(1, 0, &[(&["strong", "em"], "a"), (&["em", "strong"], "b")])]), ) .unwrap(); let root = doc.get_or_insert_xml_fragment(FRAGMENT_ROOT); let txn = doc.transact(); let Some(XmlOut::Element(p)) = root.get(&txn, 0) else { panic!() }; let Some(XmlOut::Text(t)) = p.get(&txn, 0) else { panic!() }; assert_eq!(t.diff(&txn, yrs::types::text::YChange::identity).len(), 1); } /// Every refusal leaves the document exactly as it was. #[test] fn refuses_malformed_lists_and_writes_nothing() { let good = ops(&[(1, 0, &[(&[], "x")])]); let mut wrong_version = good.clone(); wrong_version[0] = 2; let mut trailing = good.clone(); trailing.push(0); let truncated = good[..good.len() - 1].to_vec(); let mut bad_utf8 = good.clone(); *bad_utf8.last_mut().unwrap() = 0xff; let cases: Vec<(&str, Vec)> = vec![ ("empty input", vec![]), ("wrong version", wrong_version), ("trailing bytes", trailing), ("truncated", truncated), ("invalid utf-8", bad_utf8), ("unknown kind", { let mut v = good.clone(); v[5] = 3; v }), ("level 0", ops(&[(2, 0, &[(&[], "x")])])), ("level 7", ops(&[(2, 7, &[(&[], "x")])])), ("unknown mark", ops(&[(1, 0, &[(&["link"], "x")])])), ("retired size", ops(&[(1, 0, &[(&["size_lg"], "x")])])), ("code", ops(&[(1, 0, &[(&["code"], "x")])])), ( "two fonts", ops(&[(1, 0, &[(&["font_sans", "font_serif"], "x")])]), ), ("two sizes", ops(&[(1, 0, &[(&["size_8", "size_9"], "x")])])), ("same mark twice", ops(&[(1, 0, &[(&["em", "em"], "x")])])), ("empty text", ops(&[(1, 0, &[(&[], "")])])), ("tab", ops(&[(1, 0, &[(&[], "a\tb")])])), ("newline", ops(&[(1, 0, &[(&[], "a\nb")])])), ("nul", ops(&[(1, 0, &[(&[], "a\0b")])])), ( "a good block, then a bad one", ops(&[(1, 0, &[(&[], "fine")]), (1, 0, &[(&[], "")])]), ), ]; for (name, bytes) in cases { let doc = fresh(); let before = snapshot_bytes(&doc); assert_eq!(build(&doc, &bytes), Err(BuildError::Malformed), "{name}"); assert_eq!(snapshot_bytes(&doc), before, "{name} wrote something"); assert_eq!( fragment_json(&doc), r#"{"type":"doc","content":[]}"#, "{name}" ); } } #[test] fn refuses_past_its_limits() { let mut v = vec![VERSION]; v.extend((MAX_BLOCKS + 1).to_le_bytes()); assert_eq!(build(&fresh(), &v), Err(BuildError::Limit)); let mut v = vec![VERSION]; v.extend(1u32.to_le_bytes()); v.push(1); v.extend(u32::MAX.to_le_bytes()); assert_eq!(build(&fresh(), &v), Err(BuildError::Limit)); let big = vec![0u8; docs_core::build::MAX_INPUT + 1]; assert_eq!(build(&fresh(), &big), Err(BuildError::Limit)); } /// An update written under a client id past 2^53 - 1 decodes in yrs and /// in no browser (lib0 refuses the varuint), so the builder refuses to /// write under one at all. #[test] fn refuses_a_client_id_a_browser_cannot_read() { let list = ops(&[(1, 0, &[(&[], "x")])]); for id in [docs_core::build::MAX_SAFE_CLIENT_ID + 1, u64::MAX >> 1] { let doc = Doc::with_options(Options::with_guid_and_client_id("build-test".into(), id)); let before = snapshot_bytes(&doc); assert_eq!(build(&doc, &list), Err(BuildError::UnsafeClientId)); assert_eq!(snapshot_bytes(&doc), before); } let doc = Doc::with_options(Options::with_guid_and_client_id( "build-test".into(), docs_core::build::MAX_SAFE_CLIENT_ID, )); build(&doc, &list).unwrap(); } #[test] fn writes_only_into_an_empty_document() { let doc = fresh(); let list = ops(&[(1, 0, &[(&[], "x")])]); build(&doc, &list).unwrap(); let before = snapshot_bytes(&doc); assert_eq!(build(&doc, &list), Err(BuildError::NotEmpty)); assert_eq!(snapshot_bytes(&doc), before); } /// What is built replays, from its snapshot, into a second document as /// the same structure: the check the host makes before saving. #[test] fn the_snapshot_replays_to_the_same_structure() { let doc = fresh(); build( &doc, &ops(&[ (2, 1, &[(&["font_caladea"], "Über 🦀")]), (1, 0, &[(&["size_11"], "x")]), ]), ) .unwrap(); let replay = Doc::with_options(Options::with_guid_and_client_id("build-test".into(), 10)); apply_update(&replay, &snapshot_bytes(&doc)).unwrap(); assert_eq!(fragment_json(&replay), fragment_json(&doc)); } #[test] fn the_abi_reports_each_refusal_as_its_own_code() { let h = doc_new("abi-build", 3); assert_eq!(build_slice(h, &[]), ERR_BUILD_MALFORMED); let mut v = vec![VERSION]; v.extend((MAX_BLOCKS + 1).to_le_bytes()); assert_eq!(build_slice(h, &v), ERR_BUILD_LIMIT); assert_eq!(build_slice(h, &ops(&[(1, 0, &[(&[], "x")])])), 0); assert_eq!( build_slice(h, &ops(&[(1, 0, &[(&[], "x")])])), ERR_BUILD_NOT_EMPTY ); assert_eq!( json_string(h).unwrap(), r#"{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"x"}]}]}"# ); doc_free(h); assert_eq!(build_slice(h, &ops(&[])), ERR_NO_DOC); }