Skip to main content

docling_core/
tree.rs

1//! docling's **item tree**, for a backend that knows the exact shape upstream
2//! gives a document and wants the JSON export to reproduce it.
3//!
4//! [`DoclingDocument::nodes`](crate::DoclingDocument::nodes) is a flat,
5//! reading-order stream tuned for Markdown / DocLang / LaTeX; the JSON export
6//! rebuilds docling's parent/child structure from it with generic rules (runs
7//! of list items become list groups, a heading is a flat sibling of the text
8//! that follows it). Upstream's backends do not all agree on that structure:
9//! the HTML backend nests everything after a heading *under* the heading,
10//! splits a paragraph of mixed formatting into an `inline` group of one text
11//! item per formatting run, parents a rich table cell's content to a group
12//! under the table, keeps site chrome on the `furniture` layer… and numbers
13//! every item in the order it *creates* them. A backend that ports those
14//! rules call-for-call (HTML's `html_tree.rs`, DOCX's `docx_tree.rs`) records
15//! the result here — an arena of items in
16//! creation order, each with its parent and children — and the JSON export
17//! ([`DoclingDocument::export_to_json`](crate::DoclingDocument::export_to_json))
18//! serializes this tree instead of deriving one from the nodes. Every other
19//! serializer keeps reading the flat nodes, so their output is unaffected.
20
21use crate::{ContentLayer, FieldItem, PictureImage, Script, Table};
22
23/// docling-core's `Formatting`: the inline styles an item carries in JSON.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
25pub struct Formatting {
26    pub bold: bool,
27    pub italic: bool,
28    pub underline: bool,
29    pub strikethrough: bool,
30    pub script: Script,
31}
32
33/// A `list_item`'s docling fields.
34#[derive(Debug, Clone, PartialEq, Eq, Default)]
35pub struct ListMeta {
36    pub enumerated: bool,
37    /// docling's `marker` — the HTML backend writes `""` unless an ordered
38    /// list carries an explicit `start`, then `"{n}."`.
39    pub marker: String,
40}
41
42/// What an item in the tree is. Mirrors the docling-core item classes the
43/// JSON `texts` / `groups` / `tables` / `pictures` / `field_regions` buckets
44/// hold.
45#[derive(Debug, Clone, PartialEq)]
46pub enum TreeKind {
47    /// A `TextItem` / `TitleItem` / `SectionHeaderItem` / `ListItem`, told
48    /// apart by `label` (`text`, `title`, `section_header`, `list_item`,
49    /// `caption`, `checkbox_selected`, `checkbox_unselected`, …).
50    Text {
51        label: String,
52        text: String,
53        /// docling's `orig` when it differs from `text` (the heading text
54        /// before unicode cleanup, say); `None` = same as `text`.
55        orig: Option<String>,
56        formatting: Option<Formatting>,
57        hyperlink: Option<String>,
58        /// `section_header` only: docling's heading level.
59        level: Option<u8>,
60        /// `list_item` only.
61        list: Option<ListMeta>,
62    },
63    /// A `CodeItem`.
64    Code {
65        text: String,
66        orig: Option<String>,
67        /// The language hint (a highlighter class token such as `python`),
68        /// mapped onto docling's `CodeLanguageLabel` at export; `None` →
69        /// `unknown`.
70        language: Option<String>,
71        formatting: Option<Formatting>,
72        hyperlink: Option<String>,
73    },
74    /// A `GroupItem`: `label` is docling's `GroupLabel` value (`inline`,
75    /// `list`, `section`, `unspecified`, …), `name` its name (`group`, `list`,
76    /// `ordered list`, `header-2`, `rich_cell_group_1_0_3`, …).
77    Group { label: String, name: String },
78    /// A `TableItem`. `rich_cells` marks the cells docling serialized as a
79    /// `RichTableCell`: `(row, col)` grid anchor → the group item (a child of
80    /// the table) that holds the cell's content. `captions` are caption text
81    /// items in the tree.
82    Table {
83        table: Table,
84        rich_cells: Vec<(usize, usize, usize)>,
85        captions: Vec<usize>,
86    },
87    /// A `PictureItem`, its caption text items and optional payload.
88    /// `classification` is a `PictureClassificationLabel` value written as
89    /// the picture's `meta.classification` (an HTML `<stamp>` / `<signature>`).
90    Picture {
91        captions: Vec<usize>,
92        image: Option<PictureImage>,
93        classification: Option<String>,
94        /// The prediction's `confidence`, when the backend writes one: the
95        /// DocLang deserializer stamps `1.0`; the office and HTML backends
96        /// leave it out (`None`).
97        confidence: Option<f64>,
98        /// A native chart's data grid (docling's `meta.tabular_chart.chart_data`,
99        /// the series reconstructed as a `TableData`), for a DOCX chart drawing.
100        chart: Option<Table>,
101        /// The `ImageRef.dpi` docling writes for `image` when the backend
102        /// read one from the file (python-pptx's `Image.dpi`: PIL's `dpi`
103        /// info, rounded, 72 when absent or out of 1–2048); `None` → 72,
104        /// which is what upstream's other office backends pass.
105        dpi: Option<u32>,
106    },
107    /// A form key-value region (`field_regions` / `field_items`).
108    FieldRegion { items: Vec<FieldItem> },
109    /// A `KeyValueItem` (`key_value_items`): docling's `GraphData` of key and
110    /// value cells and their links, written verbatim.
111    KeyValueGraph {
112        cells: Vec<crate::GraphCell>,
113        links: Vec<crate::GraphLink>,
114    },
115}
116
117/// docling's `ProvenanceItem` for a tree item, written verbatim: the
118/// backend's own geometry in the page's units — a PPTX shape's EMU box,
119/// whose `pages` entry is the slide size in EMU — rather than the 0–511
120/// DocLang grid the flat [`Node::Located`](crate::Node::Located) carries
121/// (which cannot round-trip those integers).
122#[derive(Debug, Clone, PartialEq)]
123pub struct TreeProv {
124    /// 1-based page (slide) number.
125    pub page_no: usize,
126    /// `[l, t, r, b]`, exactly as docling computed them.
127    pub bbox: [f64; 4],
128    /// docling's `coord_origin` tag. The office backends tag their
129    /// top-left-based boxes `TOPLEFT` (the PPTX backend since docling#4294 —
130    /// it used to tag them `BOTTOMLEFT`, which read the tuple as `(l, b, r,
131    /// t)` and swapped the vertical edges); a backend that really works in a
132    /// bottom-left space sets this.
133    pub bottom_left: bool,
134    /// `[0, len(text)]` in characters for a text item, `[0, 0]` for a table
135    /// or picture.
136    pub charspan: [usize; 2],
137}
138
139/// docling's `TrackSource` — where in a time-based track (a WebVTT cue) a
140/// text item came from. Written as the item's `source: [{"kind": "track", …}]`.
141#[derive(Debug, Clone, PartialEq)]
142pub struct TreeTrack {
143    /// The cue's start offset in seconds (docling's `WebVTTTimestamp.seconds`:
144    /// `h*3600 + m*60 + s + millis/1000.0`, so the float is bit-identical).
145    pub start_time: f64,
146    /// The cue's end offset in seconds.
147    pub end_time: f64,
148    /// The cue identifier line, when the cue has one.
149    pub identifier: Option<String>,
150    /// The `<v …>` voice annotation the text sits in, when any.
151    pub voice: Option<String>,
152}
153
154/// One item of an [`ItemTree`].
155#[derive(Debug, Clone, PartialEq)]
156pub struct TreeItem {
157    /// The parent item's index; `None` = the document body.
158    pub parent: Option<usize>,
159    /// Child item indices, in docling's `children` order.
160    pub children: Vec<usize>,
161    /// The content layer; `None` = `body`.
162    pub layer: Option<ContentLayer>,
163    pub kind: TreeKind,
164    /// The item's `prov` entry, when the backend has page geometry for it
165    /// (`None` → `prov: []`, what the HTML and DOCX backends write).
166    pub prov: Option<TreeProv>,
167    /// docling's `DocItem.comments`: the `comment_section` groups (or note
168    /// text items) annotating this item, as item indices — written after
169    /// `prov` when non-empty.
170    pub comments: Vec<usize>,
171    /// docling's `DocItem.source`: the track segment a text item was taken
172    /// from (WebVTT cues) — written after `prov` when set.
173    pub source: Option<TreeTrack>,
174    /// Removed by [`ItemTree::delete`] (docling's `delete_items`): the slot
175    /// stays so every other index keeps its meaning, but the item is not
176    /// numbered or written.
177    pub deleted: bool,
178    /// Footnotes / endnotes referenced from inside this text item (#538): the
179    /// note call's position (chars into the item's text) and the note's text.
180    /// docling keeps notes as unlinked furniture `footnote` items, so the
181    /// JSON never shows this; the Pandoc AST writes each as a `Note` there.
182    pub notes: Vec<TreeNote>,
183    /// This furniture `footnote` item is the body of a note some text item
184    /// calls (it travels in that item's [`Self::notes`]); the Pandoc AST then
185    /// leaves it out as a standalone block.
186    pub note_body: bool,
187}
188
189/// A note call inside a text item ([`TreeItem::notes`]).
190#[derive(Debug, Clone, PartialEq, Eq)]
191pub struct TreeNote {
192    /// The call's position, in chars into the item's `text`.
193    pub offset: usize,
194    /// The note's plain text.
195    pub text: String,
196}
197
198impl ItemTree {
199    /// Where each note call of one paragraph lands (#538): `full_text` is the
200    /// paragraph's text, `offsets` the calls' positions in it (chars), and
201    /// the paragraph's items are those created from `first_new` on. Each text
202    /// item is a trimmed slice of the paragraph (a formatting run, a link, or
203    /// the whole heading / list item), matched in order; a call inside an
204    /// item lands there, one between items ends the earlier (or starts the
205    /// first). When no item matches, the call ends the paragraph's last text
206    /// item; with no text item at all it is `None`.
207    pub fn place_note_calls(
208        &self,
209        first_new: usize,
210        full_text: &str,
211        offsets: &[usize],
212    ) -> Vec<Option<(usize, usize)>> {
213        let texts: Vec<(usize, &str)> = (first_new..self.items.len())
214            .filter(|&i| !self.items[i].deleted)
215            .filter_map(|i| match &self.items[i].kind {
216                TreeKind::Text { text, .. } | TreeKind::Code { text, .. } => {
217                    Some((i, text.as_str()))
218                }
219                _ => None,
220            })
221            .collect();
222        // Each found item's (id, start, end) in chars of `full_text`.
223        let mut spans: Vec<(usize, usize, usize)> = Vec::new();
224        let mut cursor = 0usize; // bytes
225        for &(item, text) in &texts {
226            if text.is_empty() {
227                continue;
228            }
229            if let Some(pos) = full_text[cursor..].find(text) {
230                let start_b = cursor + pos;
231                let start = full_text[..start_b].chars().count();
232                spans.push((item, start, start + text.chars().count()));
233                cursor = start_b + text.len();
234            }
235        }
236        offsets
237            .iter()
238            .map(|&offset| {
239                spans
240                    .iter()
241                    .find(|&&(_, start, end)| offset >= start && offset <= end)
242                    .map(|&(item, start, _)| (item, offset - start))
243                    .or_else(
244                        || match spans.iter().rev().find(|&&(_, _, end)| end <= offset) {
245                            Some(&(item, start, end)) => Some((item, end - start)),
246                            None => spans.first().map(|&(item, _, _)| (item, 0)),
247                        },
248                    )
249                    .or_else(|| {
250                        texts
251                            .last()
252                            .map(|&(item, text)| (item, text.chars().count()))
253                    })
254            })
255            .collect()
256    }
257}
258
259/// docling's item tree in creation order (see the [module docs](self)).
260#[derive(Debug, Clone, PartialEq, Default)]
261pub struct ItemTree {
262    /// Every item, indexed by creation order — which is how docling numbers
263    /// `#/texts/N`, `#/groups/N`, … within each bucket.
264    pub items: Vec<TreeItem>,
265    /// The body's `children`, as item indices.
266    pub body: Vec<usize>,
267}
268
269impl ItemTree {
270    /// Append an item under `parent` (`None` = body) on `layer`, registering
271    /// it as its parent's last child — docling's `add_*` calls do exactly that.
272    pub fn add(
273        &mut self,
274        parent: Option<usize>,
275        layer: Option<ContentLayer>,
276        kind: TreeKind,
277    ) -> usize {
278        let id = self.items.len();
279        self.items.push(TreeItem {
280            parent,
281            children: Vec::new(),
282            layer,
283            kind,
284            prov: None,
285            comments: Vec::new(),
286            source: None,
287            deleted: false,
288            notes: Vec::new(),
289            note_body: false,
290        });
291        match parent {
292            Some(p) => self.items[p].children.push(id),
293            None => self.body.push(id),
294        }
295        id
296    }
297
298    /// [`add`](Self::add) with the item's provenance — docling's
299    /// `add_text(…, prov=prov)`.
300    pub fn add_with_prov(
301        &mut self,
302        parent: Option<usize>,
303        layer: Option<ContentLayer>,
304        kind: TreeKind,
305        prov: TreeProv,
306    ) -> usize {
307        let id = self.add(parent, layer, kind);
308        self.items[id].prov = Some(prov);
309        id
310    }
311
312    /// Append every item of `other` after this tree's, renumbering its
313    /// indices (parents, children, comments, table/picture caption and
314    /// rich-cell refs) and adding its body children to this body — so a
315    /// backend can build independent fragments in parallel (one per PPTX
316    /// slide) and still hand the export one tree in creation order, exactly
317    /// as if it had been built sequentially.
318    pub fn append(&mut self, other: ItemTree) {
319        let off = self.items.len();
320        let shift = |i: usize| i + off;
321        for mut item in other.items {
322            item.parent = item.parent.map(shift);
323            for c in item.children.iter_mut().chain(item.comments.iter_mut()) {
324                *c = shift(*c);
325            }
326            match &mut item.kind {
327                TreeKind::Table {
328                    rich_cells,
329                    captions,
330                    ..
331                } => {
332                    for (_, _, g) in rich_cells.iter_mut() {
333                        *g = shift(*g);
334                    }
335                    for c in captions.iter_mut() {
336                        *c = shift(*c);
337                    }
338                }
339                TreeKind::Picture { captions, .. } => {
340                    for c in captions.iter_mut() {
341                        *c = shift(*c);
342                    }
343                }
344                _ => {}
345            }
346            self.items.push(item);
347        }
348        self.body.extend(other.body.into_iter().map(shift));
349    }
350
351    /// Move `id` under `new_parent`, dropping it from its current parent's
352    /// children and appending it to the new one's — docling's
353    /// `group_cell_elements` re-parenting of a rich cell's items.
354    pub fn reparent(&mut self, id: usize, new_parent: Option<usize>) {
355        let old = self.items[id].parent;
356        let siblings = match old {
357            Some(p) => &mut self.items[p].children,
358            None => &mut self.body,
359        };
360        siblings.retain(|&c| c != id);
361        self.items[id].parent = new_parent;
362        match new_parent {
363            Some(p) => self.items[p].children.push(id),
364            None => self.body.push(id),
365        }
366    }
367
368    /// Re-number the items in traversal order — a pre-order walk of the body
369    /// through every layer, which is how docling's
370    /// `DoclingDocument.concatenate` (and `_normalize_references`) re-creates
371    /// a document's items: a group created after the content it was later
372    /// wrapped around comes before that content afterwards. Items the walk
373    /// does not reach (deleted ones) are dropped. Returns each old id's new
374    /// id.
375    pub fn renumber_in_traversal_order(&mut self) -> Vec<Option<usize>> {
376        let mut order = Vec::with_capacity(self.items.len());
377        let mut stack: Vec<usize> = self.body.iter().rev().copied().collect();
378        while let Some(id) = stack.pop() {
379            if self.items[id].deleted {
380                continue;
381            }
382            order.push(id);
383            stack.extend(self.items[id].children.iter().rev());
384        }
385        let mut new_of: Vec<Option<usize>> = vec![None; self.items.len()];
386        for (new, &old) in order.iter().enumerate() {
387            new_of[old] = Some(new);
388        }
389        let remap = |ids: &mut Vec<usize>| {
390            *ids = ids.iter().filter_map(|&i| new_of[i]).collect();
391        };
392        let mut old_items: Vec<Option<TreeItem>> = std::mem::take(&mut self.items)
393            .into_iter()
394            .map(Some)
395            .collect();
396        for &old in &order {
397            let mut item = old_items[old].take().expect("each item visited once");
398            item.parent = item.parent.and_then(|p| new_of[p]);
399            remap(&mut item.children);
400            remap(&mut item.comments);
401            match &mut item.kind {
402                TreeKind::Table {
403                    rich_cells,
404                    captions,
405                    ..
406                } => {
407                    rich_cells.retain_mut(|(_, _, g)| match new_of[*g] {
408                        Some(n) => {
409                            *g = n;
410                            true
411                        }
412                        None => false,
413                    });
414                    remap(captions);
415                }
416                TreeKind::Picture { captions, .. } => remap(captions),
417                _ => {}
418            }
419            self.items.push(item);
420        }
421        remap(&mut self.body);
422        new_of
423    }
424
425    /// Remove `id` from the tree — docling's `delete_items`, which the DOCX
426    /// backend uses to drop the empty text item a blank spacer paragraph left
427    /// between two items of a resumed list. The item leaves its parent's
428    /// children and is neither numbered nor written; its slot stays so the
429    /// indices held elsewhere stay valid.
430    pub fn delete(&mut self, id: usize) {
431        match self.items[id].parent {
432            Some(p) => self.items[p].children.retain(|&c| c != id),
433            None => self.body.retain(|&c| c != id),
434        }
435        self.items[id].deleted = true;
436    }
437
438    /// docling-core's `DoclingDocument.validate_misplaced_list_items` (a
439    /// model validator, so it runs whenever docling-core serializes or loads
440    /// a document): every `list_item` whose parent is not a `list` group is
441    /// re-homed into a new one. A pre-order walk of the body (groups
442    /// included) collects them; consecutive misplaced items directly on the
443    /// body share one group, any other misplaced item gets its own. Working
444    /// from the last run back, each run gets a `ListGroup` (name `group`)
445    /// inserted where its first item stood, the items are deleted and
446    /// re-added under the group as fresh items, so they move to the end of
447    /// the text numbering (#527: the DOCX backend leaves such items in rich
448    /// table cells). A no-op for a well-formed tree.
449    ///
450    /// One deliberate divergence (#586): docling-core deletes each item *with
451    /// its children* and re-adds it from its text alone, so a mixed-format
452    /// item — an empty `list_item` over an `inline` group of text runs —
453    /// comes back empty and its text is gone from the JSON (and from the
454    /// Markdown/HTML docling serializes after that validator ran; the JSON
455    /// docling saves *before* exporting still has it). Here the children
456    /// follow the item into the group: the structure docling-core requires,
457    /// the content the document had.
458    pub fn wrap_misplaced_list_items(&mut self) {
459        let is_list_item = |t: &Self, id: usize| matches!(&t.items[id].kind, TreeKind::Text { label, .. } if label == "list_item");
460        let in_list_group = |t: &Self, id: usize| {
461            t.items[id].parent.is_some_and(
462                |p| matches!(&t.items[p].kind, TreeKind::Group { label, .. } if label == "list"),
463            )
464        };
465        let mut runs: Vec<Vec<usize>> = Vec::new();
466        // `None` = the body itself, which the walk yields first.
467        let mut prev: Option<usize> = None;
468        let mut stack: Vec<usize> = self.body.iter().rev().copied().collect();
469        while let Some(id) = stack.pop() {
470            if self.items[id].deleted {
471                continue;
472            }
473            if is_list_item(self, id) && !in_list_group(self, id) {
474                let continues =
475                    prev.is_some_and(|p| is_list_item(self, p) && self.items[p].parent.is_none());
476                match runs.last_mut() {
477                    Some(run) if continues => run.push(id),
478                    _ => runs.push(vec![id]),
479                }
480            }
481            prev = Some(id);
482            stack.extend(self.items[id].children.iter().rev().copied());
483        }
484        for run in runs.into_iter().rev() {
485            let parent = self.items[run[0]].parent;
486            let group = self.add(
487                parent,
488                None,
489                TreeKind::Group {
490                    label: "list".into(),
491                    name: "group".into(),
492                },
493            );
494            let siblings = match parent {
495                Some(p) => &mut self.items[p].children,
496                None => &mut self.body,
497            };
498            siblings.pop();
499            let at = siblings
500                .iter()
501                .position(|&c| c == run[0])
502                .unwrap_or(siblings.len());
503            siblings.insert(at, group);
504            for &li in &run {
505                // Not `delete_subtree`: the children move to the copy (#586).
506                self.delete(li);
507            }
508            // `add_list_item` keeps the text, marker, formatting, hyperlink
509            // and first provenance — not comments or a source. The children
510            // (the inline group of a mixed-format item) are carried over.
511            for &li in &run {
512                let children = std::mem::take(&mut self.items[li].children);
513                let copy = TreeItem {
514                    parent: Some(group),
515                    children: children.clone(),
516                    comments: Vec::new(),
517                    source: None,
518                    deleted: false,
519                    ..self.items[li].clone()
520                };
521                let id = self.items.len();
522                self.items.push(copy);
523                for c in children {
524                    self.items[c].parent = Some(id);
525                }
526                self.items[group].children.push(id);
527            }
528        }
529    }
530
531    /// The last live text-bucket item (docling's `doc.texts[-1]`).
532    pub fn last_text(&self) -> Option<usize> {
533        self.items.iter().rposition(|it| {
534            !it.deleted && matches!(it.kind, TreeKind::Text { .. } | TreeKind::Code { .. })
535        })
536    }
537
538    /// How many items of a bucket precede `id` — its `#/{bucket}/N` index.
539    pub fn bucket_index(&self, id: usize) -> usize {
540        let same = |k: &TreeKind| {
541            std::mem::discriminant(k) == std::mem::discriminant(&self.items[id].kind)
542                || matches!(
543                    (k, &self.items[id].kind),
544                    (TreeKind::Text { .. }, TreeKind::Code { .. })
545                        | (TreeKind::Code { .. }, TreeKind::Text { .. })
546                )
547        };
548        self.items[..id]
549            .iter()
550            .filter(|it| !it.deleted && same(&it.kind))
551            .count()
552    }
553
554    /// The number of tables created so far (docling's `len(doc.tables)`).
555    pub fn table_count(&self) -> usize {
556        self.items
557            .iter()
558            .filter(|it| !it.deleted && matches!(it.kind, TreeKind::Table { .. }))
559            .count()
560    }
561}
562
563#[cfg(test)]
564mod tests {
565    use super::*;
566
567    fn text(t: &str) -> TreeKind {
568        TreeKind::Text {
569            label: "text".into(),
570            text: t.into(),
571            orig: None,
572            formatting: None,
573            hyperlink: None,
574            level: None,
575            list: None,
576        }
577    }
578
579    /// `add` registers the item as its parent's (or the body's) last child;
580    /// `reparent` moves it — a rich cell's items leave the heading they were
581    /// created under for the table's group.
582    #[test]
583    fn add_and_reparent_keep_docling_children_order() {
584        let mut t = ItemTree::default();
585        let title = t.add(None, None, text("Title"));
586        let a = t.add(Some(title), None, text("a"));
587        let b = t.add(Some(title), None, text("b"));
588        let table = t.add(
589            Some(title),
590            None,
591            TreeKind::Table {
592                table: Table::default(),
593                rich_cells: Vec::new(),
594                captions: Vec::new(),
595            },
596        );
597        let group = t.add(
598            Some(table),
599            None,
600            TreeKind::Group {
601                label: "unspecified".into(),
602                name: "rich_cell_group_1_0_0".into(),
603            },
604        );
605        assert_eq!(t.body, vec![title]);
606        assert_eq!(t.items[title].children, vec![a, b, table]);
607        t.reparent(a, Some(group));
608        assert_eq!(t.items[title].children, vec![b, table]);
609        assert_eq!(t.items[group].children, vec![a]);
610        assert_eq!(t.items[a].parent, Some(group));
611        assert_eq!(t.table_count(), 1);
612        // Text and code share the `texts` bucket.
613        let code = t.add(
614            None,
615            None,
616            TreeKind::Code {
617                text: "x".into(),
618                orig: None,
619                language: None,
620                formatting: None,
621                hyperlink: None,
622            },
623        );
624        assert_eq!(t.bucket_index(code), 3, "title, a, b precede it in `texts`");
625        assert_eq!(t.bucket_index(group), 0);
626        assert_eq!(t.body, vec![title, code]);
627    }
628
629    /// `append` renumbers a fragment built on its own (a slide converted in
630    /// parallel) so the merged tree reads as if built in one pass: parents,
631    /// children, comment back-refs and caption refs all shift together.
632    #[test]
633    fn append_renumbers_a_fragment_into_creation_order() {
634        let mut whole = ItemTree::default();
635        let slide0 = whole.add(
636            None,
637            None,
638            TreeKind::Group {
639                label: "chapter".into(),
640                name: "slide-0".into(),
641            },
642        );
643        whole.add(Some(slide0), None, text("first"));
644
645        let mut frag = ItemTree::default();
646        let slide1 = frag.add(
647            None,
648            None,
649            TreeKind::Group {
650                label: "chapter".into(),
651                name: "slide-1".into(),
652            },
653        );
654        let cap = frag.add_with_prov(
655            Some(slide1),
656            None,
657            TreeKind::Text {
658                label: "caption".into(),
659                text: "Title".into(),
660                orig: None,
661                formatting: None,
662                hyperlink: None,
663                level: None,
664                list: None,
665            },
666            TreeProv {
667                page_no: 2,
668                bbox: [1.0, 2.0, 3.0, 4.0],
669                bottom_left: true,
670                charspan: [0, 5],
671            },
672        );
673        let pic = frag.add(
674            Some(slide1),
675            None,
676            TreeKind::Picture {
677                captions: vec![cap],
678                image: None,
679                classification: Some("bar_chart".into()),
680                confidence: None,
681                chart: None,
682                dpi: None,
683            },
684        );
685        let note = frag.add(
686            None,
687            Some(ContentLayer::Notes),
688            TreeKind::Group {
689                label: "comment_section".into(),
690                name: "comment-slide2-1".into(),
691            },
692        );
693        frag.items[pic].comments.push(note);
694
695        whole.append(frag);
696        assert_eq!(whole.body, vec![slide0, 2, 5]);
697        assert_eq!(whole.items[2].children, vec![3, 4]);
698        assert_eq!(whole.items[3].parent, Some(2));
699        assert_eq!(whole.items[3].prov.as_ref().map(|p| p.page_no), Some(2));
700        assert!(
701            matches!(&whole.items[4].kind, TreeKind::Picture { captions, .. } if captions == &[3])
702        );
703        assert_eq!(whole.items[4].comments, vec![5]);
704        assert_eq!(whole.items[5].parent, None);
705        assert_eq!(
706            whole.bucket_index(4),
707            0,
708            "the fragment's picture is #/pictures/0"
709        );
710        assert_eq!(
711            whole.bucket_index(5),
712            2,
713            "slide-0, slide-1 precede it in `groups`"
714        );
715    }
716
717    /// `renumber_in_traversal_order`: docling's `concatenate` re-creates the
718    /// items as a pre-order walk meets them, so a group created after the
719    /// content it was wrapped around (a rich cell's group) comes first, and a
720    /// deleted item disappears; every cross-reference follows.
721    #[test]
722    fn renumbering_follows_the_traversal() {
723        let mut t = ItemTree::default();
724        let a = t.add(None, None, text("a"));
725        let table = t.add(
726            None,
727            None,
728            TreeKind::Table {
729                table: Table::default(),
730                rich_cells: Vec::new(),
731                captions: Vec::new(),
732            },
733        );
734        let cell_text = t.add(None, None, text("cell"));
735        let group = t.add(
736            Some(table),
737            None,
738            TreeKind::Group {
739                label: "unspecified".into(),
740                name: "rich_cell_group_1_0_0".into(),
741            },
742        );
743        t.reparent(cell_text, Some(group));
744        if let TreeKind::Table { rich_cells, .. } = &mut t.items[table].kind {
745            rich_cells.push((0, 0, group));
746        }
747        let gone = t.add(None, None, text("gone"));
748        t.delete(gone);
749        let z = t.add(None, None, text("z"));
750
751        let new_of = t.renumber_in_traversal_order();
752        assert_eq!(
753            new_of,
754            vec![Some(0), Some(1), Some(3), Some(2), None, Some(4)]
755        );
756        assert_eq!(t.items.len(), 5);
757        assert_eq!(t.body, vec![0, 1, 4]);
758        assert_eq!(t.items[1].children, vec![2], "the group follows its table");
759        assert_eq!(t.items[2].parent, Some(1));
760        assert_eq!(
761            t.items[3].parent,
762            Some(2),
763            "the cell text follows its group"
764        );
765        assert!(matches!(&t.items[3].kind, TreeKind::Text { text, .. } if text == "cell"));
766        assert!(
767            matches!(&t.items[1].kind, TreeKind::Table { rich_cells, .. } if rich_cells == &[(0, 0, 2)])
768        );
769        let _ = (a, z);
770    }
771
772    /// #586: a misplaced `list_item` keeps its children when it is re-homed.
773    /// docling-core's `validate_misplaced_list_items` re-adds the item from
774    /// its text alone, so a mixed-format item (empty `list_item` over an
775    /// `inline` group of runs) lost every run — a DOCX table cell whose list
776    /// paragraph followed a `numId 0` spacer came out as an empty bullet in
777    /// the JSON and the HTML. The group goes where the item stood, the copy
778    /// is numbered last, the inline group and its texts move under it.
779    #[test]
780    fn wrapping_a_misplaced_list_item_keeps_its_runs() {
781        let mut t = ItemTree::default();
782        let cell = t.add(
783            None,
784            None,
785            TreeKind::Group {
786                label: "unspecified".into(),
787                name: "rich_cell_group_1_0_1".into(),
788            },
789        );
790        let before = t.add(Some(cell), None, text("before"));
791        let item = t.add(
792            Some(cell),
793            None,
794            TreeKind::Text {
795                label: "list_item".into(),
796                text: String::new(),
797                orig: None,
798                formatting: None,
799                hyperlink: None,
800                level: None,
801                list: Some(ListMeta {
802                    enumerated: false,
803                    marker: String::new(),
804                }),
805            },
806        );
807        let inline = t.add(
808            Some(item),
809            None,
810            TreeKind::Group {
811                label: "inline".into(),
812                name: "group".into(),
813            },
814        );
815        let run_a = t.add(Some(inline), None, text("Second item text"));
816        let run_b = t.add(Some(inline), None, text("[Optional]"));
817        let after = t.add(Some(cell), None, text("after"));
818
819        t.wrap_misplaced_list_items();
820
821        let group = t.items[cell].children[1];
822        assert_eq!(t.items[cell].children, vec![before, group, after]);
823        assert!(
824            matches!(&t.items[group].kind, TreeKind::Group { label, name } if label == "list" && name == "group")
825        );
826        assert!(t.items[item].deleted, "the original item is deleted");
827        let copy = t.items[group].children[0];
828        assert_ne!(copy, item);
829        assert!(
830            copy > after,
831            "the copy is numbered after every existing item"
832        );
833        assert_eq!(t.items[copy].children, vec![inline]);
834        assert_eq!(t.items[inline].parent, Some(copy));
835        assert_eq!(t.items[inline].children, vec![run_a, run_b]);
836        for id in [inline, run_a, run_b] {
837            assert!(!t.items[id].deleted, "item {id} must survive the re-homing");
838        }
839    }
840}