oficina / docs Public

Clone
git clone https://amadan.net/oficina/docs

Plain git — no account needed to clone.

Download

Download this file

1use docs_core::abi::{
2 build_slice, doc_free, doc_new, json_string, ERR_BUILD_LIMIT, ERR_BUILD_MALFORMED,
3 ERR_BUILD_NOT_EMPTY, ERR_NO_DOC,
4};
5use docs_core::build::{build, BuildError, MAX_BLOCKS, VERSION};
6use docs_core::{apply_update, fragment_html, fragment_json, snapshot_bytes, FRAGMENT_ROOT};
7use yrs::branch::{Branch, BranchPtr};
8use yrs::{Any, Doc, Map, MapRef, Options, Out, Text, Transact, XmlFragment, XmlOut};
9
10fn fresh() -> Doc {
11 Doc::with_options(Options::with_guid_and_client_id("build-test".into(), 9))
12}
13
14/// A run: its marks and its text.
15type Run<'a> = (&'a [&'a str], &'a str);
16/// A block: its kind, its level (headings only) and its runs.
17type Block<'a> = (u8, u8, &'a [Run<'a>]);
18
19/// The instruction list for `blocks`.
20fn ops(blocks: &[Block]) -> Vec<u8> {
21 let mut out = vec![VERSION];
22 out.extend((blocks.len() as u32).to_le_bytes());
23 for (kind, level, runs) in blocks {
24 out.push(*kind);
25 if *kind == 2 {
26 out.push(*level);
27 }
28 out.extend((runs.len() as u32).to_le_bytes());
29 for (marks, text) in runs.iter() {
30 out.push(marks.len() as u8);
31 for m in marks.iter() {
32 out.push(m.len() as u8);
33 out.extend(m.as_bytes());
34 }
35 out.extend((text.len() as u32).to_le_bytes());
36 out.extend(text.as_bytes());
37 }
38 }
39 out
40}
41
42#[test]
43fn builds_paragraphs_headings_and_marks() {
44 let doc = fresh();
45 build(
46 &doc,
47 &ops(&[
48 (2, 2, &[(&[], "Title")]),
49 (
50 1,
51 0,
52 &[
53 (&[], "Plain "),
54 (&["strong"], "bold"),
55 (&[], " then "),
56 (&["em", "font_sans", "size_14"], "styled"),
57 ],
58 ),
59 (1, 0, &[]),
60 ]),
61 )
62 .unwrap();
63 assert_eq!(
64 fragment_json(&doc),
65 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":[]}]}"#
66 );
67 assert_eq!(
68 fragment_html(&doc),
69 "<h2>Title</h2><p>Plain <strong>bold</strong> then <span class=\"docs-font-sans\"><span class=\"docs-size-14\"><em>styled</em></span></span></p><p></p>"
70 );
71}
72
73/// y-prosemirror writes a heading's level as a number and the editor's
74/// schema validates it as one; a string level is what yrs' own XML
75/// attribute calls would have written.
76#[test]
77fn a_heading_level_is_a_number() {
78 let doc = fresh();
79 build(&doc, &ops(&[(2, 3, &[(&[], "H")])])).unwrap();
80 let root = doc.get_or_insert_xml_fragment(FRAGMENT_ROOT);
81 let txn = doc.transact();
82 let Some(XmlOut::Element(h)) = root.get(&txn, 0) else {
83 panic!("no heading")
84 };
85 let level = MapRef::from(BranchPtr::from(AsRef::<Branch>::as_ref(&h))).get(&txn, "level");
86 assert!(
87 matches!(level, Some(Out::Any(Any::Number(n))) if n == 3.0),
88 "level {level:?}"
89 );
90}
91
92/// An empty block has no child at all, as y-prosemirror writes one; and
93/// a block's runs share one XmlText.
94#[test]
95fn one_text_per_block_and_none_when_empty() {
96 let doc = fresh();
97 build(
98 &doc,
99 &ops(&[(1, 0, &[(&[], "a"), (&["strong"], "b")]), (1, 0, &[])]),
100 )
101 .unwrap();
102 let root = doc.get_or_insert_xml_fragment(FRAGMENT_ROOT);
103 let txn = doc.transact();
104 let lens: Vec<u32> = root
105 .children(&txn)
106 .map(|c| match c {
107 XmlOut::Element(e) => e.len(&txn),
108 _ => panic!("not an element"),
109 })
110 .collect();
111 assert_eq!(lens, vec![1, 0]);
112}
113
114#[test]
115fn an_unmarked_run_after_a_marked_one_inherits_nothing() {
116 let doc = fresh();
117 build(
118 &doc,
119 &ops(&[(1, 0, &[(&["strong"], "a"), (&[], "b"), (&["em"], "c")])]),
120 )
121 .unwrap();
122 assert_eq!(fragment_html(&doc), "<p><strong>a</strong>b<em>c</em></p>");
123}
124
125#[test]
126fn adjacent_runs_with_the_same_marks_merge() {
127 let doc = fresh();
128 build(
129 &doc,
130 &ops(&[(1, 0, &[(&["strong", "em"], "a"), (&["em", "strong"], "b")])]),
131 )
132 .unwrap();
133 let root = doc.get_or_insert_xml_fragment(FRAGMENT_ROOT);
134 let txn = doc.transact();
135 let Some(XmlOut::Element(p)) = root.get(&txn, 0) else {
136 panic!()
137 };
138 let Some(XmlOut::Text(t)) = p.get(&txn, 0) else {
139 panic!()
140 };
141 assert_eq!(t.diff(&txn, yrs::types::text::YChange::identity).len(), 1);
142}
143
144/// Every refusal leaves the document exactly as it was.
145#[test]
146fn refuses_malformed_lists_and_writes_nothing() {
147 let good = ops(&[(1, 0, &[(&[], "x")])]);
148 let mut wrong_version = good.clone();
149 wrong_version[0] = 2;
150 let mut trailing = good.clone();
151 trailing.push(0);
152 let truncated = good[..good.len() - 1].to_vec();
153 let mut bad_utf8 = good.clone();
154 *bad_utf8.last_mut().unwrap() = 0xff;
155 let cases: Vec<(&str, Vec<u8>)> = vec![
156 ("empty input", vec![]),
157 ("wrong version", wrong_version),
158 ("trailing bytes", trailing),
159 ("truncated", truncated),
160 ("invalid utf-8", bad_utf8),
161 ("unknown kind", {
162 let mut v = good.clone();
163 v[5] = 3;
164 v
165 }),
166 ("level 0", ops(&[(2, 0, &[(&[], "x")])])),
167 ("level 7", ops(&[(2, 7, &[(&[], "x")])])),
168 ("unknown mark", ops(&[(1, 0, &[(&["link"], "x")])])),
169 ("retired size", ops(&[(1, 0, &[(&["size_lg"], "x")])])),
170 ("code", ops(&[(1, 0, &[(&["code"], "x")])])),
171 (
172 "two fonts",
173 ops(&[(1, 0, &[(&["font_sans", "font_serif"], "x")])]),
174 ),
175 ("two sizes", ops(&[(1, 0, &[(&["size_8", "size_9"], "x")])])),
176 ("same mark twice", ops(&[(1, 0, &[(&["em", "em"], "x")])])),
177 ("empty text", ops(&[(1, 0, &[(&[], "")])])),
178 ("tab", ops(&[(1, 0, &[(&[], "a\tb")])])),
179 ("newline", ops(&[(1, 0, &[(&[], "a\nb")])])),
180 ("nul", ops(&[(1, 0, &[(&[], "a\0b")])])),
181 (
182 "a good block, then a bad one",
183 ops(&[(1, 0, &[(&[], "fine")]), (1, 0, &[(&[], "")])]),
184 ),
185 ];
186 for (name, bytes) in cases {
187 let doc = fresh();
188 let before = snapshot_bytes(&doc);
189 assert_eq!(build(&doc, &bytes), Err(BuildError::Malformed), "{name}");
190 assert_eq!(snapshot_bytes(&doc), before, "{name} wrote something");
191 assert_eq!(
192 fragment_json(&doc),
193 r#"{"type":"doc","content":[]}"#,
194 "{name}"
195 );
196 }
197}
198
199#[test]
200fn refuses_past_its_limits() {
201 let mut v = vec![VERSION];
202 v.extend((MAX_BLOCKS + 1).to_le_bytes());
203 assert_eq!(build(&fresh(), &v), Err(BuildError::Limit));
204
205 let mut v = vec![VERSION];
206 v.extend(1u32.to_le_bytes());
207 v.push(1);
208 v.extend(u32::MAX.to_le_bytes());
209 assert_eq!(build(&fresh(), &v), Err(BuildError::Limit));
210
211 let big = vec![0u8; docs_core::build::MAX_INPUT + 1];
212 assert_eq!(build(&fresh(), &big), Err(BuildError::Limit));
213}
214
215/// An update written under a client id past 2^53 - 1 decodes in yrs and
216/// in no browser (lib0 refuses the varuint), so the builder refuses to
217/// write under one at all.
218#[test]
219fn refuses_a_client_id_a_browser_cannot_read() {
220 let list = ops(&[(1, 0, &[(&[], "x")])]);
221 for id in [docs_core::build::MAX_SAFE_CLIENT_ID + 1, u64::MAX >> 1] {
222 let doc = Doc::with_options(Options::with_guid_and_client_id("build-test".into(), id));
223 let before = snapshot_bytes(&doc);
224 assert_eq!(build(&doc, &list), Err(BuildError::UnsafeClientId));
225 assert_eq!(snapshot_bytes(&doc), before);
226 }
227 let doc = Doc::with_options(Options::with_guid_and_client_id(
228 "build-test".into(),
229 docs_core::build::MAX_SAFE_CLIENT_ID,
230 ));
231 build(&doc, &list).unwrap();
232}
233
234#[test]
235fn writes_only_into_an_empty_document() {
236 let doc = fresh();
237 let list = ops(&[(1, 0, &[(&[], "x")])]);
238 build(&doc, &list).unwrap();
239 let before = snapshot_bytes(&doc);
240 assert_eq!(build(&doc, &list), Err(BuildError::NotEmpty));
241 assert_eq!(snapshot_bytes(&doc), before);
242}
243
244/// What is built replays, from its snapshot, into a second document as
245/// the same structure: the check the host makes before saving.
246#[test]
247fn the_snapshot_replays_to_the_same_structure() {
248 let doc = fresh();
249 build(
250 &doc,
251 &ops(&[
252 (2, 1, &[(&["font_caladea"], "Über 🦀")]),
253 (1, 0, &[(&["size_11"], "x")]),
254 ]),
255 )
256 .unwrap();
257 let replay = Doc::with_options(Options::with_guid_and_client_id("build-test".into(), 10));
258 apply_update(&replay, &snapshot_bytes(&doc)).unwrap();
259 assert_eq!(fragment_json(&replay), fragment_json(&doc));
260}
261
262#[test]
263fn the_abi_reports_each_refusal_as_its_own_code() {
264 let h = doc_new("abi-build", 3);
265 assert_eq!(build_slice(h, &[]), ERR_BUILD_MALFORMED);
266 let mut v = vec![VERSION];
267 v.extend((MAX_BLOCKS + 1).to_le_bytes());
268 assert_eq!(build_slice(h, &v), ERR_BUILD_LIMIT);
269 assert_eq!(build_slice(h, &ops(&[(1, 0, &[(&[], "x")])])), 0);
270 assert_eq!(
271 build_slice(h, &ops(&[(1, 0, &[(&[], "x")])])),
272 ERR_BUILD_NOT_EMPTY
273 );
274 assert_eq!(
275 json_string(h).unwrap(),
276 r#"{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"x"}]}]}"#
277 );
278 doc_free(h);
279 assert_eq!(build_slice(h, &ops(&[])), ERR_NO_DOC);
280}
281