Skip to main content

docling_core/
json.rs

1//! Export a [`DoclingDocument`] to docling-core's native JSON wire format
2//! (`DoclingDocument` schema v1.10.0) — the same shape `export_to_dict()` /
3//! `save_as_json()` produce in Python docling, and the inverse of the
4//! JSON-docling reader.
5//!
6//! The crate's [`Node`] model bakes Markdown escaping (and inline markers) into
7//! its text, whereas docling stores raw text and escapes at render time. We
8//! therefore *un-escape* on the way out so a docling-core round-trip
9//! (`load_from_json().export_to_markdown()`) reproduces the same Markdown.
10
11use serde_json::{json, Value};
12
13use crate::document::{CaptionParent, ContentLayer, DoclingDocument, Node, Table};
14
15const SCHEMA_VERSION: &str = "1.10.0";
16
17/// docling-core's `CodeLanguageLabel` values (anything else serializes as
18/// `unknown`, which the model requires for code items).
19const CODE_LANGUAGES: &[&str] = &[
20    "Ada",
21    "Awk",
22    "Bash",
23    "bc",
24    "C",
25    "C#",
26    "C++",
27    "CMake",
28    "COBOL",
29    "CSS",
30    "Ceylon",
31    "Clojure",
32    "Crystal",
33    "Cuda",
34    "Cython",
35    "D",
36    "Dart",
37    "dc",
38    "Dockerfile",
39    "DocLang",
40    "Elixir",
41    "Erlang",
42    "FORTRAN",
43    "Forth",
44    "Go",
45    "HTML",
46    "Haskell",
47    "Haxe",
48    "Java",
49    "JavaScript",
50    "JSON",
51    "Julia",
52    "Kotlin",
53    "Latex",
54    "Lisp",
55    "Lua",
56    "Matlab",
57    "MoonScript",
58    "Nim",
59    "OCaml",
60    "ObjectiveC",
61    "Octave",
62    "PHP",
63    "Pascal",
64    "Perl",
65    "Prolog",
66    "Python",
67    "Racket",
68    "Ruby",
69    "Rust",
70    "SML",
71    "SQL",
72    "Scala",
73    "Scheme",
74    "Swift",
75    "Tikz",
76    "TypeScript",
77    "VisualBasic",
78    "XML",
79    "YAML",
80];
81
82/// Map a fence language to docling's `CodeLanguageLabel` (case-insensitive), else
83/// `unknown`.
84/// docling's `CodeLanguageLabel` for a language name (`unknown` when it is
85/// not one docling knows) — the mapping the JSON `code_language` field uses,
86/// for a backend that wants to test a hint before storing it.
87pub fn code_language_label(lang: &str) -> &'static str {
88    code_language(Some(lang))
89}
90
91pub(crate) fn code_language(lang: Option<&str>) -> &'static str {
92    match lang {
93        Some(l) => CODE_LANGUAGES
94            .iter()
95            .find(|c| c.eq_ignore_ascii_case(l))
96            .copied()
97            .unwrap_or("unknown"),
98        None => "unknown",
99    }
100}
101
102/// An item's exact provenance, written verbatim (see [`Builder::prov_json`]):
103/// a [`Node::Prov`] wrapper's top-left page box, or a tree item's
104/// [`TreeProv`](crate::tree::TreeProv).
105#[derive(Clone, Copy)]
106struct ExactProv {
107    page_no: usize,
108    bbox: [f64; 4],
109    bottom_left: bool,
110    charspan: [usize; 2],
111}
112
113impl From<&crate::tree::TreeProv> for ExactProv {
114    fn from(p: &crate::tree::TreeProv) -> Self {
115        ExactProv {
116            page_no: p.page_no,
117            bbox: p.bbox,
118            bottom_left: p.bottom_left,
119            charspan: p.charspan,
120        }
121    }
122}
123
124/// docling-core's `_clamp_provenance_bboxes_to_pages`: each `prov` box of
125/// every item on a known page is clamped to `[0, width] × [0, height]`
126/// (whatever its `coord_origin` — docling clamps the stored numbers), and a
127/// table whose provenance sits on one page has its cell boxes clamped too.
128fn clamp_boxes_to_pages(out: &mut Value, pages: &[(usize, f64, f64)]) {
129    if pages.is_empty() {
130        return;
131    }
132    let size = |page_no: &Value| -> Option<(f64, f64)> {
133        let n = page_no.as_u64()? as usize;
134        pages
135            .iter()
136            .find(|(p, _, _)| *p == n)
137            .map(|(_, w, h)| (*w, *h))
138    };
139    let r2 = |v: f64| (v * 100.0).round() / 100.0;
140    let clamp_bbox = |bbox: &mut Value, (w, h): (f64, f64)| {
141        for (key, hi) in [("l", w), ("r", w), ("t", h), ("b", h)] {
142            if let Some(v) = bbox.get(key).and_then(Value::as_f64) {
143                bbox[key] = json!(r2(v.clamp(0.0, hi.max(0.0))));
144            }
145        }
146    };
147    for bucket in [
148        "texts",
149        "pictures",
150        "tables",
151        "key_value_items",
152        "form_items",
153        "field_regions",
154        "field_items",
155    ] {
156        let Some(items) = out.get_mut(bucket).and_then(Value::as_array_mut) else {
157            continue;
158        };
159        for item in items {
160            let mut table_page: Option<Option<(f64, f64)>> = None;
161            if let Some(provs) = item.get_mut("prov").and_then(Value::as_array_mut) {
162                let mut page_nos: Vec<u64> = Vec::new();
163                for prov in provs.iter_mut() {
164                    if let Some(n) = prov.get("page_no").and_then(Value::as_u64) {
165                        page_nos.push(n);
166                    }
167                    let Some(sz) = prov.get("page_no").and_then(size) else {
168                        continue;
169                    };
170                    if let Some(bbox) = prov.get_mut("bbox") {
171                        clamp_bbox(bbox, sz);
172                    }
173                }
174                page_nos.sort_unstable();
175                page_nos.dedup();
176                if let [only] = page_nos[..] {
177                    table_page = Some(size(&json!(only)));
178                }
179            }
180            // A table's cells (and the `grid` docling derives from them).
181            if let (Some(Some(sz)), Some(data)) = (table_page, item.get_mut("data")) {
182                for key in ["table_cells", "grid"] {
183                    let Some(rows) = data.get_mut(key).and_then(Value::as_array_mut) else {
184                        continue;
185                    };
186                    for entry in rows.iter_mut() {
187                        let cells: Vec<&mut Value> = match entry {
188                            Value::Array(row) => row.iter_mut().collect(),
189                            other => vec![other],
190                        };
191                        for cell in cells {
192                            if let Some(bbox) = cell.get_mut("bbox").filter(|b| b.is_object()) {
193                                clamp_bbox(bbox, sz);
194                            }
195                        }
196                    }
197                }
198            }
199        }
200    }
201}
202
203/// docling-core's `Formatting` model, every field written.
204fn formatting_json(f: &crate::tree::Formatting) -> Value {
205    json!({
206        "bold": f.bold,
207        "italic": f.italic,
208        "underline": f.underline,
209        "strikethrough": f.strikethrough,
210        "script": match f.script {
211            crate::Script::Baseline => "baseline",
212            crate::Script::Sub => "sub",
213            crate::Script::Super => "super",
214        },
215    })
216}
217
218/// docling's `TrackSource` entry: `kind`, the two offsets, then the optional
219/// `identifier` / `voice` (dropped when `None`, as `exclude_none` does).
220fn track_json(t: &crate::tree::TreeTrack) -> Value {
221    let mut m = serde_json::Map::new();
222    m.insert("kind".into(), json!("track"));
223    m.insert("start_time".into(), json!(t.start_time));
224    m.insert("end_time".into(), json!(t.end_time));
225    if let Some(id) = &t.identifier {
226        m.insert("identifier".into(), json!(id));
227    }
228    if let Some(v) = &t.voice {
229        m.insert("voice".into(), json!(v));
230    }
231    Value::Object(m)
232}
233
234/// docling-core's `ImageRef` (pydantic field order: mimetype, dpi, size —
235/// as floats — uri), with the bytes inlined as a `data:` URI — a PNG, like
236/// `ImageRef.from_pil`'s (`pixel_digest::docling_data_uri`).
237fn image_ref_json(img: &crate::PictureImage) -> Value {
238    let (mimetype, uri) = crate::pixel_digest::docling_data_uri(img);
239    json!({
240        "mimetype": mimetype,
241        "dpi": img.dpi,
242        "size": { "width": img.width as f64, "height": img.height as f64 },
243        "uri": uri,
244    })
245}
246
247/// Build the docling-core JSON object for `doc`.
248pub fn to_json(doc: &DoclingDocument) -> Value {
249    build_json(doc, false)
250}
251
252/// [`to_json`] plus the note calls docling's model cannot express: a text
253/// item calling footnotes carries `"_notes": [[offset, text], …]`, a
254/// footnote item that is such a note's body `"_note_body": true` (#538).
255/// The Pandoc writer reads these; nothing is ever exported with them.
256pub(crate) fn to_json_with_notes(doc: &DoclingDocument) -> Value {
257    build_json(doc, true)
258}
259
260fn build_json(doc: &DoclingDocument, note_keys: bool) -> Value {
261    let mut b = Builder {
262        note_keys,
263        ..Builder::default()
264    };
265    // A backend that built docling's item tree ([`crate::tree`]) has already
266    // decided every parent, child and creation index; serialize that. The
267    // flat nodes are for the other serializers.
268    let body = match &doc.tree {
269        Some(tree) => {
270            // The page map still comes from the flat stream's markers (a
271            // PPTX slide's EMU size): the tree holds items, not pages.
272            for n in &doc.nodes {
273                if let Node::PageInfo {
274                    page_no,
275                    width,
276                    height,
277                } = n
278                {
279                    if *page_no > 0 {
280                        b.pages.push((*page_no, *width as f64, *height as f64));
281                    }
282                }
283            }
284            // docling-core's `validate_misplaced_list_items` runs on every
285            // document it serializes; apply it the same way (keeping the
286            // items' children, which docling-core drops — #586).
287            let mut tree = tree.clone();
288            tree.wrap_misplaced_list_items();
289            b.write_tree(&tree)
290        }
291        None => b.walk_into(&doc.nodes, "#/body"),
292    };
293    b.link_comments();
294
295    let mut out = json!({
296        "schema_name": "DoclingDocument",
297        "version": SCHEMA_VERSION,
298        "name": doc.name,
299        "origin": {
300            "mimetype": "text/plain",
301            "binary_hash": fnv1a(&doc.name),
302            "filename": doc.name,
303        },
304        "furniture": {
305            "self_ref": "#/furniture",
306            "children": [],
307            "content_layer": "furniture",
308            "name": "_root_",
309            "label": "unspecified",
310        },
311        "body": {
312            "self_ref": "#/body",
313            "children": body,
314            "content_layer": "body",
315            "name": "_root_",
316            "label": "unspecified",
317        },
318        "groups": b.groups,
319        "texts": b.texts,
320        "pictures": b.pictures,
321        "tables": b.tables,
322        "key_value_items": b.key_value_items,
323        "form_items": [],
324        "pages": b.pages.iter().map(|(n, w, h)| {
325            let r2 = |v: f64| (v * 100.0).round() / 100.0;
326            // docling-core's `PageItem` field order: size, image, page_no
327            // (#520 — the image only when page images were generated).
328            let mut page = serde_json::Map::new();
329            page.insert("size".into(), json!({ "width": r2(*w), "height": r2(*h) }));
330            if let Some(img) = doc.page_images.get(n) {
331                page.insert("image".into(), image_ref_json(img));
332            }
333            page.insert("page_no".into(), json!(n));
334            (n.to_string(), Value::Object(page))
335        }).collect::<serde_json::Map<String, Value>>(),
336    });
337
338    // docling-core's `validate_document` — a pydantic `model_validator` every
339    // `DoclingDocument` passes through when a `ConversionResult` (or a
340    // serializer) is built around it — clamps every provenance box, and a
341    // table's cell boxes, into its page's bounds in place
342    // (`_clamp_provenance_bboxes_to_pages`). The JSON docling writes therefore
343    // carries the clamped boxes: a spreadsheet region whose page was sized
344    // `right − left` × `bottom − top` loses its offset, a slide shape hanging
345    // off the slide edge is cut at it. Reproduce that on the finished items.
346    clamp_boxes_to_pages(&mut out, &b.pages);
347
348    // docling only emits `field_regions` / `field_items` when a document has
349    // form fields, and places them just before `pages`. Insert them in that slot
350    // (re-appending `pages` afterwards, since `preserve_order` keeps insertion
351    // order) so non-KVP documents' JSON is byte-identical to before.
352    if !b.field_regions.is_empty() {
353        if let Some(obj) = out.as_object_mut() {
354            let pages = obj.remove("pages");
355            obj.insert("field_regions".into(), Value::Array(b.field_regions));
356            obj.insert("field_items".into(), Value::Array(b.field_items));
357            if let Some(pages) = pages {
358                obj.insert("pages".into(), pages);
359            }
360        }
361    }
362    out
363}
364
365/// A DocumentPictureClassifier's predictions as the picture's `meta` — they
366/// land twice, exactly like docling 2.x writes them: the newer
367/// `meta.classification` field (pydantic field order: confidence, created_by,
368/// class_name) and the deprecated-but-still-emitted `classification`
369/// annotation, carried here under an `annotations` key that `add_picture`
370/// lifts onto the item.
371fn classification_meta(classes: &[crate::PictureClass]) -> Value {
372    json!({
373        "classification": {
374            "predictions": classes.iter().map(|c| json!({
375                "confidence": c.confidence as f64,
376                "created_by": "DocumentPictureClassifier",
377                "class_name": c.class_name,
378            })).collect::<Vec<_>>(),
379        },
380        "annotations": [{
381            "kind": "classification",
382            "provenance": "DocumentPictureClassifier",
383            "predicted_classes": classes.iter().map(|c| json!({
384                "class_name": c.class_name,
385                "confidence": c.confidence as f64,
386            })).collect::<Vec<_>>(),
387        }],
388    })
389}
390
391/// docling's `TableData` for a table: `table_cells`, `num_rows`/`num_cols`
392/// and the `grid` that repeats each cell at every position it covers. Shared
393/// by table items and a chart picture's `meta.tabular_chart.chart_data`.
394/// One table cell as docling's `TableCell` JSON: the eleven fields in
395/// pydantic order, `bbox` appended when the cell carries one. Built straight
396/// into a `Map` sized for the entries — the table grid repeats every cell
397/// object once per spanned slot, so on a table-heavy document (a patent's
398/// claims tables, an EBCDIC dump) this constructor and its clones *are* the
399/// JSON export's cost; the `json!` macro built the same object through a
400/// growing map with a rehash per doubling.
401#[allow(clippy::too_many_arguments)]
402fn cell_value(
403    row_span: usize,
404    col_span: usize,
405    start_row: usize,
406    end_row: usize,
407    start_col: usize,
408    end_col: usize,
409    text: String,
410    column_header: bool,
411    row_header: bool,
412    row_section: bool,
413    bbox: Option<[f32; 4]>,
414) -> Value {
415    let mut m = serde_json::Map::with_capacity(12);
416    m.insert("row_span".into(), row_span.into());
417    m.insert("col_span".into(), col_span.into());
418    m.insert("start_row_offset_idx".into(), start_row.into());
419    m.insert("end_row_offset_idx".into(), end_row.into());
420    m.insert("start_col_offset_idx".into(), start_col.into());
421    m.insert("end_col_offset_idx".into(), end_col.into());
422    m.insert("text".into(), Value::String(text));
423    m.insert("column_header".into(), column_header.into());
424    m.insert("row_header".into(), row_header.into());
425    m.insert("row_section".into(), row_section.into());
426    m.insert("fillable".into(), false.into());
427    if let Some(b) = bbox {
428        m.insert(
429            "bbox".into(),
430            json!({
431                "l": b[0], "t": b[1], "r": b[2], "b": b[3],
432                "coord_origin": "TOPLEFT",
433            }),
434        );
435    }
436    Value::Object(m)
437}
438
439/// `TableData` from a table whose cell text is Markdown-flavoured (the flat
440/// nodes: escapes to undo, GFM hard-break markers to strip).
441fn table_data(t: &Table) -> Value {
442    table_data_with(t, false)
443}
444
445/// `TableData`; with `raw` the cell text is docling's own raw cell text (a
446/// backend-built tree) and is written verbatim.
447fn table_data_with(t: &Table, raw: bool) -> Value {
448    let cell_text = |s: &str| {
449        if raw {
450            s.to_string()
451        } else {
452            unescape_text(&crate::markdown::strip_hard_breaks(s))
453        }
454    };
455    let mut num_rows = t.rows.len();
456    let mut num_cols = t.rows.iter().map(Vec::len).max().unwrap_or(0);
457    // Rectangular `rows` are the grid, and cells reaching past it are
458    // clipped — docling's own `TableData.grid` on a USPTO table whose
459    // replicated cells outrun `num_cols`, or an HTML rowspan past the last
460    // row. Ragged rows are no grid at all: a backend that compacts them
461    // (xlsx `skip_empty_cells`, #271) keeps the true offsets in first-class
462    // cells, so there the grid spans every cell's extent and the omitted
463    // positions come back as docling's empty filler cells.
464    let ragged = t.rows.iter().any(|r| r.len() != num_cols);
465    if let Some(first_class) = t.cells.as_ref().filter(|c| ragged && !c.is_empty()) {
466        for c in first_class {
467            num_rows = num_rows.max(c.start_row + c.row_span);
468            num_cols = num_cols.max(c.start_col + c.col_span);
469        }
470    }
471    let mut grid = Vec::with_capacity(num_rows);
472    let mut cells = Vec::new();
473    // Grid slot → index into `cells` (the anchor cell covering it). A flat
474    // row-major table instead of a `HashMap<(r, c), Value>` of clones: the
475    // grid is filled from it with one clone per slot, and nothing is hashed.
476    let mut slot: Vec<Option<usize>> = vec![None; num_rows * num_cols];
477    if let Some(first_class) = t.cells.as_ref().filter(|c| !c.is_empty()) {
478        for c in first_class {
479            let idx = cells.len();
480            cells.push(cell_value(
481                c.row_span,
482                c.col_span,
483                c.start_row,
484                c.start_row + c.row_span,
485                c.start_col,
486                c.start_col + c.col_span,
487                cell_text(&c.text),
488                c.column_header,
489                c.row_header,
490                c.row_section,
491                c.bbox,
492            ));
493            for r in c.start_row..(c.start_row + c.row_span).min(num_rows) {
494                for k in c.start_col..(c.start_col + c.col_span).min(num_cols) {
495                    slot[r * num_cols + k] = Some(idx);
496                }
497            }
498        }
499        for r in 0..num_rows {
500            let mut grid_row = Vec::with_capacity(num_cols);
501            for c in 0..num_cols {
502                grid_row.push(match slot[r * num_cols + c] {
503                    Some(i) => cells[i].clone(),
504                    None => cell_value(
505                        1,
506                        1,
507                        r,
508                        r + 1,
509                        c,
510                        c + 1,
511                        String::new(),
512                        false,
513                        false,
514                        false,
515                        None,
516                    ),
517                });
518            }
519            grid.push(grid_row);
520        }
521    } else {
522        let s = t.structure.as_ref();
523        let flag = |grid: Option<&Vec<Vec<bool>>>, r: usize, c: usize| -> bool {
524            grid.and_then(|g| g.get(r))
525                .and_then(|row| row.get(c))
526                .copied()
527                .unwrap_or(false)
528        };
529        let anchor_of = |r: usize, c: usize| -> (usize, usize) {
530            let (mut r0, mut c0) = (r, c);
531            while c0 > 0 && flag(s.map(|s| &s.col_continuation), r, c0) {
532                c0 -= 1;
533            }
534            while r0 > 0 && flag(s.map(|s| &s.row_continuation), r0, c0) {
535                r0 -= 1;
536            }
537            (r0, c0)
538        };
539        // Each slot's anchor, computed once; the anchor's extent is the
540        // farthest slot that resolves to it.
541        let anchors: Vec<(usize, usize)> = (0..num_rows)
542            .flat_map(|r| (0..num_cols).map(move |c| (r, c)))
543            .map(|(r, c)| anchor_of(r, c))
544            .collect();
545        let mut extent: Vec<(usize, usize)> = (0..num_rows)
546            .flat_map(|r| (0..num_cols).map(move |c| (r, c)))
547            .collect();
548        for (i, &(ar, ac)) in anchors.iter().enumerate() {
549            let (r, c) = (i / num_cols.max(1), i % num_cols.max(1));
550            let e = &mut extent[ar * num_cols + ac];
551            e.0 = e.0.max(r);
552            e.1 = e.1.max(c);
553        }
554        for (r, row) in t.rows.iter().enumerate() {
555            let mut grid_row = Vec::with_capacity(num_cols);
556            for c in 0..num_cols {
557                let (ar, ac) = anchors[r * num_cols + c];
558                if (ar, ac) == (r, c) {
559                    let (er, ec) = extent[r * num_cols + c];
560                    let text = row.get(c).map(|s| cell_text(s)).unwrap_or_default();
561                    let column_header = match s.filter(|s| !s.col_header.is_empty()) {
562                        Some(s) => flag(Some(&s.col_header), r, c),
563                        None => r == 0,
564                    };
565                    slot[r * num_cols + c] = Some(cells.len());
566                    cells.push(cell_value(
567                        er - r + 1,
568                        ec - c + 1,
569                        r,
570                        er + 1,
571                        c,
572                        ec + 1,
573                        text,
574                        column_header,
575                        flag(s.map(|s| &s.row_header), r, c),
576                        false,
577                        None,
578                    ));
579                }
580                grid_row.push(match slot[ar * num_cols + ac] {
581                    Some(i) => cells[i].clone(),
582                    None => Value::Null,
583                });
584            }
585            grid.push(grid_row);
586        }
587    }
588    json!({
589        "table_cells": cells,
590        "num_rows": num_rows,
591        "num_cols": num_cols,
592        "orientation": "rot_0",
593        "grid": grid,
594    })
595}
596
597#[derive(Default)]
598struct Builder {
599    /// Write the internal `_notes` / `_note_body` keys of tree text items
600    /// ([`crate::tree::TreeItem::notes`]) — for the Pandoc writer only
601    /// ([`to_json_with_notes`]); docling's JSON has no such fields.
602    note_keys: bool,
603    texts: Vec<Value>,
604    groups: Vec<Value>,
605    tables: Vec<Value>,
606    pictures: Vec<Value>,
607    field_regions: Vec<Value>,
608    field_items: Vec<Value>,
609    key_value_items: Vec<Value>,
610    /// Pages seen so far (`page_no`, width, height in points) — from the
611    /// [`Node::PageInfo`] markers the PDF paths emit; empty for every other
612    /// backend, which keeps their JSON byte-identical (`"pages": {}`, no prov).
613    pages: Vec<(usize, f64, f64)>,
614    /// The page the walk is currently on (0 before the first marker).
615    cur_page: usize,
616    cur_w: f64,
617    cur_h: f64,
618    /// The enclosing [`Node::Located`] wrapper's 0–511 grid box, waiting to be
619    /// consumed as the next item's provenance.
620    pending_loc: Option<[u16; 4]>,
621    /// The enclosing [`Node::Prov`] wrapper's (or the tree item's) exact
622    /// provenance, which takes precedence over the grid box.
623    pending_exact: Option<ExactProv>,
624    /// `$ref`s an item wants placed in its parent's `children` *before* its
625    /// own — a chart's caption item, which docling's office backends add to
626    /// the container ahead of the picture that references it.
627    pending_siblings: Vec<Value>,
628    /// `$ref`s an item wants placed in its parent's `children` right *after*
629    /// its own — an HTML `<figure>`-wrapped table's caption
630    /// ([`CaptionParent::ContainerAfter`]).
631    pending_after: Vec<Value>,
632    /// Caption `$ref`s that hang off `#/body` while their item sits deeper
633    /// ([`CaptionParent::Body`]): docling appends them to the body's children
634    /// as they are created, so they follow the top-level item being walked.
635    pending_body: Vec<Value>,
636    /// What each [`Node::CommentSection`] is referenced by, in document order —
637    /// its group `$ref`, or its note text's when the section says so. The index
638    /// is what a [`Node::Commented`] annotation carries.
639    comment_groups: Vec<String>,
640    /// The last `comment_section` group emitted, as `(name, self_ref)`: a
641    /// following section of the same name adds its note to that group rather
642    /// than opening another — one `comment-{sheet}-{cell}` group holds every
643    /// message of a threaded comment (docling#4353).
644    last_comment_section: Option<(String, String)>,
645    /// Annotated items awaiting their refs: comments are usually emitted
646    /// *after* the body they annotate (docx appends them), so the link is
647    /// patched in once the whole document has been walked.
648    pending_comments: Vec<(String, Vec<usize>)>,
649}
650
651impl Builder {
652    /// Consume the pending location (if any) into a docling `prov` array: the
653    /// 0-511 grid denormalized against the current page into BOTTOMLEFT
654    /// points, rounded to 2 decimals like docling's own export. `char_len` is
655    /// the item's text length in characters (0 for tables and pictures, whose
656    /// charspan docling emits as `[0, 0]`).
657    fn take_prov(&mut self, char_len: usize) -> Value {
658        let prov = self.prov_json(char_len, false);
659        self.pending_exact = None;
660        self.pending_loc = None;
661        prov
662    }
663
664    /// The pending provenance without consuming it. An exact [`Node::Prov`]
665    /// box wins over the grid; its own `charspan` is used unless
666    /// `span_over_text` asks for `[0, char_len]` (a chart caption's span
667    /// covers the caption text where the chart's is `[0, 0]`).
668    fn prov_json(&self, char_len: usize, span_over_text: bool) -> Value {
669        let r2 = |v: f64| (v * 100.0).round() / 100.0;
670        if let Some(ExactProv {
671            page_no,
672            bbox: [l, t, r, b],
673            bottom_left,
674            charspan,
675        }) = self.pending_exact
676        {
677            let charspan = if span_over_text {
678                [0, char_len]
679            } else {
680                charspan
681            };
682            return json!([{
683                "page_no": page_no,
684                "bbox": {
685                    "l": r2(l), "t": r2(t), "r": r2(r), "b": r2(b),
686                    "coord_origin": if bottom_left { "BOTTOMLEFT" } else { "TOPLEFT" },
687                },
688                "charspan": charspan,
689            }]);
690        }
691        let Some([x0, y0, x1, y1]) = self.pending_loc else {
692            return json!([]);
693        };
694        // An all-zero grid box is the sentinel for "this item has no geometry"
695        // (a slide's speaker notes, say). docling writes a zero bbox for it,
696        // not a box spanning the page, which is what denormalizing would give.
697        if [x0, y0, x1, y1] == [0, 0, 0, 0] {
698            return json!([{
699                "page_no": self.cur_page,
700                "bbox": { "l": 0.0, "t": 0.0, "r": 0.0, "b": 0.0, "coord_origin": "BOTTOMLEFT" },
701                "charspan": [0, char_len],
702            }]);
703        }
704        json!([{
705            "page_no": self.cur_page,
706            "bbox": {
707                "l": r2(x0 as f64 * self.cur_w / 512.0),
708                "t": r2(self.cur_h - y0 as f64 * self.cur_h / 512.0),
709                "r": r2(x1 as f64 * self.cur_w / 512.0),
710                "b": r2(self.cur_h - y1 as f64 * self.cur_h / 512.0),
711                "coord_origin": "BOTTOMLEFT",
712            },
713            "charspan": [0, char_len],
714        }])
715    }
716
717    /// Adopt a node's own location field (tables, formulas, list items carry
718    /// one instead of a [`Node::Located`] wrapper) when no wrapper is pending.
719    fn adopt_loc(&mut self, loc: Option<[u16; 4]>) {
720        if self.pending_loc.is_none() && self.cur_page > 0 {
721            self.pending_loc = loc;
722        }
723    }
724
725    /// Resolve the [`Node::Commented`] annotations collected during the walk
726    /// into docling's `comments: [{"$ref": "#/groups/N"}]` key on the annotated
727    /// item. It has to run after the whole walk: docx appends its comment
728    /// bodies, so the groups they live in are usually allocated *later* than
729    /// the paragraphs pointing at them. docling emits the key between `prov`
730    /// and `orig`, so insert it in place rather than appending (serde_json runs
731    /// with `preserve_order`, i.e. key order is output order).
732    fn link_comments(&mut self) {
733        let refs: Vec<(String, Vec<Value>)> = std::mem::take(&mut self.pending_comments)
734            .into_iter()
735            .map(|(item, comments)| {
736                let refs = comments
737                    .iter()
738                    .filter_map(|i| self.comment_groups.get(*i))
739                    .map(|r| json!({ "$ref": r }))
740                    .collect();
741                (item, refs)
742            })
743            .collect();
744        for (item, comment_refs) in refs {
745            if comment_refs.is_empty() {
746                continue;
747            }
748            let Some(target) = self.item_mut(&item) else {
749                continue;
750            };
751            let Some(obj) = target.as_object_mut() else {
752                continue;
753            };
754            let tail: Vec<(String, Value)> = obj
755                .iter()
756                .skip_while(|(k, _)| k.as_str() != "prov")
757                .skip(1)
758                .map(|(k, v)| (k.clone(), v.clone()))
759                .collect();
760            for (k, _) in &tail {
761                obj.shift_remove(k);
762            }
763            obj.insert("comments".into(), Value::Array(comment_refs));
764            for (k, v) in tail {
765                obj.insert(k, v);
766            }
767        }
768    }
769
770    /// The stored JSON object a `#/texts/N`-style self-ref points at.
771    fn item_mut(&mut self, self_ref: &str) -> Option<&mut Value> {
772        let idx = ref_index(self_ref)?;
773        let bucket = if self_ref.starts_with("#/texts/") {
774            &mut self.texts
775        } else if self_ref.starts_with("#/tables/") {
776            &mut self.tables
777        } else if self_ref.starts_with("#/pictures/") {
778            &mut self.pictures
779        } else if self_ref.starts_with("#/groups/") {
780            &mut self.groups
781        } else {
782            return None;
783        };
784        bucket.get_mut(idx)
785    }
786
787    /// Serialize a backend-built [`ItemTree`](crate::tree::ItemTree): every
788    /// item in creation order into its bucket, with the parent / children /
789    /// layer the tree recorded. Returns the body's `children` refs.
790    fn write_tree(&mut self, tree: &crate::tree::ItemTree) -> Vec<Value> {
791        use crate::tree::TreeKind;
792        // Every item's `self_ref` first: children may be listed before they
793        // are written (a rich cell's group is created after its content).
794        let mut refs: Vec<String> = Vec::with_capacity(tree.items.len());
795        let (mut nt, mut ng, mut ntb, mut np, mut nf, mut nk) = (0, 0, 0, 0, 0, 0);
796        for item in &tree.items {
797            if item.deleted {
798                refs.push(String::new());
799                continue;
800            }
801            let r = match &item.kind {
802                TreeKind::Text { .. } | TreeKind::Code { .. } => {
803                    nt += 1;
804                    format!("#/texts/{}", nt - 1)
805                }
806                TreeKind::Group { .. } => {
807                    ng += 1;
808                    format!("#/groups/{}", ng - 1)
809                }
810                TreeKind::Table { .. } => {
811                    ntb += 1;
812                    format!("#/tables/{}", ntb - 1)
813                }
814                TreeKind::Picture { .. } => {
815                    np += 1;
816                    format!("#/pictures/{}", np - 1)
817                }
818                TreeKind::FieldRegion { items } => {
819                    // A region's marker / key / value parts are text items
820                    // too, numbered where docling creates them.
821                    nt += items
822                        .iter()
823                        .map(|i| {
824                            [&i.marker, &i.key, &i.value]
825                                .iter()
826                                .filter(|p| p.is_some())
827                                .count()
828                        })
829                        .sum::<usize>();
830                    nf += 1;
831                    format!("#/field_regions/{}", nf - 1)
832                }
833                TreeKind::KeyValueGraph { .. } => {
834                    nk += 1;
835                    format!("#/key_value_items/{}", nk - 1)
836                }
837            };
838            refs.push(r);
839        }
840        let ref_of = |id: usize| json!({ "$ref": refs[id] });
841        for (id, item) in tree.items.iter().enumerate() {
842            if item.deleted {
843                continue;
844            }
845            let parent = item.parent.map_or("#/body", |p| refs[p].as_str());
846            // A deleted item has no ref; one still listed as a child (a stale
847            // backend link) is left out rather than written as `"$ref": ""`,
848            // which docling-core rejects on load (#527).
849            let children: Vec<Value> = item
850                .children
851                .iter()
852                .filter(|&&c| !tree.items[c].deleted)
853                .map(|&c| ref_of(c))
854                .collect();
855            let layer = item.layer.map_or("body", |l| l.value());
856            // The item's own provenance, consumed by the writer below
857            // (`take_prov`); an item without one writes `prov: []`.
858            self.pending_exact = item.prov.as_ref().map(ExactProv::from);
859            let self_ref = match &item.kind {
860                TreeKind::Text {
861                    label,
862                    text,
863                    orig,
864                    formatting,
865                    hyperlink,
866                    level,
867                    list,
868                } => {
869                    // docling's field order: …, text, formatting, hyperlink,
870                    // then the subclass fields (`level`; `enumerated`, `marker`).
871                    let mut tail = serde_json::Map::new();
872                    if let Some(f) = formatting {
873                        tail.insert("formatting".into(), formatting_json(f));
874                    }
875                    if let Some(h) = hyperlink {
876                        tail.insert("hyperlink".into(), json!(h));
877                    }
878                    if let Some(l) = level {
879                        tail.insert("level".into(), json!(l));
880                    }
881                    if let Some(l) = list {
882                        tail.insert("enumerated".into(), json!(l.enumerated));
883                        tail.insert("marker".into(), json!(l.marker));
884                    }
885                    let r = format!("#/texts/{}", self.texts.len());
886                    let prov = self.take_prov(text.chars().count());
887                    let mut item_json = json!({
888                        "self_ref": r,
889                        "parent": { "$ref": parent },
890                        "children": children,
891                        "content_layer": layer,
892                        "label": label,
893                        "prov": prov,
894                    });
895                    // docling's `comments` back-refs sit between `prov` and
896                    // `orig`, and are written only when set.
897                    if !item.comments.is_empty() {
898                        item_json["comments"] =
899                            Value::Array(item.comments.iter().map(|&c| ref_of(c)).collect());
900                    }
901                    // `DocItem.source`, likewise only when set: a WebVTT
902                    // cue's `TrackSource`, whose `None` fields are omitted.
903                    if let Some(track) = &item.source {
904                        item_json["source"] = json!([track_json(track)]);
905                    }
906                    merge(
907                        &mut item_json,
908                        json!({
909                            "orig": orig.as_deref().unwrap_or(text),
910                            "text": text,
911                        }),
912                    );
913                    merge(&mut item_json, Value::Object(tail));
914                    if self.note_keys {
915                        if !item.notes.is_empty() {
916                            item_json["_notes"] = Value::Array(
917                                item.notes
918                                    .iter()
919                                    .map(|n| json!([n.offset, n.text]))
920                                    .collect(),
921                            );
922                        }
923                        if item.note_body {
924                            item_json["_note_body"] = json!(true);
925                        }
926                    }
927                    self.texts.push(item_json);
928                    r
929                }
930                TreeKind::Code {
931                    text,
932                    orig,
933                    language,
934                    formatting,
935                    hyperlink,
936                } => {
937                    let r = format!("#/texts/{}", self.texts.len());
938                    let prov = self.take_prov(text.chars().count());
939                    let mut item_json = json!({
940                        "self_ref": r,
941                        "parent": { "$ref": parent },
942                        "children": children,
943                        "content_layer": layer,
944                        "label": "code",
945                        "prov": prov,
946                    });
947                    if !item.comments.is_empty() {
948                        item_json["comments"] =
949                            Value::Array(item.comments.iter().map(|&c| ref_of(c)).collect());
950                    }
951                    merge(
952                        &mut item_json,
953                        json!({
954                            "orig": orig.as_deref().unwrap_or(text),
955                            "text": text,
956                        }),
957                    );
958                    if let Some(f) = formatting {
959                        item_json["formatting"] = formatting_json(f);
960                    }
961                    if let Some(h) = hyperlink {
962                        item_json["hyperlink"] = json!(h);
963                    }
964                    merge(
965                        &mut item_json,
966                        json!({
967                            "captions": [],
968                            "references": [],
969                            "footnotes": [],
970                            "code_language": code_language(language.as_deref()),
971                        }),
972                    );
973                    self.texts.push(item_json);
974                    r
975                }
976                TreeKind::Group { label, name } => {
977                    self.pending_exact = None;
978                    let r = format!("#/groups/{}", self.groups.len());
979                    self.groups.push(json!({
980                        "self_ref": r,
981                        "parent": { "$ref": parent },
982                        "children": children,
983                        "content_layer": layer,
984                        "name": name,
985                        "label": label,
986                    }));
987                    r
988                }
989                TreeKind::Table {
990                    table,
991                    rich_cells,
992                    captions,
993                } => {
994                    // docling's raw cell text: nothing to unescape or strip.
995                    let r = self.add_table_with(table, parent, true);
996                    let idx = ref_index(&r).expect("table ref");
997                    let t = &mut self.tables[idx];
998                    t["children"] = Value::Array(children);
999                    t["content_layer"] = json!(layer);
1000                    t["captions"] = Value::Array(captions.iter().map(|&c| ref_of(c)).collect());
1001                    // A `RichTableCell` is the plain cell plus a `ref` to the
1002                    // group holding its content — on `table_cells` only; the
1003                    // derived `grid` shows plain cells.
1004                    for &(row, col, group) in rich_cells {
1005                        let cell_ref = ref_of(group);
1006                        let hit = |c: &Value| {
1007                            c["start_row_offset_idx"] == json!(row)
1008                                && c["start_col_offset_idx"] == json!(col)
1009                        };
1010                        if let Some(cells) = t["data"]["table_cells"].as_array_mut() {
1011                            for c in cells.iter_mut().filter(|c| hit(c)) {
1012                                c["ref"] = cell_ref.clone();
1013                            }
1014                        }
1015                    }
1016                    r
1017                }
1018                TreeKind::Picture {
1019                    captions,
1020                    image,
1021                    classification,
1022                    confidence,
1023                    chart,
1024                    dpi,
1025                } => {
1026                    // A chart's meta: the kind as the one classification
1027                    // prediction (pydantic's field order puts `confidence`
1028                    // first when present), then the reconstructed data grid
1029                    // (#405).
1030                    let mut meta = classification.as_ref().map(|c| {
1031                        let mut pred = serde_json::Map::new();
1032                        if let Some(conf) = confidence {
1033                            pred.insert("confidence".into(), json!(conf));
1034                        }
1035                        pred.insert("class_name".into(), json!(c));
1036                        json!({ "classification": { "predictions": [pred] } })
1037                    });
1038                    if let (Some(m), Some(t)) = (meta.as_mut(), chart) {
1039                        if !t.rows.is_empty() {
1040                            m["tabular_chart"] = json!({ "chart_data": table_data(t) });
1041                        }
1042                    }
1043                    let prov = self.take_prov(0);
1044                    let r = self.push_picture(
1045                        prov,
1046                        captions.iter().map(|&c| ref_of(c)).collect(),
1047                        children,
1048                        image.as_ref(),
1049                        meta,
1050                        parent,
1051                    );
1052                    if let Some(idx) = ref_index(&r) {
1053                        self.pictures[idx]["content_layer"] = json!(layer);
1054                        // The image's dpi is the file's when the backend read
1055                        // it (python-pptx does); the default 72 otherwise.
1056                        if let (Some(dpi), Some(img)) = (dpi, self.pictures[idx].get_mut("image")) {
1057                            img["dpi"] = json!(dpi);
1058                        }
1059                    }
1060                    r
1061                }
1062                TreeKind::FieldRegion { items } => {
1063                    self.pending_exact = None;
1064                    let r = self.add_field_region(items, parent);
1065                    if let Some(region) = self.field_regions.last_mut() {
1066                        region["content_layer"] = json!(layer);
1067                    }
1068                    r
1069                }
1070                TreeKind::KeyValueGraph { cells, links } => {
1071                    self.pending_exact = None;
1072                    let r = self.add_key_value_graph(cells, links, parent);
1073                    if let Some(item) = self.key_value_items.last_mut() {
1074                        item["content_layer"] = json!(layer);
1075                    }
1076                    r
1077                }
1078            };
1079            debug_assert_eq!(self_ref, refs[id], "tree item {id} numbered out of order");
1080        }
1081        tree.body
1082            .iter()
1083            .filter(|&&c| !tree.items[c].deleted)
1084            .map(|&c| ref_of(c))
1085            .collect()
1086    }
1087
1088    fn add_node(&mut self, node: &Node, parent: &str) -> Option<String> {
1089        match node {
1090            Node::Heading { level: 1, text } => {
1091                Some(self.add_text("title", text, parent, json!({})))
1092            }
1093            Node::Heading { level, text } => Some(self.add_text(
1094                "section_header",
1095                text,
1096                parent,
1097                json!({ "level": level.saturating_sub(1) }),
1098            )),
1099            Node::Caption { text, href } => {
1100                let extra = match href {
1101                    Some(url) => json!({ "hyperlink": url }),
1102                    None => json!({}),
1103                };
1104                Some(self.add_text("caption", text, parent, extra))
1105            }
1106            Node::Paragraph { text } => {
1107                // A whole-paragraph display equation is a formula item (docling
1108                // wraps it in `$$…$$` and, unlike a text item, never escapes it).
1109                let t = text.trim();
1110                match t.strip_prefix("$$").and_then(|s| s.strip_suffix("$$")) {
1111                    Some(inner) if !inner.is_empty() => Some(self.add_formula(inner, parent)),
1112                    _ => Some(self.add_text("text", text, parent, json!({}))),
1113                }
1114            }
1115            Node::CheckboxItem { checked, text } => {
1116                // JSON keeps the task-list form as a plain text item (the
1117                // `checkbox_selected`/`checkbox_unselected` label is DocLang-only).
1118                let mark = if *checked { "- [x] " } else { "- [ ] " };
1119                Some(self.add_text("text", &format!("{mark}{text}"), parent, json!({})))
1120            }
1121            Node::Code {
1122                language,
1123                text,
1124                orig,
1125                ..
1126            } => Some(self.add_code(text, language.as_deref(), orig.as_deref(), parent)),
1127            // A CodeFormula-decoded display formula: `text` carries the LaTeX,
1128            // `orig` the raw glyph extraction (docling's enriched shape).
1129            Node::Formula {
1130                latex,
1131                orig,
1132                location,
1133            } => {
1134                self.adopt_loc(*location);
1135                Some(self.add_formula_item(latex, orig, parent))
1136            }
1137            // docling's notes-layer `comment_section` group holding the
1138            // comment's text item. What the annotated items point at differs
1139            // upstream: the docx backend links the group (so a comment's
1140            // replies group together), everything going through
1141            // docling-core's `add_comment` links the note text itself.
1142            Node::CommentSection {
1143                name,
1144                text,
1145                refs_note_text,
1146                grouped,
1147            } => {
1148                if !*grouped {
1149                    // docling-core's bare `add_comment`: the note text sits
1150                    // directly under the parent and is what the back-refs
1151                    // point at.
1152                    let child =
1153                        self.add_text("text", text, parent, json!({ "content_layer": "notes" }));
1154                    self.comment_groups.push(child.clone());
1155                    return Some(child);
1156                }
1157                if let Some((_, self_ref)) = self
1158                    .last_comment_section
1159                    .as_ref()
1160                    .filter(|(n, _)| n == name)
1161                    .cloned()
1162                {
1163                    // Another message of the same thread: a further note in
1164                    // the group already open for this cell.
1165                    let child =
1166                        self.add_text("text", text, &self_ref, json!({ "content_layer": "notes" }));
1167                    if let Some(children) =
1168                        self.groups[group_index(&self_ref)]["children"].as_array_mut()
1169                    {
1170                        children.push(json!({ "$ref": child }));
1171                    }
1172                    self.comment_groups.push(if *refs_note_text {
1173                        child
1174                    } else {
1175                        self_ref.clone()
1176                    });
1177                    return Some(self_ref);
1178                }
1179                let self_ref = format!("#/groups/{}", self.groups.len());
1180                self.groups.push(Value::Null);
1181                let child =
1182                    self.add_text("text", text, &self_ref, json!({ "content_layer": "notes" }));
1183                self.groups[group_index(&self_ref)] = json!({
1184                    "self_ref": self_ref,
1185                    "parent": { "$ref": parent },
1186                    "children": [{ "$ref": child }],
1187                    "content_layer": "notes",
1188                    "name": name,
1189                    "label": "comment_section",
1190                });
1191                self.last_comment_section = Some((name.clone(), self_ref.clone()));
1192                self.comment_groups.push(if *refs_note_text {
1193                    child
1194                } else {
1195                    self_ref.clone()
1196                });
1197                Some(self_ref)
1198            }
1199            // The annotation itself is a cross-reference: emit the item, then
1200            // remember it so the group refs can be filled in at the end.
1201            Node::Commented { comments, inner } => {
1202                let item = self.add_node(inner, parent)?;
1203                if !comments.is_empty() {
1204                    self.pending_comments.push((item.clone(), comments.clone()));
1205                }
1206                Some(item)
1207            }
1208            Node::Table(t) => Some(self.add_table(t, parent)),
1209            Node::Picture {
1210                caption,
1211                caption_href,
1212                image,
1213                classification,
1214                caption_parent,
1215            } => Some(self.add_picture(
1216                caption.as_deref(),
1217                caption_href.as_deref(),
1218                image.as_ref(),
1219                classification.as_deref().map(classification_meta),
1220                parent,
1221                *caption_parent,
1222            )),
1223            // A chart is a picture item in the JSON with docling's chart
1224            // meta — `classification` (the chart kind, as the one prediction)
1225            // and `tabular_chart.chart_data`, the series reconstructed as a
1226            // `TableData` (#405) — and no image payload.
1227            Node::Chart {
1228                kind,
1229                table,
1230                caption,
1231                location,
1232            } => {
1233                self.adopt_loc(*location);
1234                let mut meta = json!({
1235                    "classification": { "predictions": [{ "class_name": kind }] },
1236                });
1237                if !table.rows.is_empty() {
1238                    meta["tabular_chart"] = json!({ "chart_data": table_data(table) });
1239                }
1240                // docling's office backends add the chart's title as a caption
1241                // item of the *container* (the sheet group, the slide), listed
1242                // before the picture that references it, with the chart's own
1243                // box and a charspan over the caption text — not as a child
1244                // of the picture, which is where a PDF caption lives.
1245                let mut captions = Vec::new();
1246                if let Some(cap) = caption.as_deref().filter(|c| !c.is_empty()) {
1247                    let prov = self.prov_json(unescape_text(cap).chars().count(), true);
1248                    let cap_ref = self.add_text_with("caption", cap, parent, json!({}), prov);
1249                    self.pending_siblings.push(json!({ "$ref": cap_ref }));
1250                    captions.push(json!({ "$ref": cap_ref }));
1251                }
1252                let prov = self.take_prov(0);
1253                Some(self.push_picture(prov, captions, Vec::new(), None, Some(meta), parent))
1254            }
1255            // A DocLang-only node is omitted from the JSON body.
1256            Node::DoclangOnly(_) => None,
1257            Node::Group {
1258                label,
1259                name,
1260                layer,
1261                children,
1262            } => Some(self.add_group(label, name.as_deref(), *layer, children, parent)),
1263            Node::FieldRegion { items } => Some(self.add_field_region(items, parent)),
1264            Node::KeyValueGraph { cells, links } => {
1265                Some(self.add_key_value_graph(cells, links, parent))
1266            }
1267            // A rich inline group is a text item over its Markdown text; the
1268            // structured runs are DocLang-only, so the JSON matches a paragraph.
1269            Node::InlineGroup { md_text, .. } => {
1270                Some(self.add_text("text", md_text, parent, json!({})))
1271            }
1272            // A plain-text backend dump is a single text item over the file body.
1273            Node::TextDump(text) => Some(self.add_text("text", text, parent, json!({}))),
1274            // Speaker notes are content a deck carries, and docling puts them
1275            // in the JSON on their own layer, so a consumer reading only JSON
1276            // can pick them (#402). Page furniture stays out of the flat
1277            // path; a backend that builds docling's item tree (HTML) puts its
1278            // furniture-layer items in the JSON through `write_tree`.
1279            Node::Furniture {
1280                layer: ContentLayer::Notes,
1281                inner,
1282            } => {
1283                let item = self.add_node(inner, parent)?;
1284                self.set_layer(&item, "notes");
1285                Some(item)
1286            }
1287            Node::Furniture { .. } => None,
1288            // PDF page headers and footers: docling writes them as body-parented
1289            // `page_header`/`page_footer` text items on the furniture layer, so a
1290            // JSON consumer can read running headers (printed page ids, dates).
1291            Node::PageFurniture {
1292                footer,
1293                location,
1294                text,
1295            } => {
1296                if self.cur_page > 0 {
1297                    self.pending_loc = Some(*location);
1298                }
1299                let label = if *footer {
1300                    "page_footer"
1301                } else {
1302                    "page_header"
1303                };
1304                let item = self.add_text(label, text, parent, json!({}));
1305                self.pending_loc = None;
1306                self.set_layer(&item, "furniture");
1307                Some(item)
1308            }
1309            // A labelled furniture paragraph (a `.doc` header / footer or
1310            // note body, #535): the item docling's office backends write.
1311            Node::FurnitureText { label, text } => {
1312                let item = self.add_text(label, text, parent, json!({}));
1313                self.set_layer(&item, "furniture");
1314                Some(item)
1315            }
1316            // A PDF picture's contained text (docling's `_add_child_elements`):
1317            // items parented to the picture just written, listed after its
1318            // caption in that picture's `children`.
1319            Node::PictureChildren(children) => {
1320                let pic = self.pictures.len().checked_sub(1)?;
1321                let pic_ref = format!("#/pictures/{pic}");
1322                let refs = self.walk_into(children, &pic_ref);
1323                if let Some(list) = self.pictures[pic]["children"].as_array_mut() {
1324                    list.extend(refs);
1325                }
1326                None
1327            }
1328            // A location wrapper turns into the wrapped item's `prov` entry —
1329            // but only on pages the PDF paths described with a PageInfo marker
1330            // (other geometry-bearing backends, e.g. PPTX shapes, keep their
1331            // pre-#171 provenance-less JSON until they emit markers too).
1332            Node::Located { location, inner } => {
1333                if self.cur_page > 0 {
1334                    self.pending_loc = Some(*location);
1335                }
1336                let r = self.add_node(inner, parent);
1337                self.pending_loc = None;
1338                r
1339            }
1340            Node::Prov {
1341                page_no,
1342                bbox,
1343                charspan,
1344                inner,
1345                ..
1346            } => {
1347                self.pending_exact = Some(ExactProv {
1348                    page_no: *page_no,
1349                    bbox: bbox.map(f64::from),
1350                    bottom_left: false,
1351                    charspan: *charspan,
1352                });
1353                let r = self.add_node(inner, parent);
1354                self.pending_exact = None;
1355                r
1356            }
1357            // Page breaks are DocLang-only; docling omits them from the JSON body.
1358            Node::PageBreak => None,
1359            // The page marker: record the page's number and size for the
1360            // `pages` map, and denormalize every following location against it.
1361            Node::PageInfo {
1362                page_no,
1363                width,
1364                height,
1365            } => {
1366                self.cur_page = *page_no;
1367                self.cur_w = *width as f64;
1368                self.cur_h = *height as f64;
1369                if *page_no > 0 {
1370                    self.pages.push((*page_no, self.cur_w, self.cur_h));
1371                }
1372                None
1373            }
1374            // Handled by `add_list` in `walk`.
1375            Node::ListItem { .. } => None,
1376        }
1377    }
1378
1379    /// A form key-value region: `field_regions/N` holds the region, each field is
1380    /// a `field_items/M` whose children are its `marker` / `field_key` /
1381    /// `field_value` texts (absent parts are simply omitted).
1382    fn add_field_region(&mut self, items: &[crate::FieldItem], parent: &str) -> String {
1383        let self_ref = format!("#/field_regions/{}", self.field_regions.len());
1384        self.field_regions.push(Value::Null);
1385        let region_index = self.field_regions.len() - 1;
1386        let mut item_refs = Vec::new();
1387        for item in items {
1388            item_refs.push(json!({ "$ref": self.add_field_item(item, &self_ref) }));
1389        }
1390        self.field_regions[region_index] = json!({
1391            "self_ref": self_ref,
1392            "parent": { "$ref": parent },
1393            "children": item_refs,
1394            "content_layer": "body",
1395            "label": "field_region",
1396            "prov": [],
1397        });
1398        self_ref
1399    }
1400
1401    /// A `KeyValueItem`: docling's `GraphData` written cell for cell and link
1402    /// for link (`key_value_items/N`), the item itself childless and without
1403    /// provenance, the way the XBRL backend creates it.
1404    fn add_key_value_graph(
1405        &mut self,
1406        cells: &[crate::GraphCell],
1407        links: &[crate::GraphLink],
1408        parent: &str,
1409    ) -> String {
1410        let self_ref = format!("#/key_value_items/{}", self.key_value_items.len());
1411        let cells: Vec<Value> = cells
1412            .iter()
1413            .map(|c| {
1414                json!({
1415                    "label": c.label,
1416                    "cell_id": c.cell_id,
1417                    "text": c.text,
1418                    "orig": c.orig,
1419                })
1420            })
1421            .collect();
1422        let links: Vec<Value> = links
1423            .iter()
1424            .map(|l| {
1425                json!({
1426                    "label": l.label,
1427                    "source_cell_id": l.source_cell_id,
1428                    "target_cell_id": l.target_cell_id,
1429                })
1430            })
1431            .collect();
1432        self.key_value_items.push(json!({
1433            "self_ref": self_ref,
1434            "parent": { "$ref": parent },
1435            "children": [],
1436            "content_layer": "body",
1437            "label": "key_value_region",
1438            "prov": [],
1439            "captions": [],
1440            "references": [],
1441            "footnotes": [],
1442            "graph": { "cells": cells, "links": links },
1443        }));
1444        self_ref
1445    }
1446
1447    fn add_field_item(&mut self, item: &crate::FieldItem, parent: &str) -> String {
1448        let self_ref = format!("#/field_items/{}", self.field_items.len());
1449        self.field_items.push(Value::Null);
1450        let item_index = self.field_items.len() - 1;
1451        let mut child_refs = Vec::new();
1452        for (label, text) in [
1453            ("marker", &item.marker),
1454            ("field_key", &item.key),
1455            ("field_value", &item.value),
1456        ] {
1457            if let Some(text) = text {
1458                // A value's `kind` (docling's `read_only` / `fillable`)
1459                // follows its text.
1460                let extra = match (label, &item.value_kind) {
1461                    ("field_value", Some(kind)) => json!({ "kind": kind }),
1462                    _ => json!({}),
1463                };
1464                child_refs.push(json!({ "$ref": self.add_text(label, text, &self_ref, extra) }));
1465            }
1466        }
1467        self.field_items[item_index] = json!({
1468            "self_ref": self_ref,
1469            "parent": { "$ref": parent },
1470            "children": child_refs,
1471            "content_layer": "body",
1472            "label": "field_item",
1473            "prov": [],
1474        });
1475        self_ref
1476    }
1477
1478    /// Move an already-emitted item onto a content layer. Notes are single
1479    /// text items today; a deeper notes subtree would need its children moved
1480    /// too, and no backend builds one.
1481    fn set_layer(&mut self, self_ref: &str, layer: &str) {
1482        let bucket = match self_ref.split('/').nth(1) {
1483            Some("texts") => &mut self.texts,
1484            Some("tables") => &mut self.tables,
1485            Some("pictures") => &mut self.pictures,
1486            Some("groups") => &mut self.groups,
1487            _ => return,
1488        };
1489        if let Some(item) = self_ref
1490            .rsplit('/')
1491            .next()
1492            .and_then(|i| i.parse::<usize>().ok())
1493            .and_then(|i| bucket.get_mut(i))
1494        {
1495            item["content_layer"] = json!(layer);
1496        }
1497    }
1498
1499    fn add_text(&mut self, label: &str, text: &str, parent: &str, extra: Value) -> String {
1500        let prov = self.take_prov(unescape_text(text).chars().count());
1501        self.add_text_with(label, text, parent, extra, prov)
1502    }
1503
1504    /// [`Self::add_text`] with an explicit `prov` (a chart caption shares the
1505    /// chart's box without consuming it).
1506    fn add_text_with(
1507        &mut self,
1508        label: &str,
1509        text: &str,
1510        parent: &str,
1511        extra: Value,
1512        prov: Value,
1513    ) -> String {
1514        let self_ref = format!("#/texts/{}", self.texts.len());
1515        let raw = unescape_text(text);
1516        let mut item = json!({
1517            "self_ref": self_ref,
1518            "parent": { "$ref": parent },
1519            "children": [],
1520            "content_layer": "body",
1521            "label": label,
1522            "prov": prov,
1523            "orig": raw,
1524            "text": raw,
1525        });
1526        merge(&mut item, extra);
1527        self.texts.push(item);
1528        self_ref
1529    }
1530
1531    /// A display-math formula item. `latex` is the raw content (no `$$`); docling
1532    /// re-wraps it and never escapes it.
1533    fn add_formula(&mut self, latex: &str, parent: &str) -> String {
1534        let self_ref = format!("#/texts/{}", self.texts.len());
1535        let prov = self.take_prov(latex.chars().count());
1536        self.texts.push(json!({
1537            "self_ref": self_ref,
1538            "parent": { "$ref": parent },
1539            "children": [],
1540            "content_layer": "body",
1541            "label": "formula",
1542            "prov": prov,
1543            "orig": latex,
1544            "text": latex,
1545        }));
1546        self_ref
1547    }
1548
1549    /// A CodeFormula-enriched display formula: `text` is the model's LaTeX
1550    /// while `orig` keeps the raw glyph extraction (docling's enriched shape;
1551    /// the plain [`Self::add_formula`] above sets both to the same string).
1552    fn add_formula_item(&mut self, latex: &str, orig: &str, parent: &str) -> String {
1553        let self_ref = format!("#/texts/{}", self.texts.len());
1554        let prov = self.take_prov(latex.chars().count());
1555        self.texts.push(json!({
1556            "self_ref": self_ref,
1557            "parent": { "$ref": parent },
1558            "children": [],
1559            "content_layer": "body",
1560            "label": "formula",
1561            "prov": prov,
1562            "orig": orig,
1563            "text": latex,
1564        }));
1565        self_ref
1566    }
1567
1568    fn add_code(
1569        &mut self,
1570        text: &str,
1571        language: Option<&str>,
1572        orig: Option<&str>,
1573        parent: &str,
1574    ) -> String {
1575        let self_ref = format!("#/texts/{}", self.texts.len());
1576        let raw = unescape_text(text);
1577        let prov = self.take_prov(raw.chars().count());
1578        self.texts.push(json!({
1579            "self_ref": self_ref,
1580            "parent": { "$ref": parent },
1581            "children": [],
1582            "content_layer": "body",
1583            "label": "code",
1584            "prov": prov,
1585            // With code enrichment, `text` is the model's rewrite while `orig`
1586            // keeps the raw extraction; otherwise both are the same string.
1587            "orig": orig.map(unescape_text).unwrap_or_else(|| raw.clone()),
1588            "text": raw,
1589            "captions": [],
1590            "references": [],
1591            "footnotes": [],
1592            "code_language": code_language(language),
1593        }));
1594        self_ref
1595    }
1596
1597    /// Build a list group from a run of (possibly multi-level) list items. A
1598    /// deeper level starts a nested list under the preceding item.
1599    fn add_list(&mut self, items: &[Node], parent: &str) -> String {
1600        let self_ref = format!("#/groups/{}", self.groups.len());
1601        // reserve the slot so nested groups get later indices
1602        self.groups.push(Value::Null);
1603        let base = level_of(&items[0]);
1604        let mut children = Vec::new();
1605        let mut i = 0;
1606        while i < items.len() {
1607            // Empty paragraphs absorbed into the run (blank lines between items)
1608            // are not list items — skip them.
1609            if !matches!(items[i], Node::ListItem { .. }) {
1610                i += 1;
1611                continue;
1612            }
1613            let lvl = level_of(&items[i]);
1614            if lvl > base {
1615                // shouldn't happen at the head; skip defensively
1616                i += 1;
1617                continue;
1618            }
1619            let item_ref = self.add_list_item(&items[i], &self_ref);
1620            // collect any deeper items that nest under this one
1621            let mut j = i + 1;
1622            while j < items.len() && level_of(&items[j]) > base {
1623                j += 1;
1624            }
1625            if j > i + 1 {
1626                let mut nested = Vec::new();
1627                self.add_sibling_lists(&items[i + 1..j], &item_ref, &mut nested);
1628                // the nested list group(s) are children of this item
1629                if let Some(idx) = ref_index(&item_ref) {
1630                    self.texts[idx]["children"]
1631                        .as_array_mut()
1632                        .unwrap()
1633                        .extend(nested);
1634                }
1635            }
1636            children.push(json!({ "$ref": item_ref }));
1637            i = j;
1638        }
1639        self.groups[group_index(&self_ref)] = json!({
1640            "self_ref": self_ref,
1641            "parent": { "$ref": parent },
1642            "children": children,
1643            "content_layer": "body",
1644            "name": "list",
1645            "label": "list",
1646        });
1647        self_ref
1648    }
1649
1650    fn add_list_item(&mut self, node: &Node, parent: &str) -> String {
1651        let Node::ListItem {
1652            ordered,
1653            number,
1654            text,
1655            location,
1656            ..
1657        } = node
1658        else {
1659            unreachable!()
1660        };
1661        self.adopt_loc(*location);
1662        let self_ref = format!("#/texts/{}", self.texts.len());
1663        let raw = unescape_text(text);
1664        let prov = self.take_prov(raw.chars().count());
1665        let marker = if *ordered {
1666            format!("{number}.")
1667        } else {
1668            "-".to_string()
1669        };
1670        self.texts.push(json!({
1671            "self_ref": self_ref,
1672            "parent": { "$ref": parent },
1673            "children": [],
1674            "content_layer": "body",
1675            "label": "list_item",
1676            "prov": prov,
1677            "orig": raw,
1678            "text": raw,
1679            "enumerated": ordered,
1680            "marker": marker,
1681        }));
1682        self_ref
1683    }
1684
1685    fn add_table(&mut self, t: &Table, parent: &str) -> String {
1686        self.add_table_with(t, parent, false)
1687    }
1688
1689    /// [`Self::add_table`]; `raw` cell text is written verbatim (see
1690    /// [`table_data_with`]).
1691    fn add_table_with(&mut self, t: &Table, parent: &str, raw: bool) -> String {
1692        let self_ref = format!("#/tables/{}", self.tables.len());
1693        self.adopt_loc(t.location);
1694        let prov = self.take_prov(0);
1695        // The caption is a separate text item the table references (docling's
1696        // `TableItem.captions`), added before the grid so its box isn't
1697        // inherited by a later item.
1698        let (captions, children) = match t.caption.as_deref().filter(|c| !c.is_empty()) {
1699            Some(cap) => self.add_caption(cap, json!({}), &self_ref, parent, t.caption_parent),
1700            None => (Vec::new(), Vec::new()),
1701        };
1702        let data = table_data_with(t, raw);
1703        self.tables.push(json!({
1704            "self_ref": self_ref,
1705            "parent": { "$ref": parent },
1706            "children": children,
1707            "content_layer": "body",
1708            "label": "table",
1709            "prov": prov,
1710            "captions": captions,
1711            "references": [],
1712            "footnotes": [],
1713            "data": data,
1714            "annotations": [],
1715        }));
1716        self_ref
1717    }
1718
1719    /// Add a picture's or table's caption text item where `choice` says it
1720    /// hangs (#390), returning the `captions` entry for the item and the
1721    /// item's own `children` (the caption, when it is the item's child).
1722    /// The caption never consumes the item's pending provenance — the item
1723    /// takes its box first.
1724    fn add_caption(
1725        &mut self,
1726        text: &str,
1727        extra: Value,
1728        self_ref: &str,
1729        parent: &str,
1730        choice: CaptionParent,
1731    ) -> (Vec<Value>, Vec<Value>) {
1732        // docling's PDF pipeline parents the caption to the item; every
1733        // declarative backend leaves `add_text`'s default — the body — even
1734        // for an item inside a group; the office backends and HTML's
1735        // `<figure>` hang it off the item's container.
1736        let cap_parent = match choice {
1737            CaptionParent::Item => self_ref,
1738            CaptionParent::Container | CaptionParent::ContainerAfter => parent,
1739            CaptionParent::Body => "#/body",
1740        };
1741        let cap_ref = json!({ "$ref": self.add_text("caption", text, cap_parent, extra) });
1742        match choice {
1743            CaptionParent::Item => return (vec![cap_ref.clone()], vec![cap_ref]),
1744            // Created ahead of the item, so it precedes the item in the
1745            // container's children — and, on the body, in the body's.
1746            CaptionParent::Container => self.pending_siblings.push(cap_ref.clone()),
1747            CaptionParent::Body if parent == "#/body" => {
1748                self.pending_siblings.push(cap_ref.clone())
1749            }
1750            CaptionParent::ContainerAfter => self.pending_after.push(cap_ref.clone()),
1751            // The item sits deeper: the body's children get the caption after
1752            // the top-level item under walk, where docling appended it.
1753            CaptionParent::Body => self.pending_body.push(cap_ref.clone()),
1754        }
1755        (vec![cap_ref], Vec::new())
1756    }
1757
1758    /// `meta` is the picture's docling `PictureMeta` (a classifier's
1759    /// predictions, a chart's kind and data), `None` for a plain picture.
1760    fn add_picture(
1761        &mut self,
1762        caption: Option<&str>,
1763        caption_href: Option<&str>,
1764        image: Option<&crate::PictureImage>,
1765        meta: Option<Value>,
1766        parent: &str,
1767        caption_parent: CaptionParent,
1768    ) -> String {
1769        let self_ref = format!("#/pictures/{}", self.pictures.len());
1770        // Take the picture's own provenance before the caption text is added —
1771        // the caption is a separate item and must not inherit the crop's box.
1772        let prov = self.take_prov(0);
1773        let (captions, children) = match caption.filter(|c| !c.is_empty()) {
1774            Some(cap) => {
1775                // Emit the caption as a text item that the picture references. A
1776                // wrapping `<a href>`'s link rides as docling's `hyperlink` field
1777                // on the caption item (#328).
1778                let extra = match caption_href {
1779                    Some(href) => json!({ "hyperlink": href }),
1780                    None => json!({}),
1781                };
1782                self.add_caption(cap, extra, &self_ref, parent, caption_parent)
1783            }
1784            None => (Vec::new(), Vec::new()),
1785        };
1786        self.push_picture(prov, captions, children, image, meta, parent)
1787    }
1788
1789    /// Append the picture item itself — `prov`, `captions` and `children`
1790    /// (a PDF caption is the picture's child) already settled.
1791    fn push_picture(
1792        &mut self,
1793        prov: Value,
1794        captions: Vec<Value>,
1795        children: Vec<Value>,
1796        image: Option<&crate::PictureImage>,
1797        meta: Option<Value>,
1798        parent: &str,
1799    ) -> String {
1800        let self_ref = format!("#/pictures/{}", self.pictures.len());
1801        // The legacy `classification` annotation rides along with a
1802        // classifier's `meta` (see `classification_meta`); a chart's meta has
1803        // none, like docling's.
1804        let annotations = meta
1805            .as_ref()
1806            .and_then(|m| m.get("annotations").cloned())
1807            .unwrap_or_else(|| json!([]));
1808        let meta = meta.map(|mut m| {
1809            if let Some(obj) = m.as_object_mut() {
1810                obj.remove("annotations");
1811            }
1812            m
1813        });
1814        // `meta` sits between `content_layer` and `label` in docling's field
1815        // order (and `preserve_order` keeps ours byte-compatible), so the item
1816        // is built in one shot per shape rather than patched afterwards.
1817        let mut item = match meta {
1818            Some(meta) => json!({
1819                "self_ref": self_ref,
1820                "parent": { "$ref": parent },
1821                "children": children,
1822                "content_layer": "body",
1823                "meta": meta,
1824                "label": "picture",
1825                "prov": prov,
1826                "captions": captions,
1827                "references": [],
1828                "footnotes": [],
1829                "annotations": annotations,
1830            }),
1831            None => json!({
1832                "self_ref": self_ref,
1833                "parent": { "$ref": parent },
1834                "children": children,
1835                "content_layer": "body",
1836                "label": "picture",
1837                "prov": prov,
1838                "captions": captions,
1839                "references": [],
1840                "footnotes": [],
1841                "annotations": annotations,
1842            }),
1843        };
1844        // docling stores the extracted image as an `ImageRef` (data URI + size,
1845        // the size as floats) between `footnotes` and `annotations` — pydantic
1846        // field order, which `preserve_order` lets us reproduce by rebuilding
1847        // the tail.
1848        if let Some(img) = image {
1849            let image = image_ref_json(img);
1850            if let Some(obj) = item.as_object_mut() {
1851                let annotations = obj.remove("annotations").unwrap_or_else(|| json!([]));
1852                obj.insert("image".into(), image);
1853                obj.insert("annotations".into(), annotations);
1854            }
1855        }
1856        self.pictures.push(item);
1857        self_ref
1858    }
1859
1860    fn add_group(
1861        &mut self,
1862        label: &str,
1863        name: Option<&str>,
1864        layer: Option<ContentLayer>,
1865        nodes: &[Node],
1866        parent: &str,
1867    ) -> String {
1868        let self_ref = format!("#/groups/{}", self.groups.len());
1869        self.groups.push(Value::Null);
1870        // Everything the walk creates belongs to this group, so a non-body
1871        // layer (a hidden sheet) is stamped on the whole subtree afterwards —
1872        // docling puts the layer on the group *and* on every item under it.
1873        let mark = (
1874            self.texts.len(),
1875            self.tables.len(),
1876            self.pictures.len(),
1877            self.groups.len(),
1878        );
1879        let children = self.walk_into(nodes, &self_ref);
1880        let name = name.unwrap_or(if label == "inline" { "group" } else { label });
1881        let content_layer = layer.map_or("body", |l| l.value());
1882        self.groups[group_index(&self_ref)] = json!({
1883            "self_ref": self_ref,
1884            "parent": { "$ref": parent },
1885            "children": children,
1886            "content_layer": content_layer,
1887            "name": name,
1888            "label": label,
1889        });
1890        if layer.is_some() {
1891            let (t, tb, p, g) = mark;
1892            for item in self.texts[t..]
1893                .iter_mut()
1894                .chain(self.tables[tb..].iter_mut())
1895                .chain(self.pictures[p..].iter_mut())
1896                .chain(self.groups[g..].iter_mut())
1897            {
1898                if let Some(obj) = item.as_object_mut() {
1899                    obj.insert("content_layer".into(), json!(content_layer));
1900                }
1901            }
1902        }
1903        self_ref
1904    }
1905
1906    /// Walk a slice of sibling nodes, returning each child's `$ref`; runs of
1907    /// list items are folded into list groups (one per sibling list).
1908    fn walk_into(&mut self, nodes: &[Node], parent: &str) -> Vec<Value> {
1909        // Siblings that all carry a creation rank (an XLSX sheet's items) are
1910        // *added* in that order — so `#/tables/N` and friends are numbered as
1911        // docling numbers them — while their refs keep the node order, which
1912        // is docling's position-sorted `children`.
1913        let seqs: Option<Vec<usize>> = nodes
1914            .iter()
1915            .map(|n| match n {
1916                Node::Prov { seq: Some(s), .. } => Some(*s),
1917                _ => None,
1918            })
1919            .collect();
1920        if let Some(seqs) = seqs.filter(|s| !s.is_empty()) {
1921            let mut order: Vec<usize> = (0..nodes.len()).collect();
1922            order.sort_by_key(|&i| seqs[i]);
1923            let mut slots: Vec<Vec<Value>> = vec![Vec::new(); nodes.len()];
1924            for i in order {
1925                if let Some(r) = self.add_node(&nodes[i], parent) {
1926                    slots[i].append(&mut self.pending_siblings);
1927                    slots[i].push(json!({ "$ref": r }));
1928                    slots[i].append(&mut self.pending_after);
1929                }
1930                if parent == "#/body" {
1931                    slots[i].append(&mut self.pending_body);
1932                }
1933            }
1934            return slots.into_iter().flatten().collect();
1935        }
1936        let mut children = Vec::new();
1937        let mut i = 0;
1938        while i < nodes.len() {
1939            if matches!(nodes[i], Node::ListItem { .. }) {
1940                let start = i;
1941                i += 1;
1942                loop {
1943                    match nodes.get(i) {
1944                        Some(Node::ListItem { .. }) => i += 1,
1945                        // Absorb an empty paragraph sitting between two list
1946                        // items (docling keeps the ListGroup contiguous).
1947                        Some(Node::Paragraph { text })
1948                            if text.is_empty()
1949                                && matches!(nodes.get(i + 1), Some(Node::ListItem { .. })) =>
1950                        {
1951                            i += 1
1952                        }
1953                        _ => break,
1954                    }
1955                }
1956                self.add_sibling_lists(&nodes[start..i], parent, &mut children);
1957            } else {
1958                if let Some(r) = self.add_node(&nodes[i], parent) {
1959                    children.append(&mut self.pending_siblings);
1960                    children.push(json!({ "$ref": r }));
1961                    children.append(&mut self.pending_after);
1962                }
1963                i += 1;
1964            }
1965            // Body-parented captions of items deeper in the tree follow the
1966            // top-level item they were created under (#390).
1967            if parent == "#/body" {
1968                children.append(&mut self.pending_body);
1969            }
1970        }
1971        children
1972    }
1973
1974    /// A run of list items may hold several *sibling* lists; emit one list group
1975    /// per sibling. The boundary is the backend's `first_in_list` flag on a
1976    /// base-level item — the same rule as the Markdown serializer's blank line
1977    /// (#385; the kind-flip and number-gap guesses are gone).
1978    fn add_sibling_lists(&mut self, run: &[Node], parent: &str, out: &mut Vec<Value>) {
1979        let base = level_of(&run[0]);
1980        let mut seg = 0;
1981        for k in 0..run.len() {
1982            let Node::ListItem {
1983                first_in_list,
1984                level,
1985                ..
1986            } = &run[k]
1987            else {
1988                continue;
1989            };
1990            if *level != base {
1991                continue; // nested item — handled inside add_list
1992            }
1993            if k > seg && *first_in_list {
1994                out.push(json!({ "$ref": self.add_list(&run[seg..k], parent) }));
1995                seg = k;
1996            }
1997        }
1998        out.push(json!({ "$ref": self.add_list(&run[seg..], parent) }));
1999    }
2000}
2001
2002fn level_of(node: &Node) -> u8 {
2003    match node {
2004        Node::ListItem { level, .. } => *level,
2005        _ => 0,
2006    }
2007}
2008
2009fn group_index(self_ref: &str) -> usize {
2010    self_ref.rsplit('/').next().unwrap().parse().unwrap()
2011}
2012
2013fn ref_index(self_ref: &str) -> Option<usize> {
2014    self_ref.rsplit('/').next()?.parse().ok()
2015}
2016
2017/// Merge the key/values of `extra` (an object) into `target` (an object).
2018fn merge(target: &mut Value, extra: Value) {
2019    if let (Some(t), Some(e)) = (target.as_object_mut(), extra.as_object()) {
2020        for (k, v) in e {
2021            t.insert(k.clone(), v.clone());
2022        }
2023    }
2024}
2025
2026/// Reverse [`crate`]'s Markdown text escaping (HTML entities + `\_`).
2027fn unescape_text(s: &str) -> String {
2028    s.replace("&lt;", "<")
2029        .replace("&gt;", ">")
2030        .replace("&amp;", "&")
2031        .replace("\\_", "_")
2032}
2033
2034/// 64-bit FNV-1a, a stand-in for docling's `binary_hash` (we lack the source bytes
2035/// at export time; the value only needs to be a stable u64).
2036fn fnv1a(s: &str) -> u64 {
2037    let mut h: u64 = 0xcbf29ce484222325;
2038    for b in s.bytes() {
2039        h ^= b as u64;
2040        h = h.wrapping_mul(0x100000001b3);
2041    }
2042    h
2043}
2044
2045#[cfg(test)]
2046mod tests {
2047    use crate::{
2048        CaptionParent, ContentLayer, DoclingDocument, ImageMode, Node, PictureImage, Table,
2049    };
2050    use serde_json::Value;
2051
2052    fn cell_at(text: &str, row: usize, col: usize, col_span: usize) -> crate::TableCell {
2053        crate::TableCell {
2054            text: text.into(),
2055            bbox: None,
2056            start_row: row,
2057            start_col: col,
2058            row_span: 1,
2059            col_span,
2060            column_header: row == 0,
2061            row_header: false,
2062            row_section: false,
2063        }
2064    }
2065
2066    /// First-class cells past the rows: rectangular rows are the grid and
2067    /// clip them (docling's `TableData.grid` on USPTO's overrun replicas);
2068    /// ragged rows — an xlsx table compacted by `skip_empty_cells` (#271) —
2069    /// are no grid, so the cells' extent sizes it and the omitted positions
2070    /// come back as empty filler cells in `grid` only.
2071    #[test]
2072    fn ragged_rows_take_their_grid_from_first_class_cells() {
2073        let cells = vec![
2074            cell_at("h0", 0, 0, 1),
2075            cell_at("h2", 0, 2, 1),
2076            cell_at("wide", 1, 0, 3),
2077        ];
2078        let export = |rows: Vec<Vec<String>>| -> Value {
2079            let mut doc = DoclingDocument::new("t");
2080            doc.push(Node::Table(Table {
2081                rows,
2082                cells: Some(cells.clone()),
2083                ..Table::default()
2084            }));
2085            let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2086            v["tables"][0]["data"].clone()
2087        };
2088        // Compacted rows: 2 and 3 wide, the cells say the grid is 3 wide.
2089        let data = export(vec![
2090            vec!["h0".into(), "h2".into()],
2091            vec!["wide".into(), "wide".into(), "wide".into()],
2092        ]);
2093        assert_eq!(data["num_rows"], 2);
2094        assert_eq!(data["num_cols"], 3);
2095        assert_eq!(data["table_cells"].as_array().unwrap().len(), 3);
2096        let row0: Vec<&str> = data["grid"][0]
2097            .as_array()
2098            .unwrap()
2099            .iter()
2100            .map(|c| c["text"].as_str().unwrap())
2101            .collect();
2102        assert_eq!(row0, ["h0", "", "h2"]);
2103        assert_eq!(data["table_cells"][2]["col_span"], 3);
2104        // Rectangular rows narrower than the cells: the rows win, the cells
2105        // are clipped to them exactly as before.
2106        let data = export(vec![
2107            vec!["h0".into(), "h2".into()],
2108            vec!["wide".into(), "wide".into()],
2109        ]);
2110        assert_eq!(data["num_cols"], 2);
2111        assert_eq!(data["grid"][0].as_array().unwrap().len(), 2);
2112    }
2113
2114    fn doc_with_image() -> DoclingDocument {
2115        let mut doc = DoclingDocument::new("t");
2116        doc.push(Node::Picture {
2117            caption: Some("Fig 1".into()),
2118            caption_href: None,
2119            image: Some(PictureImage {
2120                dpi: crate::PictureImage::DEFAULT_DPI,
2121                mimetype: "image/png".into(),
2122                width: 4,
2123                height: 2,
2124                data: b"foobar".to_vec(),
2125            }),
2126            classification: None,
2127            caption_parent: Default::default(),
2128        });
2129        doc
2130    }
2131
2132    /// #402: a deck's speaker notes are content, and docling puts them in the
2133    /// JSON on the `notes` layer so a consumer reading only JSON can pick them
2134    /// out. Markdown still serializes the body layer alone, and page furniture
2135    /// stays out of the JSON, where docling does keep it.
2136    #[test]
2137    fn notes_layer_items_reach_the_json_but_furniture_does_not() {
2138        let mut doc = DoclingDocument::new("t");
2139        doc.push(Node::Heading {
2140            level: 1,
2141            text: "Slide One".into(),
2142        });
2143        doc.push(Node::Furniture {
2144            layer: ContentLayer::Notes,
2145            inner: Box::new(Node::Located {
2146                location: [0, 0, 0, 0],
2147                inner: Box::new(Node::Paragraph {
2148                    text: "Speaker note for slide 1.".into(),
2149                }),
2150            }),
2151        });
2152        doc.push(Node::Furniture {
2153            layer: ContentLayer::Furniture,
2154            inner: Box::new(Node::Paragraph {
2155                text: "page header".into(),
2156            }),
2157        });
2158
2159        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2160        let texts = v["texts"].as_array().unwrap();
2161        assert_eq!(
2162            texts
2163                .iter()
2164                .map(|t| (
2165                    t["label"].as_str().unwrap(),
2166                    t["content_layer"].as_str().unwrap(),
2167                    t["text"].as_str().unwrap()
2168                ))
2169                .collect::<Vec<_>>(),
2170            vec![
2171                ("title", "body", "Slide One"),
2172                ("text", "notes", "Speaker note for slide 1."),
2173            ],
2174            "the note is carried on its own layer; the furniture is not carried"
2175        );
2176        // The body layer is what Markdown serializes, so it does not change.
2177        assert_eq!(doc.export_to_markdown(), "# Slide One\n");
2178    }
2179
2180    /// #410: a backend that describes merged ranges only as continuation
2181    /// flags (xlsx `<mergeCell>`, docx `gridSpan`/`vMerge`) gets docling's
2182    /// one-`TableCell`-per-range JSON: the anchor's offsets and spans, the
2183    /// entry repeated across the grid positions it covers — not a 1×1 cell
2184    /// per position with the text copied into each.
2185    #[test]
2186    fn continuation_flags_become_spanning_cells() {
2187        let mut doc = DoclingDocument::new("t");
2188        // A1:C2 merged ("merged"), then a plain row underneath.
2189        let rows = vec![
2190            vec!["merged".to_string(), "merged".into(), "merged".into()],
2191            vec!["merged".to_string(), "merged".into(), "merged".into()],
2192            vec!["a".to_string(), "b".into(), "c".into()],
2193        ];
2194        doc.push(Node::Table(crate::Table {
2195            rows,
2196            location: None,
2197            structure: Some(crate::TableStructure {
2198                header_row: vec![true, false, false],
2199                col_continuation: vec![
2200                    vec![false, true, true],
2201                    vec![false, true, true],
2202                    vec![false, false, false],
2203                ],
2204                row_continuation: vec![
2205                    vec![false, false, false],
2206                    vec![true, true, true],
2207                    vec![false, false, false],
2208                ],
2209                row_header: Vec::new(),
2210                col_header: Vec::new(),
2211            }),
2212            cell_blocks: None,
2213            cells: None,
2214            caption: None,
2215            caption_parent: Default::default(),
2216        }));
2217        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2218        let data = &v["tables"][0]["data"];
2219        assert_eq!(data["num_rows"], 3);
2220        assert_eq!(data["num_cols"], 3);
2221        let cells = data["table_cells"].as_array().unwrap();
2222        assert_eq!(
2223            cells.len(),
2224            4,
2225            "one cell for the range, three for the plain row"
2226        );
2227        assert_eq!(
2228            cells[0],
2229            serde_json::json!({
2230                "row_span": 2, "col_span": 3,
2231                "start_row_offset_idx": 0, "end_row_offset_idx": 2,
2232                "start_col_offset_idx": 0, "end_col_offset_idx": 3,
2233                "text": "merged", "column_header": true, "row_header": false,
2234                "row_section": false, "fillable": false,
2235            })
2236        );
2237        assert_eq!(cells[1]["text"], "a");
2238        assert_eq!(cells[1]["row_span"], 1);
2239        assert_eq!(cells[1]["column_header"], false);
2240        // The grid repeats the range's entry at every position it covers.
2241        let grid = data["grid"].as_array().unwrap();
2242        assert_eq!(grid.len(), 3);
2243        for (r, row) in grid.iter().take(2).enumerate() {
2244            for (c, cell) in row.as_array().unwrap().iter().enumerate() {
2245                assert_eq!(*cell, cells[0], "grid[{r}][{c}]");
2246            }
2247        }
2248        assert_eq!(grid[2][2]["text"], "c");
2249    }
2250
2251    /// A [`Node::Prov`] wrapper is docling's provenance verbatim — the exact
2252    /// box in a top-left origin, the backend's charspan — and the page marker
2253    /// before it sizes the page; a chart's caption becomes a sibling of the
2254    /// picture in the container, listed first, sharing the chart's box with
2255    /// a charspan over its text. That is the JSON shape of an XLSX sheet.
2256    #[test]
2257    fn exact_provenance_pages_and_chart_captions_follow_docling() {
2258        let mut doc = DoclingDocument::new("t");
2259        doc.push(Node::PageInfo {
2260            page_no: 1,
2261            width: 3.0,
2262            height: 4.0,
2263        });
2264        let table = crate::Table {
2265            rows: vec![vec!["a".to_string(), "b".into()]],
2266            ..Default::default()
2267        };
2268        doc.push(Node::Group {
2269            label: "sheet".into(),
2270            name: Some("Data".into()),
2271            layer: None,
2272            children: vec![
2273                // Node order is the position-sorted one; creation order (the
2274                // `seq`) had the chart first — so the chart is `#/pictures/0`
2275                // *and* its caption `#/texts/0`, while the table stays the
2276                // group's first child.
2277                Node::Prov {
2278                    page_no: 1,
2279                    bbox: [0.0, 0.0, 3.0, 4.0],
2280                    charspan: [0, 0],
2281                    seq: Some(1),
2282                    inner: Box::new(Node::Table(table.clone())),
2283                },
2284                Node::Prov {
2285                    page_no: 1,
2286                    bbox: [0.0, 1.0, 1.0, 1.0],
2287                    charspan: [0, 0],
2288                    seq: Some(0),
2289                    inner: Box::new(Node::Chart {
2290                        kind: "bar_chart".into(),
2291                        table,
2292                        caption: Some("Sales".into()),
2293                        location: Some([0, 128, 170, 128]),
2294                    }),
2295                },
2296            ],
2297        });
2298        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2299        assert_eq!(
2300            v["pages"],
2301            serde_json::json!({"1": {"size": {"width": 3.0, "height": 4.0}, "page_no": 1}})
2302        );
2303        assert_eq!(
2304            v["tables"][0]["prov"],
2305            serde_json::json!([{
2306                "page_no": 1,
2307                "bbox": {"l": 0.0, "t": 0.0, "r": 3.0, "b": 4.0, "coord_origin": "TOPLEFT"},
2308                "charspan": [0, 0],
2309            }])
2310        );
2311        assert_eq!(v["tables"][0]["data"]["orientation"], "rot_0");
2312        // The caption is the group's child *before* the picture, parented to
2313        // the group, and referenced by the picture.
2314        let sheet = &v["groups"][0];
2315        assert_eq!(
2316            sheet["children"],
2317            serde_json::json!([
2318                {"$ref": "#/tables/0"}, {"$ref": "#/texts/0"}, {"$ref": "#/pictures/0"}
2319            ])
2320        );
2321        let cap = &v["texts"][0];
2322        assert_eq!(cap["label"], "caption");
2323        assert_eq!(cap["parent"], serde_json::json!({"$ref": "#/groups/0"}));
2324        assert_eq!(cap["prov"][0]["charspan"], serde_json::json!([0, 5]));
2325        assert_eq!(cap["prov"][0]["bbox"]["b"], 1.0);
2326        let pic = &v["pictures"][0];
2327        assert_eq!(pic["captions"], serde_json::json!([{"$ref": "#/texts/0"}]));
2328        assert_eq!(pic["prov"][0]["charspan"], serde_json::json!([0, 0]));
2329        assert_eq!(pic["prov"][0]["bbox"]["coord_origin"], "TOPLEFT");
2330        assert_eq!(
2331            pic["meta"]["classification"]["predictions"][0]["class_name"],
2332            "bar_chart"
2333        );
2334        assert_eq!(pic["meta"]["tabular_chart"]["chart_data"]["num_cols"], 2);
2335    }
2336
2337    /// An all-zero location is the "no geometry" sentinel — a slide's speaker
2338    /// notes carry one — and docling writes it as a zero bbox, not as a box
2339    /// spanning the whole page, which is what denormalizing the grid gives.
2340    #[test]
2341    fn a_zero_location_is_a_zero_bbox_not_the_whole_page() {
2342        let mut doc = DoclingDocument::new("t");
2343        doc.push(Node::PageInfo {
2344            page_no: 1,
2345            width: 12192000.0,
2346            height: 6858000.0,
2347        });
2348        doc.push(Node::Furniture {
2349            layer: ContentLayer::Notes,
2350            inner: Box::new(Node::Located {
2351                location: [0, 0, 0, 0],
2352                inner: Box::new(Node::Paragraph {
2353                    text: "a note".into(),
2354                }),
2355            }),
2356        });
2357        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2358        let prov = &v["texts"][0]["prov"][0];
2359        assert_eq!(prov["page_no"], 1);
2360        assert_eq!(prov["charspan"], serde_json::json!([0, 6]));
2361        assert_eq!(
2362            prov["bbox"],
2363            serde_json::json!({"l": 0.0, "t": 0.0, "r": 0.0, "b": 0.0, "coord_origin": "BOTTOMLEFT"})
2364        );
2365        // The page itself is recorded at its true size.
2366        assert_eq!(
2367            v["pages"]["1"]["size"],
2368            serde_json::json!({"width": 12192000.0, "height": 6858000.0})
2369        );
2370    }
2371
2372    /// #171: PageInfo markers become the `pages` map, and `Located` wrappers /
2373    /// node-level locations become per-item `prov` — the 0–511 grid
2374    /// denormalized against the page into BOTTOMLEFT points. Without markers
2375    /// (every declarative backend) the JSON stays exactly as before: empty
2376    /// `pages`, `prov: []` even for located nodes.
2377    #[test]
2378    fn page_markers_produce_pages_and_prov() {
2379        let mut doc = DoclingDocument::new("t");
2380        doc.push(Node::PageInfo {
2381            page_no: 1,
2382            width: 512.0,
2383            height: 1024.0,
2384        });
2385        doc.push(Node::Located {
2386            location: [128, 64, 256, 128], // quarter/eighth points of the grid
2387            inner: Box::new(Node::Paragraph {
2388                text: "hello".into(),
2389            }),
2390        });
2391        doc.push(Node::Table(Table {
2392            rows: vec![vec!["a".into()]],
2393            location: Some([0, 0, 512, 512]),
2394            ..Table::default()
2395        }));
2396        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2397        assert_eq!(v["pages"]["1"]["page_no"], 1);
2398        assert_eq!(v["pages"]["1"]["size"]["width"], 512.0);
2399        assert_eq!(v["pages"]["1"]["size"]["height"], 1024.0);
2400        // 512-wide page: grid x scales 1:1; 1024-high: grid y doubles, then
2401        // flips to the BOTTOMLEFT origin (t from grid-top 64 → 1024-128=896).
2402        let prov = &v["texts"][0]["prov"][0];
2403        assert_eq!(prov["page_no"], 1);
2404        assert_eq!(prov["bbox"]["l"], 128.0);
2405        assert_eq!(prov["bbox"]["t"], 896.0);
2406        assert_eq!(prov["bbox"]["r"], 256.0);
2407        assert_eq!(prov["bbox"]["b"], 768.0);
2408        assert_eq!(prov["bbox"]["coord_origin"], "BOTTOMLEFT");
2409        assert_eq!(prov["charspan"][1], 5);
2410        // The table adopts its own location field; charspan is [0, 0].
2411        let tprov = &v["tables"][0]["prov"][0];
2412        assert_eq!(tprov["bbox"]["t"], 1024.0);
2413        assert_eq!(tprov["bbox"]["b"], 0.0);
2414        assert_eq!(tprov["charspan"][1], 0);
2415
2416        // No markers → the pre-#171 shape, byte for byte.
2417        let mut plain = DoclingDocument::new("t");
2418        plain.push(Node::Located {
2419            location: [1, 2, 3, 4],
2420            inner: Box::new(Node::Paragraph { text: "x".into() }),
2421        });
2422        let v: Value = serde_json::from_str(&plain.export_to_json()).unwrap();
2423        assert_eq!(v["pages"], serde_json::json!({}));
2424        assert_eq!(v["texts"][0]["prov"], serde_json::json!([]));
2425    }
2426
2427    /// PDF page headers/footers reach the JSON as docling writes them:
2428    /// body-parented text items on the furniture layer, with their box.
2429    #[test]
2430    fn page_furniture_becomes_furniture_layer_text() {
2431        let mut doc = DoclingDocument::new("t");
2432        doc.push(Node::PageInfo {
2433            page_no: 1,
2434            width: 512.0,
2435            height: 512.0,
2436        });
2437        doc.push(Node::PageFurniture {
2438            footer: false,
2439            location: [10, 0, 100, 20],
2440            text: "Chapter 1".into(),
2441        });
2442        doc.push(Node::Paragraph {
2443            text: "body".into(),
2444        });
2445        doc.push(Node::PageFurniture {
2446            footer: true,
2447            location: [400, 490, 500, 512],
2448            text: "1.10.2".into(),
2449        });
2450        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2451        let texts = v["texts"].as_array().unwrap();
2452        assert_eq!(texts.len(), 3);
2453        assert_eq!(texts[0]["label"], "page_header");
2454        assert_eq!(texts[0]["content_layer"], "furniture");
2455        assert_eq!(texts[0]["parent"]["$ref"], "#/body");
2456        assert_eq!(texts[0]["prov"][0]["bbox"]["l"], 10.0);
2457        assert_eq!(texts[1]["content_layer"], "body");
2458        assert_eq!(texts[1]["prov"], serde_json::json!([]));
2459        assert_eq!(texts[2]["label"], "page_footer");
2460        assert_eq!(texts[2]["text"], "1.10.2");
2461        assert_eq!(texts[2]["content_layer"], "furniture");
2462    }
2463
2464    #[test]
2465    fn picture_image_in_markdown_modes_and_json() {
2466        let doc = doc_with_image();
2467        // placeholder (default) ignores the image
2468        assert!(doc.export_to_markdown().contains("<!-- image -->"));
2469        // embedded → base64 data URI (b"foobar" → "Zm9vYmFy")
2470        let (md, files) = doc.export_to_markdown_with_images(ImageMode::Embedded, "artifacts");
2471        assert!(
2472            md.contains("![Image](data:image/png;base64,Zm9vYmFy)"),
2473            "got:\n{md}"
2474        );
2475        assert!(files.is_empty());
2476        // referenced → file link + collected bytes
2477        let (md, files) = doc.export_to_markdown_with_images(ImageMode::Referenced, "artifacts");
2478        assert!(
2479            md.contains("![Image](artifacts/image_000000.png)"),
2480            "got:\n{md}"
2481        );
2482        assert_eq!(
2483            files,
2484            vec![("artifacts/image_000000.png".to_string(), b"foobar".to_vec())]
2485        );
2486        // JSON carries the ImageRef (data URI + size — floats, as docling's
2487        // `Size` is — placed before `annotations`).
2488        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2489        assert_eq!(v["pictures"][0]["image"]["mimetype"], "image/png");
2490        assert_eq!(v["pictures"][0]["image"]["size"]["width"], 4.0);
2491        let keys: Vec<&str> = v["pictures"][0]
2492            .as_object()
2493            .unwrap()
2494            .keys()
2495            .map(String::as_str)
2496            .collect();
2497        assert_eq!(&keys[keys.len() - 2..], ["image", "annotations"]);
2498        assert_eq!(
2499            v["pictures"][0]["image"]["uri"],
2500            "data:image/png;base64,Zm9vYmFy"
2501        );
2502    }
2503
2504    #[test]
2505    fn exports_docling_schema() {
2506        let mut doc = DoclingDocument::new("t");
2507        doc.push(Node::Heading {
2508            level: 1,
2509            text: "Title".into(),
2510        });
2511        doc.push(Node::Heading {
2512            level: 2,
2513            text: "Sec".into(),
2514        });
2515        doc.push(Node::Paragraph {
2516            text: "Body &amp; more".into(),
2517        }); // markdown-escaped
2518        doc.push(Node::ListItem {
2519            ordered: false,
2520            number: 0,
2521            first_in_list: true,
2522            text: "one".into(),
2523            level: 0,
2524            marker: None,
2525            location: None,
2526            dclx: None,
2527            href: None,
2528            layer: None,
2529        });
2530        doc.push(Node::ListItem {
2531            ordered: false,
2532            number: 0,
2533            first_in_list: false,
2534            text: "two".into(),
2535            level: 0,
2536            marker: None,
2537            location: None,
2538            dclx: None,
2539            href: None,
2540            layer: None,
2541        });
2542        doc.push(Node::Table(Table {
2543            rows: vec![vec!["A".into(), "B".into()]],
2544            location: None,
2545            structure: None,
2546            cell_blocks: None,
2547            cells: None,
2548            caption: None,
2549            caption_parent: Default::default(),
2550        }));
2551
2552        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2553        assert_eq!(v["schema_name"], "DoclingDocument");
2554        assert_eq!(v["version"], "1.10.0");
2555        assert_eq!(v["texts"][0]["label"], "title");
2556        assert_eq!(v["texts"][1]["label"], "section_header");
2557        assert_eq!(v["texts"][1]["level"], 1); // heading level 2 → docling level 1
2558        assert_eq!(v["texts"][2]["text"], "Body & more"); // un-escaped for the wire format
2559                                                          // consecutive list items fold into one list group, parented to it
2560        assert_eq!(v["groups"][0]["label"], "list");
2561        assert_eq!(v["groups"][0]["children"].as_array().unwrap().len(), 2);
2562        assert_eq!(v["texts"][3]["parent"]["$ref"], "#/groups/0");
2563        assert_eq!(v["texts"][3]["marker"], "-");
2564        // table grid + header flag
2565        assert_eq!(v["tables"][0]["data"]["num_cols"], 2);
2566        assert_eq!(v["tables"][0]["data"]["grid"][0][0]["column_header"], true);
2567    }
2568    /// A named group on a non-body layer — docling's hidden spreadsheet sheet:
2569    /// the group carries the sheet's name and the `invisible` layer, and every
2570    /// item inside it carries the layer too.
2571    #[test]
2572    fn a_layered_group_stamps_its_whole_subtree() {
2573        let doc = DoclingDocument {
2574            name: "s".into(),
2575            nodes: vec![
2576                Node::Group {
2577                    label: "sheet".into(),
2578                    name: Some("Sheet1".into()),
2579                    layer: None,
2580                    children: vec![Node::Paragraph {
2581                        text: "visible".into(),
2582                    }],
2583                },
2584                Node::Group {
2585                    label: "sheet".into(),
2586                    name: Some("Sheet2".into()),
2587                    layer: Some(ContentLayer::Invisible),
2588                    children: vec![Node::Paragraph {
2589                        text: "hidden".into(),
2590                    }],
2591                },
2592            ],
2593            ..DoclingDocument::new("s")
2594        };
2595        let v = crate::json::to_json(&doc);
2596        assert_eq!(v["groups"][0]["label"], "sheet");
2597        assert_eq!(v["groups"][0]["name"], "Sheet1");
2598        assert_eq!(v["groups"][0]["content_layer"], "body");
2599        assert_eq!(v["texts"][0]["content_layer"], "body");
2600        assert_eq!(v["groups"][1]["name"], "Sheet2");
2601        assert_eq!(v["groups"][1]["content_layer"], "invisible");
2602        assert_eq!(v["texts"][1]["content_layer"], "invisible");
2603        // The group's children are the items, and the body holds the groups.
2604        assert_eq!(v["groups"][1]["children"][0]["$ref"], "#/texts/1");
2605        assert_eq!(v["body"]["children"][1]["$ref"], "#/groups/1");
2606    }
2607
2608    /// A backend-built item tree is serialized as it is: items numbered in
2609    /// creation order per bucket (a field region's part texts included), the
2610    /// tree's parents / children / layers, docling's field order for
2611    /// `formatting`, `hyperlink`, `level`, `enumerated`/`marker`, a rich
2612    /// cell's `ref` on `table_cells` only, raw cell text.
2613    /// The DOCX tree's extras: an item `delete`d (docling's `delete_items`,
2614    /// the spacer between two items of a resumed list) is neither written nor
2615    /// numbered, `comments` back-refs sit between `prov` and `orig`, and a
2616    /// chart picture carries `classification` plus `tabular_chart`.
2617    #[test]
2618    fn deleted_items_comment_refs_and_chart_meta_in_the_tree() {
2619        use crate::tree::{ItemTree, TreeKind};
2620        let mut t = ItemTree::default();
2621        let text = |txt: &str| TreeKind::Text {
2622            label: "text".into(),
2623            text: txt.into(),
2624            orig: None,
2625            formatting: None,
2626            hyperlink: None,
2627            level: None,
2628            list: None,
2629        };
2630        let a = t.add(None, None, text("a"));
2631        let blank = t.add(None, None, text(""));
2632        let b = t.add(None, None, text("b"));
2633        t.delete(blank);
2634        let group = t.add(
2635            None,
2636            Some(ContentLayer::Notes),
2637            TreeKind::Group {
2638                label: "comment_section".into(),
2639                name: "comment-0".into(),
2640            },
2641        );
2642        t.add(Some(group), Some(ContentLayer::Notes), text("note"));
2643        t.items[a].comments.push(group);
2644        t.add(
2645            None,
2646            None,
2647            TreeKind::Picture {
2648                captions: Vec::new(),
2649                image: None,
2650                classification: Some("bar_chart".into()),
2651                confidence: None,
2652                chart: Some(Table {
2653                    rows: vec![vec!["".into(), "s".into()], vec!["c".into(), "1".into()]],
2654                    ..Table::default()
2655                }),
2656                dpi: None,
2657            },
2658        );
2659        assert_eq!(t.last_text(), Some(4), "the note; the blank is skipped");
2660        assert_eq!(t.bucket_index(b), 1, "numbered past the deleted item");
2661        let mut doc = DoclingDocument::new("t");
2662        doc.tree = Some(t);
2663        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2664        let texts = v["texts"].as_array().unwrap();
2665        assert_eq!(texts.len(), 3);
2666        assert_eq!(texts[1]["text"], "b");
2667        assert_eq!(texts[1]["self_ref"], "#/texts/1");
2668        assert_eq!(
2669            v["body"]["children"],
2670            serde_json::json!([{"$ref": "#/texts/0"}, {"$ref": "#/texts/1"}, {"$ref": "#/groups/0"}, {"$ref": "#/pictures/0"}])
2671        );
2672        let keys: Vec<&str> = texts[0]
2673            .as_object()
2674            .unwrap()
2675            .keys()
2676            .map(String::as_str)
2677            .collect();
2678        assert_eq!(
2679            keys,
2680            vec![
2681                "self_ref",
2682                "parent",
2683                "children",
2684                "content_layer",
2685                "label",
2686                "prov",
2687                "comments",
2688                "orig",
2689                "text"
2690            ]
2691        );
2692        assert_eq!(
2693            texts[0]["comments"],
2694            serde_json::json!([{"$ref": "#/groups/0"}])
2695        );
2696        assert!(texts[1].get("comments").is_none());
2697        let meta = &v["pictures"][0]["meta"];
2698        assert_eq!(
2699            meta["classification"]["predictions"][0]["class_name"],
2700            "bar_chart"
2701        );
2702        assert_eq!(meta["tabular_chart"]["chart_data"]["num_rows"], 2);
2703    }
2704
2705    /// A tree item's `TreeProv` is written verbatim — a raw EMU box with
2706    /// whatever origin tag the backend set (`BOTTOMLEFT` here) and a per-item
2707    /// charspan, a note's zero `TOPLEFT` box — a picture's `image.dpi` is the file's when the backend
2708    /// read one, an item without provenance writes `prov: []`, and the page
2709    /// map still comes from the flat stream's markers.
2710    #[test]
2711    fn tree_items_carry_exact_provenance_and_dpi() {
2712        use crate::tree::{ItemTree, TreeKind, TreeProv};
2713        let text = |label: &str, t: &str| TreeKind::Text {
2714            label: label.into(),
2715            text: t.into(),
2716            orig: None,
2717            formatting: None,
2718            hyperlink: None,
2719            level: None,
2720            list: None,
2721        };
2722        let mut t = ItemTree::default();
2723        let slide = t.add(
2724            None,
2725            None,
2726            TreeKind::Group {
2727                label: "chapter".into(),
2728                name: "slide-0".into(),
2729            },
2730        );
2731        t.add_with_prov(
2732            Some(slide),
2733            None,
2734            text("paragraph", "héllo"),
2735            TreeProv {
2736                page_no: 1,
2737                bbox: [914400.0, 1828800.0, 2743200.0, 457200.0],
2738                bottom_left: true,
2739                charspan: [0, 5],
2740            },
2741        );
2742        t.add_with_prov(
2743            Some(slide),
2744            None,
2745            TreeKind::Picture {
2746                captions: Vec::new(),
2747                image: Some(crate::PictureImage {
2748                    dpi: crate::PictureImage::DEFAULT_DPI,
2749                    mimetype: "image/png".into(),
2750                    width: 2,
2751                    height: 2,
2752                    data: vec![0],
2753                }),
2754                classification: None,
2755                confidence: None,
2756                chart: None,
2757                dpi: Some(300),
2758            },
2759            TreeProv {
2760                page_no: 1,
2761                bbox: [0.0; 4],
2762                bottom_left: false,
2763                charspan: [0, 0],
2764            },
2765        );
2766        t.add(
2767            Some(slide),
2768            Some(ContentLayer::Notes),
2769            text("text", "no geometry"),
2770        );
2771        let mut doc = DoclingDocument::new("t");
2772        doc.push(Node::PageInfo {
2773            page_no: 1,
2774            width: 9144000.0,
2775            height: 6858000.0,
2776        });
2777        doc.tree = Some(t);
2778        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2779        assert_eq!(
2780            v["texts"][0]["prov"],
2781            serde_json::json!([{
2782                "page_no": 1,
2783                "bbox": { "l": 914400.0, "t": 1828800.0, "r": 2743200.0, "b": 457200.0, "coord_origin": "BOTTOMLEFT" },
2784                "charspan": [0, 5],
2785            }])
2786        );
2787        assert_eq!(v["texts"][0]["label"], "paragraph");
2788        assert_eq!(
2789            v["pictures"][0]["prov"][0]["bbox"]["coord_origin"],
2790            "TOPLEFT"
2791        );
2792        assert_eq!(v["pictures"][0]["image"]["dpi"], 300);
2793        assert_eq!(v["texts"][1]["prov"], serde_json::json!([]));
2794        assert_eq!(v["texts"][1]["content_layer"], "notes");
2795        assert_eq!(v["pages"]["1"]["size"]["width"], 9144000.0);
2796        assert_eq!(v["pages"]["1"]["page_no"], 1);
2797    }
2798
2799    /// docling-core's `validate_document` clamps every provenance box (and a
2800    /// one-page table's cell boxes) into its page — the state every
2801    /// `ConversionResult` leaves a document in, so the state docling's JSON
2802    /// shows. A box on a page the document does not describe is left alone.
2803    #[test]
2804    fn provenance_boxes_are_clamped_to_their_page() {
2805        let mut doc = DoclingDocument::new("t");
2806        doc.push(Node::PageInfo {
2807            page_no: 1,
2808            width: 10.0,
2809            height: 8.0,
2810        });
2811        doc.push(Node::Prov {
2812            page_no: 1,
2813            bbox: [-1.0, 2.0, 12.0, 9.5],
2814            charspan: [0, 1],
2815            seq: None,
2816            inner: Box::new(Node::Paragraph { text: "x".into() }),
2817        });
2818        let mut table = Table {
2819            rows: vec![vec!["a".into()]],
2820            ..Table::default()
2821        };
2822        table.cells = Some(vec![crate::TableCell {
2823            text: "a".into(),
2824            bbox: Some([1.0, 1.0, 11.0, 9.0]),
2825            start_row: 0,
2826            start_col: 0,
2827            row_span: 1,
2828            col_span: 1,
2829            column_header: false,
2830            row_header: false,
2831            row_section: false,
2832        }]);
2833        doc.push(Node::Prov {
2834            page_no: 1,
2835            bbox: [0.0, 0.0, 10.0, 8.0],
2836            charspan: [0, 0],
2837            seq: None,
2838            inner: Box::new(Node::Table(table)),
2839        });
2840        doc.push(Node::Prov {
2841            page_no: 7,
2842            bbox: [-5.0, 0.0, 50.0, 50.0],
2843            charspan: [0, 1],
2844            seq: None,
2845            inner: Box::new(Node::Paragraph { text: "y".into() }),
2846        });
2847        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2848        assert_eq!(
2849            v["texts"][0]["prov"][0]["bbox"],
2850            serde_json::json!({ "l": 0.0, "t": 2.0, "r": 10.0, "b": 8.0, "coord_origin": "TOPLEFT" })
2851        );
2852        let cell = &v["tables"][0]["data"]["table_cells"][0]["bbox"];
2853        assert_eq!(
2854            (cell["l"].as_f64(), cell["r"].as_f64(), cell["b"].as_f64()),
2855            (Some(1.0), Some(10.0), Some(8.0))
2856        );
2857        assert_eq!(v["tables"][0]["data"]["grid"][0][0]["bbox"]["r"], 10.0);
2858        assert_eq!(
2859            v["texts"][1]["prov"][0]["bbox"]["r"], 50.0,
2860            "page 7 is not described"
2861        );
2862    }
2863
2864    /// docling-core's `validate_misplaced_list_items`, as it re-homes list
2865    /// items outside a `list` group (#527) — the refs below are what
2866    /// docling-core 2.99 writes for the same document: the two consecutive
2867    /// items on the body share a group, each item in another group gets its
2868    /// own, the runs are handled last-first (new groups and re-added texts
2869    /// numbered in that order), and a well-placed item is left alone.
2870    #[test]
2871    fn misplaced_list_items_are_wrapped_like_docling_core() {
2872        use crate::tree::{ItemTree, ListMeta, TreeKind};
2873        let mut t = ItemTree::default();
2874        let li = |txt: &str| TreeKind::Text {
2875            label: "list_item".into(),
2876            text: txt.into(),
2877            orig: None,
2878            formatting: None,
2879            hyperlink: None,
2880            level: None,
2881            list: Some(ListMeta {
2882                enumerated: false,
2883                marker: "-".into(),
2884            }),
2885        };
2886        let group = |label: &str, name: &str| TreeKind::Group {
2887            label: label.into(),
2888            name: name.into(),
2889        };
2890        t.add(None, None, li("A"));
2891        t.add(None, None, li("B"));
2892        t.add(
2893            None,
2894            None,
2895            TreeKind::Text {
2896                label: "text".into(),
2897                text: "plain".into(),
2898                orig: None,
2899                formatting: None,
2900                hyperlink: None,
2901                level: None,
2902                list: None,
2903            },
2904        );
2905        let cell = t.add(None, None, group("unspecified", "cell"));
2906        t.add(Some(cell), None, li("C"));
2907        t.add(Some(cell), None, li("D"));
2908        let list = t.add(None, None, group("list", "list"));
2909        t.add(Some(list), None, li("E"));
2910        let doc = DoclingDocument {
2911            tree: Some(t),
2912            ..DoclingDocument::new("t")
2913        };
2914        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2915        let refs = |x: &Value| -> Vec<String> {
2916            x.as_array()
2917                .unwrap()
2918                .iter()
2919                .map(|r| r["$ref"].as_str().unwrap().to_string())
2920                .collect()
2921        };
2922        assert_eq!(
2923            refs(&v["body"]["children"]),
2924            ["#/groups/4", "#/texts/0", "#/groups/0", "#/groups/1"]
2925        );
2926        assert_eq!(
2927            refs(&v["groups"][0]["children"]),
2928            ["#/groups/3", "#/groups/2"]
2929        );
2930        for (g, name, kids) in [
2931            (2, "group", vec!["#/texts/2"]),
2932            (3, "group", vec!["#/texts/3"]),
2933            (4, "group", vec!["#/texts/4", "#/texts/5"]),
2934            (1, "list", vec!["#/texts/1"]),
2935        ] {
2936            assert_eq!(v["groups"][g]["label"], "list");
2937            assert_eq!(v["groups"][g]["name"], name);
2938            assert_eq!(refs(&v["groups"][g]["children"]), kids);
2939        }
2940        let texts: Vec<&str> = v["texts"]
2941            .as_array()
2942            .unwrap()
2943            .iter()
2944            .map(|t| t["text"].as_str().unwrap())
2945            .collect();
2946        assert_eq!(texts, ["plain", "E", "D", "C", "A", "B"]);
2947        assert_eq!(v["texts"][2]["parent"]["$ref"], "#/groups/2");
2948    }
2949
2950    /// A child the tree still lists after deleting it is left out instead
2951    /// of written as `"$ref": ""`, which docling-core rejects (#527).
2952    #[test]
2953    fn a_deleted_child_is_not_written_as_an_empty_ref() {
2954        use crate::tree::{ItemTree, TreeKind};
2955        let mut t = ItemTree::default();
2956        let text = |txt: &str| TreeKind::Text {
2957            label: "text".into(),
2958            text: txt.into(),
2959            orig: None,
2960            formatting: None,
2961            hyperlink: None,
2962            level: None,
2963            list: None,
2964        };
2965        let g = t.add(
2966            None,
2967            None,
2968            TreeKind::Group {
2969                label: "unspecified".into(),
2970                name: "g".into(),
2971            },
2972        );
2973        let gone = t.add(Some(g), None, text(""));
2974        t.add(Some(g), None, text("kept"));
2975        t.items[gone].deleted = true; // still in `g`'s children
2976        let doc = DoclingDocument {
2977            tree: Some(t),
2978            ..DoclingDocument::new("t")
2979        };
2980        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2981        assert_eq!(
2982            v["groups"][0]["children"],
2983            serde_json::json!([{"$ref": "#/texts/0"}])
2984        );
2985    }
2986
2987    #[test]
2988    fn a_backend_item_tree_is_written_verbatim() {
2989        use crate::tree::{Formatting, ItemTree, ListMeta, TreeKind};
2990        let mut t = ItemTree::default();
2991        let text = |label: &str, txt: &str| TreeKind::Text {
2992            label: label.into(),
2993            text: txt.into(),
2994            orig: None,
2995            formatting: None,
2996            hyperlink: None,
2997            level: None,
2998            list: None,
2999        };
3000        let title = t.add(None, Some(ContentLayer::Furniture), text("title", "Page"));
3001        let h = t.add(None, None, text("title", "Heading"));
3002        let group = t.add(
3003            Some(h),
3004            None,
3005            TreeKind::Group {
3006                label: "inline".into(),
3007                name: "group".into(),
3008            },
3009        );
3010        t.add(
3011            Some(group),
3012            None,
3013            TreeKind::Text {
3014                label: "text".into(),
3015                text: "bold".into(),
3016                orig: None,
3017                formatting: Some(Formatting {
3018                    bold: true,
3019                    ..Formatting::default()
3020                }),
3021                hyperlink: Some("https://example.com/".into()),
3022                level: None,
3023                list: None,
3024            },
3025        );
3026        t.add(
3027            Some(group),
3028            None,
3029            TreeKind::Code {
3030                text: "x = 1".into(),
3031                orig: None,
3032                language: Some("python".into()),
3033                formatting: None,
3034                hyperlink: None,
3035            },
3036        );
3037        let sub = t.add(
3038            Some(h),
3039            None,
3040            TreeKind::Text {
3041                label: "section_header".into(),
3042                text: "Sub".into(),
3043                orig: Some("Sub\u{2019}".into()),
3044                formatting: None,
3045                hyperlink: None,
3046                level: Some(1),
3047                list: None,
3048            },
3049        );
3050        let item = t.add(
3051            Some(sub),
3052            None,
3053            TreeKind::Text {
3054                label: "list_item".into(),
3055                text: "item".into(),
3056                orig: None,
3057                formatting: None,
3058                hyperlink: None,
3059                level: None,
3060                list: Some(ListMeta {
3061                    enumerated: true,
3062                    marker: "3.".into(),
3063                }),
3064            },
3065        );
3066        let _region = t.add(
3067            Some(sub),
3068            None,
3069            TreeKind::FieldRegion {
3070                items: vec![crate::FieldItem {
3071                    marker: None,
3072                    key: Some("Name".into()),
3073                    value: Some("Duck".into()),
3074                    value_kind: Some("read_only".into()),
3075                }],
3076            },
3077        );
3078        let table = t.add(
3079            Some(sub),
3080            None,
3081            TreeKind::Table {
3082                table: Table {
3083                    rows: vec![vec!["a  \n&lt;".into(), "b".into()]],
3084                    cells: Some(vec![
3085                        crate::TableCell {
3086                            text: "a  \n&lt;".into(),
3087                            bbox: None,
3088                            start_row: 0,
3089                            start_col: 0,
3090                            row_span: 3,
3091                            col_span: 1,
3092                            column_header: false,
3093                            row_header: true,
3094                            row_section: false,
3095                        },
3096                        crate::TableCell {
3097                            text: "b".into(),
3098                            bbox: None,
3099                            start_row: 0,
3100                            start_col: 1,
3101                            row_span: 1,
3102                            col_span: 1,
3103                            column_header: false,
3104                            row_header: false,
3105                            row_section: false,
3106                        },
3107                    ]),
3108                    ..Table::default()
3109                },
3110                rich_cells: vec![(0, 1, 0)], // patched below
3111                captions: Vec::new(),
3112            },
3113        );
3114        let cell_group = t.add(
3115            Some(table),
3116            None,
3117            TreeKind::Group {
3118                label: "unspecified".into(),
3119                name: "rich_cell_group_1_0_0".into(),
3120            },
3121        );
3122        if let TreeKind::Table { rich_cells, .. } = &mut t.items[table].kind {
3123            *rich_cells = vec![(0, 1, cell_group)];
3124        }
3125        let after = t.add(Some(sub), None, text("text", "after the region"));
3126        let _ = (title, after);
3127        // A list item belongs in a `list` group — one outside it would be
3128        // re-homed by `wrap_misplaced_list_items` (created last, so the
3129        // other groups keep their numbers).
3130        let list = t.add(
3131            Some(sub),
3132            None,
3133            TreeKind::Group {
3134                label: "list".into(),
3135                name: "list".into(),
3136            },
3137        );
3138        t.reparent(item, Some(list));
3139
3140        let doc = DoclingDocument {
3141            tree: Some(t),
3142            ..DoclingDocument::new("t")
3143        };
3144        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
3145        // Creation order: Page, Heading, bold, x = 1, Sub, item, [Name, Duck], after.
3146        let texts: Vec<&str> = v["texts"]
3147            .as_array()
3148            .unwrap()
3149            .iter()
3150            .map(|t| t["text"].as_str().unwrap())
3151            .collect();
3152        assert_eq!(
3153            texts,
3154            [
3155                "Page",
3156                "Heading",
3157                "bold",
3158                "x = 1",
3159                "Sub",
3160                "item",
3161                "Name",
3162                "Duck",
3163                "after the region"
3164            ]
3165        );
3166        assert_eq!(
3167            v["body"]["children"],
3168            serde_json::json!([{"$ref": "#/texts/0"}, {"$ref": "#/texts/1"}])
3169        );
3170        assert_eq!(v["texts"][0]["content_layer"], "furniture");
3171        assert_eq!(
3172            v["texts"][1]["children"],
3173            serde_json::json!([{"$ref": "#/groups/0"}, {"$ref": "#/texts/4"}])
3174        );
3175        let bold = &v["texts"][2];
3176        assert_eq!(bold["parent"]["$ref"], "#/groups/0");
3177        let keys: Vec<&str> = bold
3178            .as_object()
3179            .unwrap()
3180            .keys()
3181            .map(String::as_str)
3182            .collect();
3183        assert_eq!(
3184            keys,
3185            [
3186                "self_ref",
3187                "parent",
3188                "children",
3189                "content_layer",
3190                "label",
3191                "prov",
3192                "orig",
3193                "text",
3194                "formatting",
3195                "hyperlink"
3196            ]
3197        );
3198        assert_eq!(
3199            bold["formatting"],
3200            serde_json::json!({"bold": true, "italic": false, "underline": false, "strikethrough": false, "script": "baseline"})
3201        );
3202        let code = &v["texts"][3];
3203        assert_eq!(code["label"], "code");
3204        assert_eq!(code["code_language"], "Python");
3205        let sub = &v["texts"][4];
3206        assert_eq!(sub["orig"], "Sub\u{2019}");
3207        assert_eq!(sub["level"], 1);
3208        let item = &v["texts"][5];
3209        let keys: Vec<&str> = item
3210            .as_object()
3211            .unwrap()
3212            .keys()
3213            .map(String::as_str)
3214            .collect();
3215        assert_eq!(
3216            keys,
3217            [
3218                "self_ref",
3219                "parent",
3220                "children",
3221                "content_layer",
3222                "label",
3223                "prov",
3224                "orig",
3225                "text",
3226                "enumerated",
3227                "marker"
3228            ]
3229        );
3230        assert_eq!(item["marker"], "3.");
3231        assert_eq!(v["texts"][7]["kind"], "read_only");
3232        assert_eq!(v["field_regions"][0]["parent"]["$ref"], "#/texts/4");
3233        let table = &v["tables"][0];
3234        assert_eq!(
3235            table["children"],
3236            serde_json::json!([{"$ref": "#/groups/1"}])
3237        );
3238        let cells = table["data"]["table_cells"].as_array().unwrap();
3239        assert_eq!(
3240            cells[0]["text"], "a  \n&lt;",
3241            "raw cell text is written verbatim"
3242        );
3243        assert_eq!(
3244            cells[0]["end_row_offset_idx"], 3,
3245            "declared spans are not clamped"
3246        );
3247        assert_eq!(cells[1]["ref"], serde_json::json!({"$ref": "#/groups/1"}));
3248        assert!(cells[0].get("ref").is_none());
3249        assert!(
3250            table["data"]["grid"][0][1].get("ref").is_none(),
3251            "the grid shows plain cells"
3252        );
3253        assert_eq!(v["groups"][1]["name"], "rich_cell_group_1_0_0");
3254    }
3255
3256    /// A comment section that links its note text rather than its group — the
3257    /// spreadsheet shape, where docling-core's `add_comment` appends the text
3258    /// item's ref to each target.
3259    #[test]
3260    fn a_comment_section_can_be_referenced_by_its_note_text() {
3261        let doc = DoclingDocument {
3262            name: "c".into(),
3263            nodes: vec![
3264                Node::Commented {
3265                    comments: vec![0],
3266                    inner: Box::new(Node::Paragraph {
3267                        text: "annotated".into(),
3268                    }),
3269                },
3270                Node::CommentSection {
3271                    name: "comment-Sheet1-A1".into(),
3272                    text: "[author: A]: note".into(),
3273                    refs_note_text: true,
3274                    grouped: true,
3275                },
3276            ],
3277            ..DoclingDocument::new("c")
3278        };
3279        let v = crate::json::to_json(&doc);
3280        assert_eq!(v["groups"][0]["name"], "comment-Sheet1-A1");
3281        assert_eq!(v["texts"][0]["comments"][0]["$ref"], "#/texts/1");
3282    }
3283
3284    /// docx reviewer comments: a `comment_section` group on the notes layer
3285    /// holding the note text, and a `comments` back-ref on the annotated item —
3286    /// keyed between `prov` and `orig`, the slot docling emits it in.
3287    #[test]
3288    fn comment_sections_link_back_to_their_items() {
3289        let doc = DoclingDocument {
3290            name: "c".into(),
3291            nodes: vec![
3292                Node::Commented {
3293                    comments: vec![0],
3294                    inner: Box::new(Node::Paragraph {
3295                        text: "annotated".into(),
3296                    }),
3297                },
3298                Node::Paragraph {
3299                    text: "plain".into(),
3300                },
3301                Node::CommentSection {
3302                    name: "comment-7".into(),
3303                    text: "[time: t]: note".into(),
3304                    refs_note_text: false,
3305                    grouped: true,
3306                },
3307            ],
3308            ..DoclingDocument::new("c")
3309        };
3310        let v = crate::json::to_json(&doc);
3311        // The group is the comment section; its only child is the notes text.
3312        assert_eq!(v["groups"][0]["label"], "comment_section");
3313        assert_eq!(v["groups"][0]["name"], "comment-7");
3314        assert_eq!(v["groups"][0]["content_layer"], "notes");
3315        assert_eq!(v["groups"][0]["children"][0]["$ref"], "#/texts/2");
3316        assert_eq!(v["texts"][2]["content_layer"], "notes");
3317        // The annotated item points back at the group; the plain one has no key.
3318        assert_eq!(v["texts"][0]["comments"][0]["$ref"], "#/groups/0");
3319        assert!(v["texts"][1].get("comments").is_none());
3320        // docling's key order: … prov, comments, orig, text.
3321        let keys: Vec<&str> = v["texts"][0]
3322            .as_object()
3323            .unwrap()
3324            .keys()
3325            .map(String::as_str)
3326            .collect();
3327        assert_eq!(
3328            &keys[keys.len() - 4..],
3329            &["prov", "comments", "orig", "text"]
3330        );
3331    }
3332
3333    fn picture(caption: &str, caption_parent: CaptionParent) -> Node {
3334        Node::Picture {
3335            caption: Some(caption.into()),
3336            caption_href: None,
3337            image: None,
3338            classification: None,
3339            caption_parent,
3340        }
3341    }
3342
3343    fn group(children: Vec<Node>) -> Node {
3344        Node::Group {
3345            label: "section".into(),
3346            name: None,
3347            layer: None,
3348            children,
3349        }
3350    }
3351
3352    fn refs(v: &Value) -> Vec<&str> {
3353        v.as_array()
3354            .unwrap()
3355            .iter()
3356            .map(|r| r["$ref"].as_str().unwrap())
3357            .collect()
3358    }
3359
3360    /// #390: a declarative backend's caption is docling's `add_text` default —
3361    /// a body child, appended as it is created — wherever the picture sits:
3362    /// ahead of a top-level picture, behind the top-level item enclosing a
3363    /// nested one. The picture references it either way and has no children.
3364    #[test]
3365    fn a_body_caption_follows_the_enclosing_top_level_item() {
3366        let mut doc = DoclingDocument::new("t");
3367        doc.push(picture("top", CaptionParent::Body));
3368        doc.push(group(vec![
3369            Node::Paragraph { text: "p".into() },
3370            picture("nested", CaptionParent::Body),
3371        ]));
3372        doc.push(Node::Paragraph {
3373            text: "after".into(),
3374        });
3375        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
3376        assert_eq!(
3377            refs(&v["body"]["children"]),
3378            [
3379                "#/texts/0",
3380                "#/pictures/0",
3381                "#/groups/0",
3382                "#/texts/2",
3383                "#/texts/3"
3384            ]
3385        );
3386        assert_eq!(
3387            refs(&v["groups"][0]["children"]),
3388            ["#/texts/1", "#/pictures/1"]
3389        );
3390        for (cap, pic) in [(0, 0), (2, 1)] {
3391            assert_eq!(v["texts"][cap]["label"], "caption");
3392            assert_eq!(v["texts"][cap]["parent"]["$ref"], "#/body");
3393            assert_eq!(
3394                refs(&v["pictures"][pic]["captions"]),
3395                [format!("#/texts/{cap}")]
3396            );
3397            assert_eq!(v["pictures"][pic]["children"], serde_json::json!([]));
3398        }
3399    }
3400
3401    /// The PDF pipeline's caption is the picture's (or table's) own child,
3402    /// as docling attaches a layout caption.
3403    #[test]
3404    fn an_item_caption_is_the_items_first_child() {
3405        let mut doc = DoclingDocument::new("t");
3406        doc.push(picture("fig", CaptionParent::Item));
3407        doc.push(Node::Table(Table {
3408            rows: vec![vec!["a".into()]],
3409            caption: Some("tab".into()),
3410            caption_parent: CaptionParent::Item,
3411            ..Table::default()
3412        }));
3413        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
3414        assert_eq!(refs(&v["body"]["children"]), ["#/pictures/0", "#/tables/0"]);
3415        assert_eq!(v["texts"][0]["parent"]["$ref"], "#/pictures/0");
3416        assert_eq!(refs(&v["pictures"][0]["children"]), ["#/texts/0"]);
3417        assert_eq!(refs(&v["pictures"][0]["captions"]), ["#/texts/0"]);
3418        assert_eq!(v["texts"][1]["parent"]["$ref"], "#/tables/0");
3419        assert_eq!(refs(&v["tables"][0]["children"]), ["#/texts/1"]);
3420        assert_eq!(refs(&v["tables"][0]["captions"]), ["#/texts/1"]);
3421    }
3422
3423    /// A PDF picture's contained text (`Node::PictureChildren`) is written as
3424    /// docling's `_add_child_elements` writes it: items parented to the
3425    /// picture, after its caption in the picture's `children`, never in the
3426    /// body; a list item opens its own list group under the picture. The
3427    /// Markdown and the chunker's refs are unaffected.
3428    #[test]
3429    fn picture_children_hang_off_the_picture_after_its_caption() {
3430        let mut doc = DoclingDocument::new("t");
3431        doc.push(picture("fig", CaptionParent::Item));
3432        doc.push(Node::PictureChildren(vec![
3433            Node::Heading {
3434                level: 2,
3435                text: "in-figure title".into(),
3436            },
3437            Node::Paragraph {
3438                text: "axis label".into(),
3439            },
3440            Node::ListItem {
3441                ordered: false,
3442                number: 0,
3443                first_in_list: true,
3444                text: "callout".into(),
3445                level: 0,
3446                marker: None,
3447                location: None,
3448                dclx: None,
3449                href: None,
3450                layer: None,
3451            },
3452        ]));
3453        doc.push(Node::Paragraph {
3454            text: "after".into(),
3455        });
3456        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
3457        assert_eq!(refs(&v["body"]["children"]), ["#/pictures/0", "#/texts/4"]);
3458        assert_eq!(
3459            refs(&v["pictures"][0]["children"]),
3460            ["#/texts/0", "#/texts/1", "#/texts/2", "#/groups/0"]
3461        );
3462        assert_eq!(refs(&v["pictures"][0]["captions"]), ["#/texts/0"]);
3463        assert_eq!(v["texts"][1]["label"], "section_header");
3464        assert_eq!(v["texts"][2]["label"], "text");
3465        for t in 1..=2 {
3466            assert_eq!(v["texts"][t]["parent"]["$ref"], "#/pictures/0");
3467            assert_eq!(v["texts"][t]["content_layer"], "body");
3468        }
3469        assert_eq!(v["groups"][0]["parent"]["$ref"], "#/pictures/0");
3470        assert_eq!(v["texts"][3]["parent"]["$ref"], "#/groups/0");
3471        let md = doc.export_to_markdown();
3472        assert!(
3473            !md.contains("axis label") && !md.contains("callout"),
3474            "{md}"
3475        );
3476        assert!(md.contains("after"), "{md}");
3477    }
3478
3479    /// A container caption sits beside its item under the item's parent —
3480    /// ahead of it (an office chart's title) or behind it (an HTML
3481    /// `<figure>`'s table, whose figcaption docling adds after the table).
3482    #[test]
3483    fn a_container_caption_is_the_items_sibling() {
3484        let mut doc = DoclingDocument::new("t");
3485        doc.push(group(vec![
3486            picture("chart", CaptionParent::Container),
3487            Node::Table(Table {
3488                rows: vec![vec!["a".into()]],
3489                caption: Some("figcaption".into()),
3490                caption_parent: CaptionParent::ContainerAfter,
3491                ..Table::default()
3492            }),
3493        ]));
3494        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
3495        assert_eq!(refs(&v["body"]["children"]), ["#/groups/0"]);
3496        assert_eq!(
3497            refs(&v["groups"][0]["children"]),
3498            ["#/texts/0", "#/pictures/0", "#/tables/0", "#/texts/1"]
3499        );
3500        assert_eq!(v["texts"][0]["parent"]["$ref"], "#/groups/0");
3501        assert_eq!(v["texts"][1]["parent"]["$ref"], "#/groups/0");
3502        assert_eq!(v["pictures"][0]["children"], serde_json::json!([]));
3503        assert_eq!(v["tables"][0]["children"], serde_json::json!([]));
3504    }
3505}