forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

flat.rs655 lines, 23.2 KiBHistoryRawDownload
1//! The note layout: one LoroText, `doc.get_text("body")`.
2//!
3//! Every block is its content followed by [`SEP`], so a body always ends with one; a
4//! fresh note is a single `SEP` (one empty paragraph). Inside a block `'\n'` is a hard
5//! break, or a newline in code. An image is [`OBJ`] under an `image` mark. Inline marks
6//! (`strong`, `em`, `code`, `link`) may span separators (one mark over a styled run of
7//! blocks); readers ignore them there.
8//!
9//! Block attributes are marks read from the separator only, all with expand None:
10//! - `b`: `"h1"`..`"h6"`, `"code"` or `"hr"`; absent for a paragraph.
11//! - `lang`: the language of a code block.
12//! - `wrap`: the containers around the block, outermost first, one char per level:
13//! `q` blockquote, `u` bullet list, `o` ordered list.
14//! - `join`: how many levels the block shares with the previous one, when that is not
15//! the default (see [`default_join`]).
16//! - `start`: the number of an ordered list the block opens, when not 1.
17//!
18//! Marks of equal value on consecutive separators are one mark over the whole run, so
19//! a long list is a single `wrap` mark. Content chars inside that range carry the mark
20//! too, which readers ignore.
21
22use std::collections::HashMap;
23
24use loro::{LoroDoc, LoroResult, LoroText, LoroValue, TextDelta};
25
26use crate::marks::Marks;
27use crate::tree::value_str;
28use crate::write::{Block, Inline, apply_marks};
29
30pub const BODY: &str = "body";
31/// Ends every block.
32pub const SEP: char = '\u{2029}';
33pub const SEP_STR: &str = "\u{2029}";
34/// An image's place in the text; its attributes are the `image` mark.
35pub const OBJ: char = '\u{FFFC}';
36
37pub const KEY_KIND: &str = "b";
38pub const KEY_LANG: &str = "lang";
39pub const KEY_WRAP: &str = "wrap";
40pub const KEY_JOIN: &str = "join";
41pub const KEY_START: &str = "start";
42pub const KEY_IMAGE: &str = "image";
43/// Every key that lives on separators.
44pub const BLOCK_KEYS: [&str; 5] = [KEY_KIND, KEY_LANG, KEY_WRAP, KEY_JOIN, KEY_START];
45
46pub fn body(doc: &LoroDoc) -> LoroText {
47 doc.get_text(BODY)
48}
49
50#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default)]
51pub enum Kind {
52 #[default]
53 Para,
54 Heading(u8),
55 Code,
56 Rule,
57}
58
59impl Kind {
60 pub fn from_value(v: Option<&LoroValue>) -> Kind {
61 let Some(s) = v.and_then(|v| v.as_string()) else { return Kind::Para };
62 match s.as_str() {
63 "code" => Kind::Code,
64 "hr" => Kind::Rule,
65 h if h.len() == 2 && h.starts_with('h') => match h.as_bytes()[1] {
66 n @ b'1'..=b'6' => Kind::Heading(n - b'0'),
67 _ => Kind::Para,
68 },
69 _ => Kind::Para,
70 }
71 }
72
73 pub fn value(self) -> Option<LoroValue> {
74 let s = match self {
75 Kind::Para => return None,
76 Kind::Heading(n) => ["h1", "h2", "h3", "h4", "h5", "h6"][n.clamp(1, 6) as usize - 1],
77 Kind::Code => "code",
78 Kind::Rule => "hr",
79 };
80 Some(s.into())
81 }
82
83 /// Whether the block holds editable inline content.
84 pub fn is_text(self) -> bool {
85 self != Kind::Rule
86 }
87}
88
89#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
90pub enum Wrap {
91 Quote,
92 Bullet,
93 Ordered,
94}
95
96impl Wrap {
97 pub fn is_list(self) -> bool {
98 self != Wrap::Quote
99 }
100
101 fn char(self) -> char {
102 match self {
103 Wrap::Quote => 'q',
104 Wrap::Bullet => 'u',
105 Wrap::Ordered => 'o',
106 }
107 }
108
109 fn from_char(c: char) -> Option<Wrap> {
110 match c {
111 'q' => Some(Wrap::Quote),
112 'u' => Some(Wrap::Bullet),
113 'o' => Some(Wrap::Ordered),
114 _ => None,
115 }
116 }
117}
118
119pub fn wrap_from_value(v: Option<&LoroValue>) -> Vec<Wrap> {
120 v.and_then(|v| v.as_string()).map(|s| s.chars().filter_map(Wrap::from_char).collect()).unwrap_or_default()
121}
122
123pub fn wrap_value(wrap: &[Wrap]) -> Option<LoroValue> {
124 (!wrap.is_empty()).then(|| wrap.iter().map(|w| w.char()).collect::<String>().into())
125}
126
127/// The attributes of a block, from its separator.
128#[derive(Clone, PartialEq, Eq, Hash, Debug, Default)]
129pub struct Attrs {
130 pub kind: Kind,
131 pub lang: Option<String>,
132 pub wrap: Vec<Wrap>,
133 pub join: Option<usize>,
134 pub start: Option<i64>,
135}
136
137impl Attrs {
138 pub fn from_map<S: std::hash::BuildHasher>(attrs: Option<&HashMap<String, LoroValue, S>>) -> Attrs {
139 let mut out = Attrs::default();
140 for (k, v) in attrs.into_iter().flatten() {
141 out.set(k, v);
142 }
143 out
144 }
145
146 /// Applies one key of a separator's marks; null or a foreign key clears or does
147 /// nothing. Returns whether `key` is a block key.
148 pub fn set(&mut self, key: &str, v: &LoroValue) -> bool {
149 let num = |v: &LoroValue| match v {
150 LoroValue::I64(i) => Some(*i),
151 LoroValue::Double(d) => Some(*d as i64),
152 _ => None,
153 };
154 match key {
155 KEY_KIND => self.kind = Kind::from_value(Some(v)),
156 KEY_LANG => self.lang = value_str(v).filter(|l| !l.is_empty()),
157 KEY_WRAP => self.wrap = wrap_from_value(Some(v)),
158 KEY_JOIN => self.join = num(v).map(|j| j.max(0) as usize),
159 KEY_START => self.start = num(v),
160 _ => return false,
161 }
162 true
163 }
164
165 /// The value of each of [`BLOCK_KEYS`], None when unset.
166 pub fn values(&self) -> [Option<LoroValue>; 5] {
167 [
168 self.kind.value(),
169 self.lang.as_deref().map(LoroValue::from),
170 wrap_value(&self.wrap),
171 self.join.map(|j| LoroValue::from(j as i64)),
172 self.start.filter(|&s| s != 1).map(LoroValue::from),
173 ]
174 }
175}
176
177/// One block of the body: its attributes and content. Code content is one text run.
178#[derive(Clone, PartialEq, Debug, Default)]
179pub struct FlatBlock {
180 pub attrs: Attrs,
181 pub inl: Vec<Inline>,
182 /// UTF-16 length including the separator.
183 pub len16: usize,
184 /// Unicode scalars including the separator (Loro's text positions).
185 pub lenu: usize,
186}
187
188impl FlatBlock {
189 pub fn plain(&self) -> String {
190 let mut s = String::new();
191 for i in &self.inl {
192 match i {
193 Inline::Text(t, _) => s.push_str(t),
194 Inline::HardBreak => s.push('\n'),
195 Inline::Image { .. } => {}
196 }
197 }
198 s
199 }
200}
201
202/// How many levels a block shares with the previous one when its `join` is unset:
203/// within the common wrap prefix, everything above the deepest list, so the block is
204/// the next item of that list. Without a list in common, the whole common prefix.
205pub fn default_join(prev: &[Wrap], cur: &[Wrap]) -> usize {
206 let common = prev.iter().zip(cur).take_while(|(a, b)| a == b).count();
207 match cur[..common].iter().rposition(|w| w.is_list()) {
208 Some(d) => d,
209 None => common,
210 }
211}
212
213// ---------------------------------------------------------------------------
214// Reading
215// ---------------------------------------------------------------------------
216
217/// Unicode scalars and UTF-16 units of `s`. ASCII, nearly all text, counts as bytes.
218pub fn str_lens(s: &str) -> (usize, usize) {
219 // Lead bytes count chars, 4-byte leads count surrogate pairs; ASCII chunks are skipped.
220 let (mut unicode, mut wide) = (0, 0);
221 for c in s.as_bytes().chunks(4096) {
222 if c.is_ascii() {
223 unicode += c.len();
224 continue;
225 }
226 for &b in c {
227 unicode += ((b as i8) >= -0x40) as usize;
228 wide += (b >= 0xF0) as usize;
229 }
230 }
231 (unicode, unicode + wide)
232}
233
234/// Every block of the body.
235pub fn read(text: &LoroText) -> Vec<FlatBlock> {
236 read_delta(text.to_delta())
237}
238
239pub fn read_doc(doc: &LoroDoc) -> Vec<FlatBlock> {
240 read(&body(doc))
241}
242
243/// Blocks from rich-text delta runs, split at separators. Content after the last
244/// separator, which concurrent edits can leave, is a last paragraph.
245pub fn read_delta(delta: Vec<TextDelta>) -> Vec<FlatBlock> {
246 let mut out = Vec::new();
247 let mut cur = FlatBlock::default();
248 // The current block's text in runs of equal marks, split into inlines once its
249 // separator gives its kind: a code block stays one text however many lines it has.
250 let mut runs: Vec<(String, Marks, Option<LoroValue>)> = Vec::new();
251 for d in delta {
252 let TextDelta::Insert { insert, attributes } = d else { continue };
253 let attrs = attributes.as_ref();
254 let marks = attrs.map(Marks::from_attrs).unwrap_or_default();
255 let image = attrs.and_then(|a| a.get(KEY_IMAGE)).filter(|v| !matches!(v, LoroValue::Null));
256 for (i, piece) in insert.split(SEP).enumerate() {
257 if i > 0 {
258 cur.attrs = Attrs::from_map(attrs);
259 cur.len16 += 1;
260 cur.lenu += 1;
261 finish_block(&mut cur, &mut runs);
262 out.push(std::mem::take(&mut cur));
263 }
264 if piece.is_empty() {
265 continue;
266 }
267 let (u, u16) = str_lens(piece);
268 cur.len16 += u16;
269 cur.lenu += u;
270 match runs.last_mut() {
271 Some((t, m, img)) if *m == marks && img.as_ref() == image => t.push_str(piece),
272 _ => runs.push((piece.to_owned(), marks.clone(), image.cloned())),
273 }
274 }
275 }
276 if !runs.is_empty() {
277 finish_block(&mut cur, &mut runs);
278 out.push(cur);
279 }
280 out
281}
282
283/// Turns the text `runs` of a block into its inlines. A code block's is its plain text.
284fn finish_block(b: &mut FlatBlock, runs: &mut Vec<(String, Marks, Option<LoroValue>)>) {
285 if b.attrs.kind == Kind::Code {
286 let mut text = String::new();
287 for (t, _, image) in runs.drain(..) {
288 match image {
289 Some(_) => text.extend(t.chars().filter(|&c| c != OBJ)),
290 None if text.is_empty() => text = t,
291 None => text.push_str(&t),
292 }
293 }
294 if !text.is_empty() {
295 b.inl.push(Inline::Text(text, Marks::default()));
296 }
297 return;
298 }
299 for (t, marks, image) in runs.drain(..) {
300 push_piece(b, &t, &marks, image.as_ref());
301 }
302}
303
304fn push_piece(b: &mut FlatBlock, piece: &str, marks: &Marks, image: Option<&LoroValue>) {
305 let text = |s: &str, b: &mut FlatBlock| {
306 if s.is_empty() {
307 return;
308 }
309 match b.inl.last_mut() {
310 Some(Inline::Text(t, m)) if m == marks => t.push_str(s),
311 _ => b.inl.push(Inline::Text(s.to_owned(), marks.clone())),
312 }
313 };
314 let mut rest = piece;
315 loop {
316 let stop = rest.find(|c| c == '\n' || (c == OBJ && image.is_some()));
317 let Some(at) = stop else {
318 text(rest, b);
319 return;
320 };
321 text(&rest[..at], b);
322 let c = rest[at..].chars().next().unwrap();
323 if c == '\n' {
324 b.inl.push(Inline::HardBreak);
325 } else if let Some(v) = image {
326 let get = |k: &str| v.get_by_key(k).and_then(value_str);
327 b.inl.push(Inline::Image {
328 src: get("src").unwrap_or_default(),
329 alt: get("alt").unwrap_or_default(),
330 title: get("title").filter(|t| !t.is_empty()),
331 });
332 }
333 rest = &rest[at + c.len_utf8()..];
334 }
335}
336
337/// Rebuilds the block tree from flat blocks.
338pub fn nest(blocks: &[FlatBlock]) -> Vec<Block> {
339 // The open containers, outermost first: their wrap and the blocks so far. A list
340 // collects items; `Open::items` holds them, the last one open.
341 struct Open {
342 wrap: Wrap,
343 start: i64,
344 items: Vec<Vec<Block>>,
345 }
346 fn close(open: Open) -> Block {
347 match open.wrap {
348 Wrap::Quote => Block::Quote(open.items.into_iter().next().unwrap_or_default()),
349 w => Block::List { ordered: w == Wrap::Ordered, start: open.start, items: open.items },
350 }
351 }
352 fn target<'a>(root: &'a mut Vec<Block>, stack: &'a mut [Open]) -> &'a mut Vec<Block> {
353 match stack.last_mut() {
354 Some(o) => o.items.last_mut().unwrap(),
355 None => root,
356 }
357 }
358 fn pop(root: &mut Vec<Block>, stack: &mut Vec<Open>) {
359 let o = stack.pop().unwrap();
360 let b = close(o);
361 target(root, stack).push(b);
362 }
363
364 let mut root = Vec::new();
365 let mut stack: Vec<Open> = Vec::new();
366 for b in blocks {
367 let wrap = &b.attrs.wrap;
368 let prev: Vec<Wrap> = stack.iter().map(|o| o.wrap).collect();
369 let common = prev.iter().zip(wrap).take_while(|(a, c)| a == c).count();
370 let keep = b.attrs.join.unwrap_or_else(|| default_join(&prev, wrap)).min(common);
371 // Levels below `keep` stay; at `keep`, a list in common gets a new item.
372 let new_item = keep < common && wrap[keep].is_list();
373 let stay = if new_item { keep + 1 } else { keep };
374 while stack.len() > stay {
375 pop(&mut root, &mut stack);
376 }
377 if new_item {
378 stack[keep].items.push(Vec::new());
379 }
380 let deepest_new_ordered = (stack.len()..wrap.len()).rev().find(|&i| wrap[i] == Wrap::Ordered);
381 for (i, &w) in wrap.iter().enumerate().skip(stack.len()) {
382 let start = if Some(i) == deepest_new_ordered { b.attrs.start.unwrap_or(1) } else { 1 };
383 stack.push(Open { wrap: w, start, items: vec![Vec::new()] });
384 }
385 target(&mut root, &mut stack).push(leaf(b));
386 }
387 while !stack.is_empty() {
388 pop(&mut root, &mut stack);
389 }
390 root
391}
392
393fn leaf(b: &FlatBlock) -> Block {
394 match b.attrs.kind {
395 Kind::Para => Block::Paragraph(b.inl.clone()),
396 Kind::Heading(n) => Block::Heading(n as i64, b.inl.clone()),
397 Kind::Code => Block::Code { lang: b.attrs.lang.clone(), text: b.plain() },
398 Kind::Rule => Block::Rule,
399 }
400}
401
402/// The note's block tree.
403pub fn doc_blocks(doc: &LoroDoc) -> Vec<Block> {
404 nest(&read_doc(doc))
405}
406
407// ---------------------------------------------------------------------------
408// Writing
409// ---------------------------------------------------------------------------
410
411/// Flattens a block tree. Every container gets at least one block, so an empty quote
412/// or list item survives as an empty paragraph.
413pub fn flatten(blocks: &[Block]) -> Vec<FlatBlock> {
414 // Each level of the path: wrap, container instance, item index.
415 type Level = (Wrap, usize, usize);
416 struct Cx {
417 out: Vec<FlatBlock>,
418 prev: Vec<Level>,
419 next_id: usize,
420 /// The ordered list a block opens, set until its first leaf.
421 start: Option<i64>,
422 }
423 fn walk(cx: &mut Cx, path: &mut Vec<Level>, blocks: &[Block]) {
424 if blocks.is_empty() {
425 emit(cx, path, Kind::Para, None, Vec::new());
426 }
427 for b in blocks {
428 match b {
429 Block::Paragraph(inl) => emit(cx, path, Kind::Para, None, inl.clone()),
430 Block::Heading(n, inl) => emit(cx, path, Kind::Heading((*n).clamp(1, 6) as u8), None, inl.clone()),
431 Block::Code { lang, text } => {
432 let inl = if text.is_empty() { Vec::new() } else { vec![Inline::Text(text.clone(), Marks::default())] };
433 emit(cx, path, Kind::Code, lang.clone().filter(|l| !l.is_empty()), inl)
434 }
435 Block::Rule => emit(cx, path, Kind::Rule, None, Vec::new()),
436 Block::Quote(inner) => {
437 cx.next_id += 1;
438 path.push((Wrap::Quote, cx.next_id, 0));
439 walk(cx, path, inner);
440 path.pop();
441 }
442 Block::List { ordered, start, items } => {
443 if items.is_empty() {
444 continue;
445 }
446 cx.next_id += 1;
447 let w = if *ordered { Wrap::Ordered } else { Wrap::Bullet };
448 if *ordered && *start != 1 {
449 cx.start = Some(*start);
450 }
451 for (i, item) in items.iter().enumerate() {
452 path.push((w, cx.next_id, i));
453 walk(cx, path, item);
454 path.pop();
455 }
456 }
457 }
458 }
459 }
460 fn emit(cx: &mut Cx, path: &[Level], kind: Kind, lang: Option<String>, inl: Vec<Inline>) {
461 // Levels in the same container and item as the previous block. At the next level
462 // `nest` starts a new item when both are lists of one kind, else new containers.
463 let same = cx.prev.iter().zip(path).take_while(|(a, b)| a == b).count();
464 let wrap: Vec<Wrap> = path.iter().map(|l| l.0).collect();
465 let prev: Vec<Wrap> = cx.prev.iter().map(|l| l.0).collect();
466 let attrs = Attrs {
467 kind,
468 lang,
469 join: (same != default_join(&prev, &wrap)).then_some(same),
470 start: cx.start.take(),
471 wrap,
472 };
473 cx.out.push(FlatBlock { attrs, inl, len16: 0, lenu: 0 });
474 cx.prev = path.to_vec();
475 }
476 let mut cx = Cx { out: Vec::new(), prev: Vec::new(), next_id: 0, start: None };
477 walk(&mut cx, &mut Vec::new(), blocks);
478 cx.out
479}
480
481/// The text of `blocks` and its marks, as [`write`] inserts them. Positions are
482/// Unicode scalars from the start of the text.
483pub struct Built {
484 pub text: String,
485 /// Inline mark runs: range and marks.
486 pub inline: Vec<(std::ops::Range<usize>, Marks)>,
487 pub images: Vec<(usize, LoroValue)>,
488 /// The separator position and attributes of each block.
489 pub seps: Vec<(usize, [Option<LoroValue>; 5])>,
490}
491
492pub fn build(blocks: &[FlatBlock]) -> Built {
493 let mut b = Built { text: String::new(), inline: Vec::new(), images: Vec::new(), seps: Vec::with_capacity(blocks.len()) };
494 let mut pos = 0usize;
495 let push = |b: &mut Built, s: &str, pos: &mut usize| {
496 for c in s.chars() {
497 b.text.push(if c == SEP { '\n' } else { c });
498 }
499 let n = s.chars().count();
500 *pos += n;
501 n
502 };
503 for block in blocks {
504 for i in &block.inl {
505 match i {
506 Inline::Text(s, m) => {
507 let start = pos;
508 let n = push(&mut b, s, &mut pos);
509 if n > 0 && *m != Marks::default() && block.attrs.kind != Kind::Code {
510 b.inline.push((start..pos, m.clone()));
511 }
512 }
513 Inline::HardBreak => {
514 push(&mut b, "\n", &mut pos);
515 }
516 Inline::Image { src, alt, title } => {
517 let mut map: HashMap<String, LoroValue> = HashMap::new();
518 map.insert("src".into(), src.as_str().into());
519 map.insert("alt".into(), alt.as_str().into());
520 if let Some(t) = title {
521 map.insert("title".into(), t.as_str().into());
522 }
523 b.images.push((pos, map.into()));
524 b.text.push(OBJ);
525 pos += 1;
526 }
527 }
528 }
529 b.seps.push((pos, block.attrs.values()));
530 b.text.push(SEP);
531 pos += 1;
532 }
533 b
534}
535
536/// Inserts `blocks` at Unicode position `at` and returns the inserted length. With
537/// `clean`, marks the surrounding text would lend the new text are cleared first.
538pub fn write(text: &LoroText, at: usize, blocks: &[FlatBlock], clean: bool) -> LoroResult<usize> {
539 let built = build(blocks);
540 if built.text.is_empty() {
541 return Ok(0);
542 }
543 text.insert(at, &built.text)?;
544 let end = at + built.seps.last().map_or(0, |s| s.0 + 1);
545 if clean {
546 for key in BLOCK_KEYS.iter().chain(&["strong", "em", "code", "link", KEY_IMAGE]) {
547 text.unmark(at..end, key)?;
548 }
549 }
550 for (range, marks) in &built.inline {
551 apply_marks(text, at + range.start..at + range.end, marks)?;
552 }
553 for (pos, v) in &built.images {
554 text.mark(at + pos..at + pos + 1, KEY_IMAGE, v.clone())?;
555 }
556 mark_seps(text, at, &built.seps)?;
557 Ok(end - at)
558}
559
560/// Marks block attributes on separators, one mark per run of equal values.
561pub fn mark_seps(text: &LoroText, at: usize, seps: &[(usize, [Option<LoroValue>; 5])]) -> LoroResult<()> {
562 for (k, key) in BLOCK_KEYS.iter().enumerate() {
563 let mut i = 0;
564 while i < seps.len() {
565 let Some(v) = &seps[i].1[k] else {
566 i += 1;
567 continue;
568 };
569 let mut j = i + 1;
570 while j < seps.len() && seps[j].1[k].as_ref() == Some(v) {
571 j += 1;
572 }
573 text.mark(at + seps[i].0..at + seps[j - 1].0 + 1, key, v.clone())?;
574 i = j;
575 }
576 }
577 Ok(())
578}
579
580/// A new doc's body: one empty paragraph.
581pub fn init(doc: &LoroDoc) -> LoroResult<()> {
582 let text = body(doc);
583 if text.len_unicode() == 0 {
584 text.insert(0, SEP_STR)?;
585 }
586 Ok(())
587}
588
589// ---------------------------------------------------------------------------
590// Queries
591// ---------------------------------------------------------------------------
592
593/// Plain text of the first non-blank block. Reads the head of the body first, so a
594/// huge note costs no more than its start.
595pub fn first_text(doc: &LoroDoc) -> String {
596 let text = body(doc);
597 let len = text.len_unicode();
598 let mut head = 4096usize;
599 loop {
600 let n = head.min(len);
601 let delta = text.slice_delta(0, n, loro::cursor::PosType::Unicode).unwrap_or_default();
602 let mut blocks = read_delta(delta);
603 // The last block may be cut off unless the whole body was read.
604 if n < len {
605 blocks.pop();
606 }
607 if let Some(b) = blocks.iter().find(|b| b.attrs.kind.is_text() && !b.plain().trim().is_empty()) {
608 return b.plain();
609 }
610 if n == len {
611 return String::new();
612 }
613 head *= 16;
614 }
615}
616
617#[cfg(test)]
618mod tests {
619 use super::*;
620
621 fn p(s: &str) -> Block {
622 Block::Paragraph(vec![Inline::Text(s.into(), Marks::default())])
623 }
624 fn ul(items: Vec<Vec<Block>>) -> Block {
625 Block::List { ordered: false, start: 1, items }
626 }
627
628 #[test]
629 fn round_trip() {
630 let bold = Marks { strong: true, ..Marks::default() };
631 let tree = vec![
632 Block::Heading(2, vec![Inline::Text("Title".into(), Marks::default())]),
633 Block::Paragraph(vec![
634 Inline::Text("a ".into(), Marks::default()),
635 Inline::Text("bold".into(), bold),
636 Inline::HardBreak,
637 Inline::Image { src: "x.png".into(), alt: "x".into(), title: None },
638 ]),
639 ul(vec![vec![p("one"), ul(vec![vec![p("nested")], vec![p("nested 2")]])], vec![p("two"), p("two b")], vec![p("three")]]),
640 Block::List { ordered: true, start: 3, items: vec![vec![p("c")], vec![Block::Quote(vec![p("q1"), p("q2")])], vec![Block::Quote(vec![p("q3")])]] },
641 Block::Quote(vec![p("quoted"), ul(vec![vec![p("in quote")]])]),
642 Block::Code { lang: Some("rust".into()), text: "fn main() {\n}\n".into() },
643 Block::Rule,
644 Block::Paragraph(Vec::new()),
645 ];
646 let doc = LoroDoc::new();
647 doc.config_text_style(crate::schema::text_style_config());
648 write(&body(&doc), 0, &flatten(&tree), false).unwrap();
649 doc.commit();
650 let copy = LoroDoc::new();
651 copy.import(&doc.export(loro::ExportMode::Snapshot).unwrap()).unwrap();
652 assert_eq!(doc_blocks(&copy), tree);
653 assert_eq!(first_text(&copy), "Title");
654 }
655}