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