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                // docling's checkbox item: the `checkbox_selected` /
1117                // `checkbox_unselected` label carries the state and the text
1118                // is the bare option label (right_to_left_03's `خير`,
1119                // docx_checkboxes' `Orange juice`). The `- [x]` task-list
1120                // marker is Markdown's rendering of it, not item text (#609).
1121                let label = if *checked {
1122                    "checkbox_selected"
1123                } else {
1124                    "checkbox_unselected"
1125                };
1126                Some(self.add_text(label, text, parent, json!({})))
1127            }
1128            Node::Code {
1129                language,
1130                text,
1131                orig,
1132                ..
1133            } => Some(self.add_code(text, language.as_deref(), orig.as_deref(), parent)),
1134            // A CodeFormula-decoded display formula: `text` carries the LaTeX,
1135            // `orig` the raw glyph extraction (docling's enriched shape).
1136            Node::Formula {
1137                latex,
1138                orig,
1139                location,
1140            } => {
1141                self.adopt_loc(*location);
1142                Some(self.add_formula_item(latex, orig, parent))
1143            }
1144            // docling's notes-layer `comment_section` group holding the
1145            // comment's text item. What the annotated items point at differs
1146            // upstream: the docx backend links the group (so a comment's
1147            // replies group together), everything going through
1148            // docling-core's `add_comment` links the note text itself.
1149            Node::CommentSection {
1150                name,
1151                text,
1152                refs_note_text,
1153                grouped,
1154            } => {
1155                if !*grouped {
1156                    // docling-core's bare `add_comment`: the note text sits
1157                    // directly under the parent and is what the back-refs
1158                    // point at.
1159                    let child =
1160                        self.add_text("text", text, parent, json!({ "content_layer": "notes" }));
1161                    self.comment_groups.push(child.clone());
1162                    return Some(child);
1163                }
1164                if let Some((_, self_ref)) = self
1165                    .last_comment_section
1166                    .as_ref()
1167                    .filter(|(n, _)| n == name)
1168                    .cloned()
1169                {
1170                    // Another message of the same thread: a further note in
1171                    // the group already open for this cell.
1172                    let child =
1173                        self.add_text("text", text, &self_ref, json!({ "content_layer": "notes" }));
1174                    if let Some(children) =
1175                        self.groups[group_index(&self_ref)]["children"].as_array_mut()
1176                    {
1177                        children.push(json!({ "$ref": child }));
1178                    }
1179                    self.comment_groups.push(if *refs_note_text {
1180                        child
1181                    } else {
1182                        self_ref.clone()
1183                    });
1184                    return Some(self_ref);
1185                }
1186                let self_ref = format!("#/groups/{}", self.groups.len());
1187                self.groups.push(Value::Null);
1188                let child =
1189                    self.add_text("text", text, &self_ref, json!({ "content_layer": "notes" }));
1190                self.groups[group_index(&self_ref)] = json!({
1191                    "self_ref": self_ref,
1192                    "parent": { "$ref": parent },
1193                    "children": [{ "$ref": child }],
1194                    "content_layer": "notes",
1195                    "name": name,
1196                    "label": "comment_section",
1197                });
1198                self.last_comment_section = Some((name.clone(), self_ref.clone()));
1199                self.comment_groups.push(if *refs_note_text {
1200                    child
1201                } else {
1202                    self_ref.clone()
1203                });
1204                Some(self_ref)
1205            }
1206            // The annotation itself is a cross-reference: emit the item, then
1207            // remember it so the group refs can be filled in at the end.
1208            Node::Commented { comments, inner } => {
1209                let item = self.add_node(inner, parent)?;
1210                if !comments.is_empty() {
1211                    self.pending_comments.push((item.clone(), comments.clone()));
1212                }
1213                Some(item)
1214            }
1215            Node::Table(t) => Some(self.add_table(t, parent)),
1216            Node::Picture {
1217                caption,
1218                caption_href,
1219                image,
1220                classification,
1221                caption_parent,
1222                caption_location,
1223            } => Some(self.add_picture(
1224                caption.as_deref(),
1225                caption_href.as_deref(),
1226                image.as_ref(),
1227                classification.as_deref().map(classification_meta),
1228                parent,
1229                (*caption_parent, *caption_location),
1230            )),
1231            // A chart is a picture item in the JSON with docling's chart
1232            // meta — `classification` (the chart kind, as the one prediction)
1233            // and `tabular_chart.chart_data`, the series reconstructed as a
1234            // `TableData` (#405) — and no image payload.
1235            Node::Chart {
1236                kind,
1237                table,
1238                caption,
1239                location,
1240            } => {
1241                self.adopt_loc(*location);
1242                let mut meta = json!({
1243                    "classification": { "predictions": [{ "class_name": kind }] },
1244                });
1245                if !table.rows.is_empty() {
1246                    meta["tabular_chart"] = json!({ "chart_data": table_data(table) });
1247                }
1248                // docling's office backends add the chart's title as a caption
1249                // item of the *container* (the sheet group, the slide), listed
1250                // before the picture that references it, with the chart's own
1251                // box and a charspan over the caption text — not as a child
1252                // of the picture, which is where a PDF caption lives.
1253                let mut captions = Vec::new();
1254                if let Some(cap) = caption.as_deref().filter(|c| !c.is_empty()) {
1255                    let prov = self.prov_json(unescape_text(cap).chars().count(), true);
1256                    let cap_ref = self.add_text_with("caption", cap, parent, json!({}), prov);
1257                    self.pending_siblings.push(json!({ "$ref": cap_ref }));
1258                    captions.push(json!({ "$ref": cap_ref }));
1259                }
1260                let prov = self.take_prov(0);
1261                Some(self.push_picture(prov, captions, Vec::new(), None, Some(meta), parent))
1262            }
1263            // A DocLang-only node is omitted from the JSON body.
1264            Node::DoclangOnly(_) => None,
1265            Node::Group {
1266                label,
1267                name,
1268                layer,
1269                children,
1270            } => Some(self.add_group(label, name.as_deref(), *layer, children, parent)),
1271            Node::FieldRegion { items } => Some(self.add_field_region(items, parent)),
1272            Node::KeyValueGraph { cells, links } => {
1273                Some(self.add_key_value_graph(cells, links, parent))
1274            }
1275            // A rich inline group is a text item over its Markdown text; the
1276            // structured runs are DocLang-only, so the JSON matches a paragraph.
1277            Node::InlineGroup { md_text, .. } => {
1278                Some(self.add_text("text", md_text, parent, json!({})))
1279            }
1280            // A plain-text backend dump is a single text item over the file body.
1281            Node::TextDump(text) => Some(self.add_text("text", text, parent, json!({}))),
1282            // Speaker notes are content a deck carries, and docling puts them
1283            // in the JSON on their own layer, so a consumer reading only JSON
1284            // can pick them (#402). Page furniture stays out of the flat
1285            // path; a backend that builds docling's item tree (HTML) puts its
1286            // furniture-layer items in the JSON through `write_tree`.
1287            Node::Furniture {
1288                layer: ContentLayer::Notes,
1289                inner,
1290            } => {
1291                let item = self.add_node(inner, parent)?;
1292                self.set_layer(&item, "notes");
1293                Some(item)
1294            }
1295            Node::Furniture { .. } => None,
1296            // PDF page headers and footers: docling writes them as body-parented
1297            // `page_header`/`page_footer` text items on the furniture layer, so a
1298            // JSON consumer can read running headers (printed page ids, dates).
1299            Node::PageFurniture {
1300                footer,
1301                location,
1302                text,
1303            } => {
1304                if self.cur_page > 0 {
1305                    self.pending_loc = Some(*location);
1306                }
1307                let label = if *footer {
1308                    "page_footer"
1309                } else {
1310                    "page_header"
1311                };
1312                let item = self.add_text(label, text, parent, json!({}));
1313                self.pending_loc = None;
1314                self.set_layer(&item, "furniture");
1315                Some(item)
1316            }
1317            // A labelled furniture paragraph (a `.doc` header / footer or
1318            // note body, #535): the item docling's office backends write.
1319            Node::FurnitureText { label, text } => {
1320                let item = self.add_text(label, text, parent, json!({}));
1321                self.set_layer(&item, "furniture");
1322                Some(item)
1323            }
1324            // A PDF picture's contained text (docling's `_add_child_elements`):
1325            // items parented to the picture just written, listed after its
1326            // caption in that picture's `children`.
1327            Node::PictureChildren(children) => {
1328                let pic = self.pictures.len().checked_sub(1)?;
1329                let pic_ref = format!("#/pictures/{pic}");
1330                let refs = self.walk_into(children, &pic_ref);
1331                if let Some(list) = self.pictures[pic]["children"].as_array_mut() {
1332                    list.extend(refs);
1333                }
1334                None
1335            }
1336            // A location wrapper turns into the wrapped item's `prov` entry —
1337            // but only on pages the PDF paths described with a PageInfo marker
1338            // (other geometry-bearing backends, e.g. PPTX shapes, keep their
1339            // pre-#171 provenance-less JSON until they emit markers too).
1340            Node::Located { location, inner } => {
1341                if self.cur_page > 0 {
1342                    self.pending_loc = Some(*location);
1343                }
1344                let r = self.add_node(inner, parent);
1345                self.pending_loc = None;
1346                r
1347            }
1348            Node::Prov {
1349                page_no,
1350                bbox,
1351                charspan,
1352                inner,
1353                ..
1354            } => {
1355                self.pending_exact = Some(ExactProv {
1356                    page_no: *page_no,
1357                    bbox: bbox.map(f64::from),
1358                    bottom_left: false,
1359                    charspan: *charspan,
1360                });
1361                let r = self.add_node(inner, parent);
1362                self.pending_exact = None;
1363                r
1364            }
1365            // Page breaks are DocLang-only; docling omits them from the JSON body.
1366            Node::PageBreak => None,
1367            // The page marker: record the page's number and size for the
1368            // `pages` map, and denormalize every following location against it.
1369            Node::PageInfo {
1370                page_no,
1371                width,
1372                height,
1373            } => {
1374                self.cur_page = *page_no;
1375                self.cur_w = *width as f64;
1376                self.cur_h = *height as f64;
1377                if *page_no > 0 {
1378                    self.pages.push((*page_no, self.cur_w, self.cur_h));
1379                }
1380                None
1381            }
1382            // Handled by `add_list` in `walk`.
1383            Node::ListItem { .. } => None,
1384        }
1385    }
1386
1387    /// A form key-value region: `field_regions/N` holds the region, each field is
1388    /// a `field_items/M` whose children are its `marker` / `field_key` /
1389    /// `field_value` texts (absent parts are simply omitted).
1390    fn add_field_region(&mut self, items: &[crate::FieldItem], parent: &str) -> String {
1391        let self_ref = format!("#/field_regions/{}", self.field_regions.len());
1392        self.field_regions.push(Value::Null);
1393        let region_index = self.field_regions.len() - 1;
1394        let mut item_refs = Vec::new();
1395        for item in items {
1396            item_refs.push(json!({ "$ref": self.add_field_item(item, &self_ref) }));
1397        }
1398        self.field_regions[region_index] = json!({
1399            "self_ref": self_ref,
1400            "parent": { "$ref": parent },
1401            "children": item_refs,
1402            "content_layer": "body",
1403            "label": "field_region",
1404            "prov": [],
1405        });
1406        self_ref
1407    }
1408
1409    /// A `KeyValueItem`: docling's `GraphData` written cell for cell and link
1410    /// for link (`key_value_items/N`), the item itself childless and without
1411    /// provenance, the way the XBRL backend creates it.
1412    fn add_key_value_graph(
1413        &mut self,
1414        cells: &[crate::GraphCell],
1415        links: &[crate::GraphLink],
1416        parent: &str,
1417    ) -> String {
1418        let self_ref = format!("#/key_value_items/{}", self.key_value_items.len());
1419        let cells: Vec<Value> = cells
1420            .iter()
1421            .map(|c| {
1422                json!({
1423                    "label": c.label,
1424                    "cell_id": c.cell_id,
1425                    "text": c.text,
1426                    "orig": c.orig,
1427                })
1428            })
1429            .collect();
1430        let links: Vec<Value> = links
1431            .iter()
1432            .map(|l| {
1433                json!({
1434                    "label": l.label,
1435                    "source_cell_id": l.source_cell_id,
1436                    "target_cell_id": l.target_cell_id,
1437                })
1438            })
1439            .collect();
1440        self.key_value_items.push(json!({
1441            "self_ref": self_ref,
1442            "parent": { "$ref": parent },
1443            "children": [],
1444            "content_layer": "body",
1445            "label": "key_value_region",
1446            "prov": [],
1447            "captions": [],
1448            "references": [],
1449            "footnotes": [],
1450            "graph": { "cells": cells, "links": links },
1451        }));
1452        self_ref
1453    }
1454
1455    fn add_field_item(&mut self, item: &crate::FieldItem, parent: &str) -> String {
1456        let self_ref = format!("#/field_items/{}", self.field_items.len());
1457        self.field_items.push(Value::Null);
1458        let item_index = self.field_items.len() - 1;
1459        let mut child_refs = Vec::new();
1460        for (label, text) in [
1461            ("marker", &item.marker),
1462            ("field_key", &item.key),
1463            ("field_value", &item.value),
1464        ] {
1465            if let Some(text) = text {
1466                // A value's `kind` (docling's `read_only` / `fillable`)
1467                // follows its text.
1468                let extra = match (label, &item.value_kind) {
1469                    ("field_value", Some(kind)) => json!({ "kind": kind }),
1470                    _ => json!({}),
1471                };
1472                child_refs.push(json!({ "$ref": self.add_text(label, text, &self_ref, extra) }));
1473            }
1474        }
1475        self.field_items[item_index] = json!({
1476            "self_ref": self_ref,
1477            "parent": { "$ref": parent },
1478            "children": child_refs,
1479            "content_layer": "body",
1480            "label": "field_item",
1481            "prov": [],
1482        });
1483        self_ref
1484    }
1485
1486    /// Move an already-emitted item onto a content layer. Notes are single
1487    /// text items today; a deeper notes subtree would need its children moved
1488    /// too, and no backend builds one.
1489    fn set_layer(&mut self, self_ref: &str, layer: &str) {
1490        let bucket = match self_ref.split('/').nth(1) {
1491            Some("texts") => &mut self.texts,
1492            Some("tables") => &mut self.tables,
1493            Some("pictures") => &mut self.pictures,
1494            Some("groups") => &mut self.groups,
1495            _ => return,
1496        };
1497        if let Some(item) = self_ref
1498            .rsplit('/')
1499            .next()
1500            .and_then(|i| i.parse::<usize>().ok())
1501            .and_then(|i| bucket.get_mut(i))
1502        {
1503            item["content_layer"] = json!(layer);
1504        }
1505    }
1506
1507    fn add_text(&mut self, label: &str, text: &str, parent: &str, extra: Value) -> String {
1508        let prov = self.take_prov(unescape_text(text).chars().count());
1509        self.add_text_with(label, text, parent, extra, prov)
1510    }
1511
1512    /// [`Self::add_text`] with an explicit `prov` (a chart caption shares the
1513    /// chart's box without consuming it).
1514    fn add_text_with(
1515        &mut self,
1516        label: &str,
1517        text: &str,
1518        parent: &str,
1519        extra: Value,
1520        prov: Value,
1521    ) -> String {
1522        let self_ref = format!("#/texts/{}", self.texts.len());
1523        let raw = unescape_text(text);
1524        let mut item = json!({
1525            "self_ref": self_ref,
1526            "parent": { "$ref": parent },
1527            "children": [],
1528            "content_layer": "body",
1529            "label": label,
1530            "prov": prov,
1531            "orig": raw,
1532            "text": raw,
1533        });
1534        merge(&mut item, extra);
1535        self.texts.push(item);
1536        self_ref
1537    }
1538
1539    /// A display-math formula item. `latex` is the raw content (no `$$`); docling
1540    /// re-wraps it and never escapes it.
1541    fn add_formula(&mut self, latex: &str, parent: &str) -> String {
1542        let self_ref = format!("#/texts/{}", self.texts.len());
1543        let prov = self.take_prov(latex.chars().count());
1544        self.texts.push(json!({
1545            "self_ref": self_ref,
1546            "parent": { "$ref": parent },
1547            "children": [],
1548            "content_layer": "body",
1549            "label": "formula",
1550            "prov": prov,
1551            "orig": latex,
1552            "text": latex,
1553        }));
1554        self_ref
1555    }
1556
1557    /// A CodeFormula-enriched display formula: `text` is the model's LaTeX
1558    /// while `orig` keeps the raw glyph extraction (docling's enriched shape;
1559    /// the plain [`Self::add_formula`] above sets both to the same string).
1560    fn add_formula_item(&mut self, latex: &str, orig: &str, parent: &str) -> String {
1561        let self_ref = format!("#/texts/{}", self.texts.len());
1562        let prov = self.take_prov(latex.chars().count());
1563        self.texts.push(json!({
1564            "self_ref": self_ref,
1565            "parent": { "$ref": parent },
1566            "children": [],
1567            "content_layer": "body",
1568            "label": "formula",
1569            "prov": prov,
1570            "orig": orig,
1571            "text": latex,
1572        }));
1573        self_ref
1574    }
1575
1576    fn add_code(
1577        &mut self,
1578        text: &str,
1579        language: Option<&str>,
1580        orig: Option<&str>,
1581        parent: &str,
1582    ) -> String {
1583        let self_ref = format!("#/texts/{}", self.texts.len());
1584        let raw = unescape_text(text);
1585        let prov = self.take_prov(raw.chars().count());
1586        self.texts.push(json!({
1587            "self_ref": self_ref,
1588            "parent": { "$ref": parent },
1589            "children": [],
1590            "content_layer": "body",
1591            "label": "code",
1592            "prov": prov,
1593            // With code enrichment, `text` is the model's rewrite while `orig`
1594            // keeps the raw extraction; otherwise both are the same string.
1595            "orig": orig.map(unescape_text).unwrap_or_else(|| raw.clone()),
1596            "text": raw,
1597            "captions": [],
1598            "references": [],
1599            "footnotes": [],
1600            "code_language": code_language(language),
1601        }));
1602        self_ref
1603    }
1604
1605    /// Build a list group from a run of (possibly multi-level) list items. A
1606    /// deeper level starts a nested list under the preceding item.
1607    fn add_list(&mut self, items: &[Node], parent: &str) -> String {
1608        let self_ref = format!("#/groups/{}", self.groups.len());
1609        // reserve the slot so nested groups get later indices
1610        self.groups.push(Value::Null);
1611        let base = level_of(&items[0]);
1612        let mut children = Vec::new();
1613        let mut i = 0;
1614        while i < items.len() {
1615            // Empty paragraphs absorbed into the run (blank lines between items)
1616            // are not list items — skip them.
1617            if !matches!(items[i], Node::ListItem { .. }) {
1618                i += 1;
1619                continue;
1620            }
1621            let lvl = level_of(&items[i]);
1622            if lvl > base {
1623                // shouldn't happen at the head; skip defensively
1624                i += 1;
1625                continue;
1626            }
1627            let item_ref = self.add_list_item(&items[i], &self_ref);
1628            // collect any deeper items that nest under this one
1629            let mut j = i + 1;
1630            while j < items.len() && level_of(&items[j]) > base {
1631                j += 1;
1632            }
1633            if j > i + 1 {
1634                let mut nested = Vec::new();
1635                self.add_sibling_lists(&items[i + 1..j], &item_ref, &mut nested);
1636                // the nested list group(s) are children of this item
1637                if let Some(idx) = ref_index(&item_ref) {
1638                    self.texts[idx]["children"]
1639                        .as_array_mut()
1640                        .unwrap()
1641                        .extend(nested);
1642                }
1643            }
1644            children.push(json!({ "$ref": item_ref }));
1645            i = j;
1646        }
1647        self.groups[group_index(&self_ref)] = json!({
1648            "self_ref": self_ref,
1649            "parent": { "$ref": parent },
1650            "children": children,
1651            "content_layer": "body",
1652            "name": "list",
1653            "label": "list",
1654        });
1655        self_ref
1656    }
1657
1658    fn add_list_item(&mut self, node: &Node, parent: &str) -> String {
1659        let Node::ListItem {
1660            ordered,
1661            number,
1662            text,
1663            location,
1664            ..
1665        } = node
1666        else {
1667            unreachable!()
1668        };
1669        self.adopt_loc(*location);
1670        let self_ref = format!("#/texts/{}", self.texts.len());
1671        let raw = unescape_text(text);
1672        let prov = self.take_prov(raw.chars().count());
1673        let marker = if *ordered {
1674            format!("{number}.")
1675        } else {
1676            "-".to_string()
1677        };
1678        self.texts.push(json!({
1679            "self_ref": self_ref,
1680            "parent": { "$ref": parent },
1681            "children": [],
1682            "content_layer": "body",
1683            "label": "list_item",
1684            "prov": prov,
1685            "orig": raw,
1686            "text": raw,
1687            "enumerated": ordered,
1688            "marker": marker,
1689        }));
1690        self_ref
1691    }
1692
1693    fn add_table(&mut self, t: &Table, parent: &str) -> String {
1694        self.add_table_with(t, parent, false)
1695    }
1696
1697    /// [`Self::add_table`]; `raw` cell text is written verbatim (see
1698    /// [`table_data_with`]).
1699    fn add_table_with(&mut self, t: &Table, parent: &str, raw: bool) -> String {
1700        let self_ref = format!("#/tables/{}", self.tables.len());
1701        self.adopt_loc(t.location);
1702        let prov = self.take_prov(0);
1703        // The caption is a separate text item the table references (docling's
1704        // `TableItem.captions`), added before the grid so its box isn't
1705        // inherited by a later item.
1706        let (captions, children) = match t.caption.as_deref().filter(|c| !c.is_empty()) {
1707            Some(cap) => self.add_caption(
1708                cap,
1709                json!({}),
1710                &self_ref,
1711                parent,
1712                (t.caption_parent, t.caption_location),
1713            ),
1714            None => (Vec::new(), Vec::new()),
1715        };
1716        let data = table_data_with(t, raw);
1717        self.tables.push(json!({
1718            "self_ref": self_ref,
1719            "parent": { "$ref": parent },
1720            "children": children,
1721            "content_layer": "body",
1722            "label": "table",
1723            "prov": prov,
1724            "captions": captions,
1725            "references": [],
1726            "footnotes": [],
1727            "data": data,
1728            "annotations": [],
1729        }));
1730        self_ref
1731    }
1732
1733    /// Add a picture's or table's caption text item where `choice` says it
1734    /// hangs (#390), returning the `captions` entry for the item and the
1735    /// item's own `children` (the caption, when it is the item's child).
1736    /// The caption never consumes the item's pending provenance — the item
1737    /// takes its box first. Its own box, when the backend kept one (the PDF
1738    /// pipeline's caption region, #609), becomes the caption's `prov` on the
1739    /// item's page, as docling's reading-order model gives every caption the
1740    /// cluster it came from; without one the caption has no `prov`.
1741    fn add_caption(
1742        &mut self,
1743        text: &str,
1744        extra: Value,
1745        self_ref: &str,
1746        parent: &str,
1747        (choice, location): (CaptionParent, Option<[u16; 4]>),
1748    ) -> (Vec<Value>, Vec<Value>) {
1749        // docling's PDF pipeline parents the caption to the item; every
1750        // declarative backend leaves `add_text`'s default — the body — even
1751        // for an item inside a group; the office backends and HTML's
1752        // `<figure>` hang it off the item's container.
1753        let cap_parent = match choice {
1754            CaptionParent::Item => self_ref,
1755            CaptionParent::Container | CaptionParent::ContainerAfter => parent,
1756            CaptionParent::Body => "#/body",
1757        };
1758        if self.cur_page > 0 && location.is_some() {
1759            self.pending_loc = location;
1760        }
1761        let cap_ref = json!({ "$ref": self.add_text("caption", text, cap_parent, extra) });
1762        match choice {
1763            CaptionParent::Item => return (vec![cap_ref.clone()], vec![cap_ref]),
1764            // Created ahead of the item, so it precedes the item in the
1765            // container's children — and, on the body, in the body's.
1766            CaptionParent::Container => self.pending_siblings.push(cap_ref.clone()),
1767            CaptionParent::Body if parent == "#/body" => {
1768                self.pending_siblings.push(cap_ref.clone())
1769            }
1770            CaptionParent::ContainerAfter => self.pending_after.push(cap_ref.clone()),
1771            // The item sits deeper: the body's children get the caption after
1772            // the top-level item under walk, where docling appended it.
1773            CaptionParent::Body => self.pending_body.push(cap_ref.clone()),
1774        }
1775        (vec![cap_ref], Vec::new())
1776    }
1777
1778    /// `meta` is the picture's docling `PictureMeta` (a classifier's
1779    /// predictions, a chart's kind and data), `None` for a plain picture.
1780    fn add_picture(
1781        &mut self,
1782        caption: Option<&str>,
1783        caption_href: Option<&str>,
1784        image: Option<&crate::PictureImage>,
1785        meta: Option<Value>,
1786        parent: &str,
1787        caption_at: (CaptionParent, Option<[u16; 4]>),
1788    ) -> String {
1789        let self_ref = format!("#/pictures/{}", self.pictures.len());
1790        // Take the picture's own provenance before the caption text is added —
1791        // the caption is a separate item and must not inherit the crop's box.
1792        let prov = self.take_prov(0);
1793        let (captions, children) = match caption.filter(|c| !c.is_empty()) {
1794            Some(cap) => {
1795                // Emit the caption as a text item that the picture references. A
1796                // wrapping `<a href>`'s link rides as docling's `hyperlink` field
1797                // on the caption item (#328).
1798                let extra = match caption_href {
1799                    Some(href) => json!({ "hyperlink": href }),
1800                    None => json!({}),
1801                };
1802                self.add_caption(cap, extra, &self_ref, parent, caption_at)
1803            }
1804            None => (Vec::new(), Vec::new()),
1805        };
1806        self.push_picture(prov, captions, children, image, meta, parent)
1807    }
1808
1809    /// Append the picture item itself — `prov`, `captions` and `children`
1810    /// (a PDF caption is the picture's child) already settled.
1811    fn push_picture(
1812        &mut self,
1813        prov: Value,
1814        captions: Vec<Value>,
1815        children: Vec<Value>,
1816        image: Option<&crate::PictureImage>,
1817        meta: Option<Value>,
1818        parent: &str,
1819    ) -> String {
1820        let self_ref = format!("#/pictures/{}", self.pictures.len());
1821        // The legacy `classification` annotation rides along with a
1822        // classifier's `meta` (see `classification_meta`); a chart's meta has
1823        // none, like docling's.
1824        let annotations = meta
1825            .as_ref()
1826            .and_then(|m| m.get("annotations").cloned())
1827            .unwrap_or_else(|| json!([]));
1828        let meta = meta.map(|mut m| {
1829            if let Some(obj) = m.as_object_mut() {
1830                obj.remove("annotations");
1831            }
1832            m
1833        });
1834        // `meta` sits between `content_layer` and `label` in docling's field
1835        // order (and `preserve_order` keeps ours byte-compatible), so the item
1836        // is built in one shot per shape rather than patched afterwards.
1837        let mut item = match meta {
1838            Some(meta) => json!({
1839                "self_ref": self_ref,
1840                "parent": { "$ref": parent },
1841                "children": children,
1842                "content_layer": "body",
1843                "meta": meta,
1844                "label": "picture",
1845                "prov": prov,
1846                "captions": captions,
1847                "references": [],
1848                "footnotes": [],
1849                "annotations": annotations,
1850            }),
1851            None => json!({
1852                "self_ref": self_ref,
1853                "parent": { "$ref": parent },
1854                "children": children,
1855                "content_layer": "body",
1856                "label": "picture",
1857                "prov": prov,
1858                "captions": captions,
1859                "references": [],
1860                "footnotes": [],
1861                "annotations": annotations,
1862            }),
1863        };
1864        // docling stores the extracted image as an `ImageRef` (data URI + size,
1865        // the size as floats) between `footnotes` and `annotations` — pydantic
1866        // field order, which `preserve_order` lets us reproduce by rebuilding
1867        // the tail.
1868        if let Some(img) = image {
1869            let image = image_ref_json(img);
1870            if let Some(obj) = item.as_object_mut() {
1871                let annotations = obj.remove("annotations").unwrap_or_else(|| json!([]));
1872                obj.insert("image".into(), image);
1873                obj.insert("annotations".into(), annotations);
1874            }
1875        }
1876        self.pictures.push(item);
1877        self_ref
1878    }
1879
1880    fn add_group(
1881        &mut self,
1882        label: &str,
1883        name: Option<&str>,
1884        layer: Option<ContentLayer>,
1885        nodes: &[Node],
1886        parent: &str,
1887    ) -> String {
1888        let self_ref = format!("#/groups/{}", self.groups.len());
1889        self.groups.push(Value::Null);
1890        // Everything the walk creates belongs to this group, so a non-body
1891        // layer (a hidden sheet) is stamped on the whole subtree afterwards —
1892        // docling puts the layer on the group *and* on every item under it.
1893        let mark = (
1894            self.texts.len(),
1895            self.tables.len(),
1896            self.pictures.len(),
1897            self.groups.len(),
1898        );
1899        let children = self.walk_into(nodes, &self_ref);
1900        let name = name.unwrap_or(if label == "inline" { "group" } else { label });
1901        let content_layer = layer.map_or("body", |l| l.value());
1902        self.groups[group_index(&self_ref)] = json!({
1903            "self_ref": self_ref,
1904            "parent": { "$ref": parent },
1905            "children": children,
1906            "content_layer": content_layer,
1907            "name": name,
1908            "label": label,
1909        });
1910        if layer.is_some() {
1911            let (t, tb, p, g) = mark;
1912            for item in self.texts[t..]
1913                .iter_mut()
1914                .chain(self.tables[tb..].iter_mut())
1915                .chain(self.pictures[p..].iter_mut())
1916                .chain(self.groups[g..].iter_mut())
1917            {
1918                if let Some(obj) = item.as_object_mut() {
1919                    obj.insert("content_layer".into(), json!(content_layer));
1920                }
1921            }
1922        }
1923        self_ref
1924    }
1925
1926    /// Walk a slice of sibling nodes, returning each child's `$ref`; runs of
1927    /// list items are folded into list groups (one per sibling list).
1928    fn walk_into(&mut self, nodes: &[Node], parent: &str) -> Vec<Value> {
1929        // Siblings that all carry a creation rank (an XLSX sheet's items) are
1930        // *added* in that order — so `#/tables/N` and friends are numbered as
1931        // docling numbers them — while their refs keep the node order, which
1932        // is docling's position-sorted `children`.
1933        let seqs: Option<Vec<usize>> = nodes
1934            .iter()
1935            .map(|n| match n {
1936                Node::Prov { seq: Some(s), .. } => Some(*s),
1937                _ => None,
1938            })
1939            .collect();
1940        if let Some(seqs) = seqs.filter(|s| !s.is_empty()) {
1941            let mut order: Vec<usize> = (0..nodes.len()).collect();
1942            order.sort_by_key(|&i| seqs[i]);
1943            let mut slots: Vec<Vec<Value>> = vec![Vec::new(); nodes.len()];
1944            for i in order {
1945                if let Some(r) = self.add_node(&nodes[i], parent) {
1946                    slots[i].append(&mut self.pending_siblings);
1947                    slots[i].push(json!({ "$ref": r }));
1948                    slots[i].append(&mut self.pending_after);
1949                }
1950                if parent == "#/body" {
1951                    slots[i].append(&mut self.pending_body);
1952                }
1953            }
1954            return slots.into_iter().flatten().collect();
1955        }
1956        let mut children = Vec::new();
1957        let mut i = 0;
1958        while i < nodes.len() {
1959            if matches!(nodes[i], Node::ListItem { .. }) {
1960                let start = i;
1961                i += 1;
1962                loop {
1963                    match nodes.get(i) {
1964                        Some(Node::ListItem { .. }) => i += 1,
1965                        // Absorb an empty paragraph sitting between two list
1966                        // items (docling keeps the ListGroup contiguous).
1967                        Some(Node::Paragraph { text })
1968                            if text.is_empty()
1969                                && matches!(nodes.get(i + 1), Some(Node::ListItem { .. })) =>
1970                        {
1971                            i += 1
1972                        }
1973                        _ => break,
1974                    }
1975                }
1976                self.add_sibling_lists(&nodes[start..i], parent, &mut children);
1977            } else {
1978                if let Some(r) = self.add_node(&nodes[i], parent) {
1979                    children.append(&mut self.pending_siblings);
1980                    children.push(json!({ "$ref": r }));
1981                    children.append(&mut self.pending_after);
1982                }
1983                i += 1;
1984            }
1985            // Body-parented captions of items deeper in the tree follow the
1986            // top-level item they were created under (#390).
1987            if parent == "#/body" {
1988                children.append(&mut self.pending_body);
1989            }
1990        }
1991        children
1992    }
1993
1994    /// A run of list items may hold several *sibling* lists; emit one list group
1995    /// per sibling. The boundary is the backend's `first_in_list` flag on a
1996    /// base-level item — the same rule as the Markdown serializer's blank line
1997    /// (#385; the kind-flip and number-gap guesses are gone).
1998    fn add_sibling_lists(&mut self, run: &[Node], parent: &str, out: &mut Vec<Value>) {
1999        let base = level_of(&run[0]);
2000        let mut seg = 0;
2001        for k in 0..run.len() {
2002            let Node::ListItem {
2003                first_in_list,
2004                level,
2005                ..
2006            } = &run[k]
2007            else {
2008                continue;
2009            };
2010            if *level != base {
2011                continue; // nested item — handled inside add_list
2012            }
2013            if k > seg && *first_in_list {
2014                out.push(json!({ "$ref": self.add_list(&run[seg..k], parent) }));
2015                seg = k;
2016            }
2017        }
2018        out.push(json!({ "$ref": self.add_list(&run[seg..], parent) }));
2019    }
2020}
2021
2022fn level_of(node: &Node) -> u8 {
2023    match node {
2024        Node::ListItem { level, .. } => *level,
2025        _ => 0,
2026    }
2027}
2028
2029fn group_index(self_ref: &str) -> usize {
2030    self_ref.rsplit('/').next().unwrap().parse().unwrap()
2031}
2032
2033fn ref_index(self_ref: &str) -> Option<usize> {
2034    self_ref.rsplit('/').next()?.parse().ok()
2035}
2036
2037/// Merge the key/values of `extra` (an object) into `target` (an object).
2038fn merge(target: &mut Value, extra: Value) {
2039    if let (Some(t), Some(e)) = (target.as_object_mut(), extra.as_object()) {
2040        for (k, v) in e {
2041            t.insert(k.clone(), v.clone());
2042        }
2043    }
2044}
2045
2046/// Reverse [`crate`]'s Markdown text escaping (HTML entities + `\_`).
2047fn unescape_text(s: &str) -> String {
2048    s.replace("&lt;", "<")
2049        .replace("&gt;", ">")
2050        .replace("&amp;", "&")
2051        .replace("\\_", "_")
2052}
2053
2054/// 64-bit FNV-1a, a stand-in for docling's `binary_hash` (we lack the source bytes
2055/// at export time; the value only needs to be a stable u64).
2056fn fnv1a(s: &str) -> u64 {
2057    let mut h: u64 = 0xcbf29ce484222325;
2058    for b in s.bytes() {
2059        h ^= b as u64;
2060        h = h.wrapping_mul(0x100000001b3);
2061    }
2062    h
2063}
2064
2065#[cfg(test)]
2066mod tests {
2067    use crate::{
2068        CaptionParent, ContentLayer, DoclingDocument, ImageMode, Node, PictureImage, Table,
2069    };
2070    use serde_json::Value;
2071
2072    fn cell_at(text: &str, row: usize, col: usize, col_span: usize) -> crate::TableCell {
2073        crate::TableCell {
2074            text: text.into(),
2075            bbox: None,
2076            start_row: row,
2077            start_col: col,
2078            row_span: 1,
2079            col_span,
2080            column_header: row == 0,
2081            row_header: false,
2082            row_section: false,
2083        }
2084    }
2085
2086    /// First-class cells past the rows: rectangular rows are the grid and
2087    /// clip them (docling's `TableData.grid` on USPTO's overrun replicas);
2088    /// ragged rows — an xlsx table compacted by `skip_empty_cells` (#271) —
2089    /// are no grid, so the cells' extent sizes it and the omitted positions
2090    /// come back as empty filler cells in `grid` only.
2091    #[test]
2092    fn ragged_rows_take_their_grid_from_first_class_cells() {
2093        let cells = vec![
2094            cell_at("h0", 0, 0, 1),
2095            cell_at("h2", 0, 2, 1),
2096            cell_at("wide", 1, 0, 3),
2097        ];
2098        let export = |rows: Vec<Vec<String>>| -> Value {
2099            let mut doc = DoclingDocument::new("t");
2100            doc.push(Node::Table(Table {
2101                rows,
2102                cells: Some(cells.clone()),
2103                ..Table::default()
2104            }));
2105            let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2106            v["tables"][0]["data"].clone()
2107        };
2108        // Compacted rows: 2 and 3 wide, the cells say the grid is 3 wide.
2109        let data = export(vec![
2110            vec!["h0".into(), "h2".into()],
2111            vec!["wide".into(), "wide".into(), "wide".into()],
2112        ]);
2113        assert_eq!(data["num_rows"], 2);
2114        assert_eq!(data["num_cols"], 3);
2115        assert_eq!(data["table_cells"].as_array().unwrap().len(), 3);
2116        let row0: Vec<&str> = data["grid"][0]
2117            .as_array()
2118            .unwrap()
2119            .iter()
2120            .map(|c| c["text"].as_str().unwrap())
2121            .collect();
2122        assert_eq!(row0, ["h0", "", "h2"]);
2123        assert_eq!(data["table_cells"][2]["col_span"], 3);
2124        // Rectangular rows narrower than the cells: the rows win, the cells
2125        // are clipped to them exactly as before.
2126        let data = export(vec![
2127            vec!["h0".into(), "h2".into()],
2128            vec!["wide".into(), "wide".into()],
2129        ]);
2130        assert_eq!(data["num_cols"], 2);
2131        assert_eq!(data["grid"][0].as_array().unwrap().len(), 2);
2132    }
2133
2134    fn doc_with_image() -> DoclingDocument {
2135        let mut doc = DoclingDocument::new("t");
2136        doc.push(Node::Picture {
2137            caption: Some("Fig 1".into()),
2138            caption_href: None,
2139            image: Some(PictureImage {
2140                dpi: crate::PictureImage::DEFAULT_DPI,
2141                mimetype: "image/png".into(),
2142                width: 4,
2143                height: 2,
2144                data: b"foobar".to_vec(),
2145            }),
2146            classification: None,
2147            caption_parent: Default::default(),
2148            caption_location: None,
2149        });
2150        doc
2151    }
2152
2153    /// #402: a deck's speaker notes are content, and docling puts them in the
2154    /// JSON on the `notes` layer so a consumer reading only JSON can pick them
2155    /// out. Markdown still serializes the body layer alone, and page furniture
2156    /// stays out of the JSON, where docling does keep it.
2157    #[test]
2158    fn notes_layer_items_reach_the_json_but_furniture_does_not() {
2159        let mut doc = DoclingDocument::new("t");
2160        doc.push(Node::Heading {
2161            level: 1,
2162            text: "Slide One".into(),
2163        });
2164        doc.push(Node::Furniture {
2165            layer: ContentLayer::Notes,
2166            inner: Box::new(Node::Located {
2167                location: [0, 0, 0, 0],
2168                inner: Box::new(Node::Paragraph {
2169                    text: "Speaker note for slide 1.".into(),
2170                }),
2171            }),
2172        });
2173        doc.push(Node::Furniture {
2174            layer: ContentLayer::Furniture,
2175            inner: Box::new(Node::Paragraph {
2176                text: "page header".into(),
2177            }),
2178        });
2179
2180        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2181        let texts = v["texts"].as_array().unwrap();
2182        assert_eq!(
2183            texts
2184                .iter()
2185                .map(|t| (
2186                    t["label"].as_str().unwrap(),
2187                    t["content_layer"].as_str().unwrap(),
2188                    t["text"].as_str().unwrap()
2189                ))
2190                .collect::<Vec<_>>(),
2191            vec![
2192                ("title", "body", "Slide One"),
2193                ("text", "notes", "Speaker note for slide 1."),
2194            ],
2195            "the note is carried on its own layer; the furniture is not carried"
2196        );
2197        // The body layer is what Markdown serializes, so it does not change.
2198        assert_eq!(doc.export_to_markdown(), "# Slide One\n");
2199    }
2200
2201    /// #410: a backend that describes merged ranges only as continuation
2202    /// flags (xlsx `<mergeCell>`, docx `gridSpan`/`vMerge`) gets docling's
2203    /// one-`TableCell`-per-range JSON: the anchor's offsets and spans, the
2204    /// entry repeated across the grid positions it covers — not a 1×1 cell
2205    /// per position with the text copied into each.
2206    #[test]
2207    fn continuation_flags_become_spanning_cells() {
2208        let mut doc = DoclingDocument::new("t");
2209        // A1:C2 merged ("merged"), then a plain row underneath.
2210        let rows = vec![
2211            vec!["merged".to_string(), "merged".into(), "merged".into()],
2212            vec!["merged".to_string(), "merged".into(), "merged".into()],
2213            vec!["a".to_string(), "b".into(), "c".into()],
2214        ];
2215        doc.push(Node::Table(crate::Table {
2216            rows,
2217            location: None,
2218            structure: Some(crate::TableStructure {
2219                header_row: vec![true, false, false],
2220                col_continuation: vec![
2221                    vec![false, true, true],
2222                    vec![false, true, true],
2223                    vec![false, false, false],
2224                ],
2225                row_continuation: vec![
2226                    vec![false, false, false],
2227                    vec![true, true, true],
2228                    vec![false, false, false],
2229                ],
2230                row_header: Vec::new(),
2231                col_header: Vec::new(),
2232            }),
2233            cell_blocks: None,
2234            cells: None,
2235            caption: None,
2236            caption_parent: Default::default(),
2237            caption_location: None,
2238        }));
2239        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2240        let data = &v["tables"][0]["data"];
2241        assert_eq!(data["num_rows"], 3);
2242        assert_eq!(data["num_cols"], 3);
2243        let cells = data["table_cells"].as_array().unwrap();
2244        assert_eq!(
2245            cells.len(),
2246            4,
2247            "one cell for the range, three for the plain row"
2248        );
2249        assert_eq!(
2250            cells[0],
2251            serde_json::json!({
2252                "row_span": 2, "col_span": 3,
2253                "start_row_offset_idx": 0, "end_row_offset_idx": 2,
2254                "start_col_offset_idx": 0, "end_col_offset_idx": 3,
2255                "text": "merged", "column_header": true, "row_header": false,
2256                "row_section": false, "fillable": false,
2257            })
2258        );
2259        assert_eq!(cells[1]["text"], "a");
2260        assert_eq!(cells[1]["row_span"], 1);
2261        assert_eq!(cells[1]["column_header"], false);
2262        // The grid repeats the range's entry at every position it covers.
2263        let grid = data["grid"].as_array().unwrap();
2264        assert_eq!(grid.len(), 3);
2265        for (r, row) in grid.iter().take(2).enumerate() {
2266            for (c, cell) in row.as_array().unwrap().iter().enumerate() {
2267                assert_eq!(*cell, cells[0], "grid[{r}][{c}]");
2268            }
2269        }
2270        assert_eq!(grid[2][2]["text"], "c");
2271    }
2272
2273    /// A [`Node::Prov`] wrapper is docling's provenance verbatim — the exact
2274    /// box in a top-left origin, the backend's charspan — and the page marker
2275    /// before it sizes the page; a chart's caption becomes a sibling of the
2276    /// picture in the container, listed first, sharing the chart's box with
2277    /// a charspan over its text. That is the JSON shape of an XLSX sheet.
2278    #[test]
2279    fn exact_provenance_pages_and_chart_captions_follow_docling() {
2280        let mut doc = DoclingDocument::new("t");
2281        doc.push(Node::PageInfo {
2282            page_no: 1,
2283            width: 3.0,
2284            height: 4.0,
2285        });
2286        let table = crate::Table {
2287            rows: vec![vec!["a".to_string(), "b".into()]],
2288            ..Default::default()
2289        };
2290        doc.push(Node::Group {
2291            label: "sheet".into(),
2292            name: Some("Data".into()),
2293            layer: None,
2294            children: vec![
2295                // Node order is the position-sorted one; creation order (the
2296                // `seq`) had the chart first — so the chart is `#/pictures/0`
2297                // *and* its caption `#/texts/0`, while the table stays the
2298                // group's first child.
2299                Node::Prov {
2300                    page_no: 1,
2301                    bbox: [0.0, 0.0, 3.0, 4.0],
2302                    charspan: [0, 0],
2303                    seq: Some(1),
2304                    inner: Box::new(Node::Table(table.clone())),
2305                },
2306                Node::Prov {
2307                    page_no: 1,
2308                    bbox: [0.0, 1.0, 1.0, 1.0],
2309                    charspan: [0, 0],
2310                    seq: Some(0),
2311                    inner: Box::new(Node::Chart {
2312                        kind: "bar_chart".into(),
2313                        table,
2314                        caption: Some("Sales".into()),
2315                        location: Some([0, 128, 170, 128]),
2316                    }),
2317                },
2318            ],
2319        });
2320        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2321        assert_eq!(
2322            v["pages"],
2323            serde_json::json!({"1": {"size": {"width": 3.0, "height": 4.0}, "page_no": 1}})
2324        );
2325        assert_eq!(
2326            v["tables"][0]["prov"],
2327            serde_json::json!([{
2328                "page_no": 1,
2329                "bbox": {"l": 0.0, "t": 0.0, "r": 3.0, "b": 4.0, "coord_origin": "TOPLEFT"},
2330                "charspan": [0, 0],
2331            }])
2332        );
2333        assert_eq!(v["tables"][0]["data"]["orientation"], "rot_0");
2334        // The caption is the group's child *before* the picture, parented to
2335        // the group, and referenced by the picture.
2336        let sheet = &v["groups"][0];
2337        assert_eq!(
2338            sheet["children"],
2339            serde_json::json!([
2340                {"$ref": "#/tables/0"}, {"$ref": "#/texts/0"}, {"$ref": "#/pictures/0"}
2341            ])
2342        );
2343        let cap = &v["texts"][0];
2344        assert_eq!(cap["label"], "caption");
2345        assert_eq!(cap["parent"], serde_json::json!({"$ref": "#/groups/0"}));
2346        assert_eq!(cap["prov"][0]["charspan"], serde_json::json!([0, 5]));
2347        assert_eq!(cap["prov"][0]["bbox"]["b"], 1.0);
2348        let pic = &v["pictures"][0];
2349        assert_eq!(pic["captions"], serde_json::json!([{"$ref": "#/texts/0"}]));
2350        assert_eq!(pic["prov"][0]["charspan"], serde_json::json!([0, 0]));
2351        assert_eq!(pic["prov"][0]["bbox"]["coord_origin"], "TOPLEFT");
2352        assert_eq!(
2353            pic["meta"]["classification"]["predictions"][0]["class_name"],
2354            "bar_chart"
2355        );
2356        assert_eq!(pic["meta"]["tabular_chart"]["chart_data"]["num_cols"], 2);
2357    }
2358
2359    /// An all-zero location is the "no geometry" sentinel — a slide's speaker
2360    /// notes carry one — and docling writes it as a zero bbox, not as a box
2361    /// spanning the whole page, which is what denormalizing the grid gives.
2362    #[test]
2363    fn a_zero_location_is_a_zero_bbox_not_the_whole_page() {
2364        let mut doc = DoclingDocument::new("t");
2365        doc.push(Node::PageInfo {
2366            page_no: 1,
2367            width: 12192000.0,
2368            height: 6858000.0,
2369        });
2370        doc.push(Node::Furniture {
2371            layer: ContentLayer::Notes,
2372            inner: Box::new(Node::Located {
2373                location: [0, 0, 0, 0],
2374                inner: Box::new(Node::Paragraph {
2375                    text: "a note".into(),
2376                }),
2377            }),
2378        });
2379        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2380        let prov = &v["texts"][0]["prov"][0];
2381        assert_eq!(prov["page_no"], 1);
2382        assert_eq!(prov["charspan"], serde_json::json!([0, 6]));
2383        assert_eq!(
2384            prov["bbox"],
2385            serde_json::json!({"l": 0.0, "t": 0.0, "r": 0.0, "b": 0.0, "coord_origin": "BOTTOMLEFT"})
2386        );
2387        // The page itself is recorded at its true size.
2388        assert_eq!(
2389            v["pages"]["1"]["size"],
2390            serde_json::json!({"width": 12192000.0, "height": 6858000.0})
2391        );
2392    }
2393
2394    /// #171: PageInfo markers become the `pages` map, and `Located` wrappers /
2395    /// node-level locations become per-item `prov` — the 0–511 grid
2396    /// denormalized against the page into BOTTOMLEFT points. Without markers
2397    /// (every declarative backend) the JSON stays exactly as before: empty
2398    /// `pages`, `prov: []` even for located nodes.
2399    /// #609: a PDF caption and a checkbox item carry their own page and box.
2400    /// docling's reading-order model gives every caption the cluster it came
2401    /// from (`_add_caption_or_footnote`), not its picture's or table's, and
2402    /// a checkbox is a text item like any other.
2403    #[test]
2404    fn captions_and_checkboxes_carry_their_own_prov() {
2405        let mut doc = DoclingDocument::new("t");
2406        doc.push(Node::PageInfo {
2407            page_no: 1,
2408            width: 512.0,
2409            height: 512.0,
2410        });
2411        doc.push(Node::Located {
2412            location: [64, 64, 448, 256],
2413            inner: Box::new(Node::Picture {
2414                caption: Some("Figure 1".into()),
2415                caption_href: None,
2416                image: None,
2417                classification: None,
2418                caption_parent: CaptionParent::Item,
2419                caption_location: Some([64, 264, 448, 280]),
2420            }),
2421        });
2422        doc.push(Node::PageInfo {
2423            page_no: 2,
2424            width: 512.0,
2425            height: 512.0,
2426        });
2427        doc.push(Node::Located {
2428            location: [64, 120, 448, 300],
2429            inner: Box::new(Node::Table(Table {
2430                rows: vec![vec!["a".into()]],
2431                caption: Some("Table 1".into()),
2432                caption_parent: CaptionParent::Item,
2433                caption_location: Some([64, 100, 300, 112]),
2434                ..Table::default()
2435            })),
2436        });
2437        doc.push(Node::Located {
2438            location: [64, 320, 200, 332],
2439            inner: Box::new(Node::CheckboxItem {
2440                checked: false,
2441                text: "First option".into(),
2442            }),
2443        });
2444        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2445        let texts = v["texts"].as_array().unwrap();
2446        let by_text = |t: &str| texts.iter().find(|x| x["text"] == t).expect(t).clone();
2447        let bbox = |p: &Value| {
2448            let b = &p["prov"][0]["bbox"];
2449            [&b["l"], &b["t"], &b["r"], &b["b"]].map(|x| x.as_f64().unwrap())
2450        };
2451        // Figure 1: its own box (grid == points on a 512 page, flipped to
2452        // BOTTOMLEFT), not the picture's.
2453        let fig = by_text("Figure 1");
2454        assert_eq!(fig["prov"][0]["page_no"], 1);
2455        assert_eq!(bbox(&fig), [64.0, 248.0, 448.0, 232.0]);
2456        assert_eq!(fig["prov"][0]["charspan"], serde_json::json!([0, 8]));
2457        assert_eq!(fig["parent"]["$ref"], "#/pictures/0");
2458        assert_eq!(v["pictures"][0]["prov"][0]["bbox"]["t"], 448.0);
2459        // Table 1 on page 2, its own box; the table keeps its own.
2460        let tab = by_text("Table 1");
2461        assert_eq!(tab["prov"][0]["page_no"], 2);
2462        assert_eq!(bbox(&tab), [64.0, 412.0, 300.0, 400.0]);
2463        assert_eq!(v["tables"][0]["prov"][0]["bbox"]["t"], 392.0);
2464        // The checkbox item.
2465        let cb = by_text("First option");
2466        assert_eq!(cb["label"], "checkbox_unselected");
2467        assert_eq!(cb["prov"][0]["page_no"], 2);
2468        assert_eq!(bbox(&cb), [64.0, 192.0, 200.0, 180.0]);
2469        assert!(texts
2470            .iter()
2471            .all(|t| !t["prov"].as_array().unwrap().is_empty()));
2472
2473        // Without a caption box (every declarative backend) the caption
2474        // still has no prov, and nothing else moves.
2475        let mut plain = DoclingDocument::new("t");
2476        plain.push(Node::PageInfo {
2477            page_no: 1,
2478            width: 512.0,
2479            height: 512.0,
2480        });
2481        plain.push(Node::Located {
2482            location: [64, 64, 448, 256],
2483            inner: Box::new(Node::Picture {
2484                caption: Some("Figure 1".into()),
2485                caption_href: None,
2486                image: None,
2487                classification: None,
2488                caption_parent: CaptionParent::Item,
2489                caption_location: None,
2490            }),
2491        });
2492        let v: Value = serde_json::from_str(&plain.export_to_json()).unwrap();
2493        assert_eq!(v["texts"][0]["prov"], serde_json::json!([]));
2494        assert_eq!(v["pictures"][0]["prov"][0]["bbox"]["t"], 448.0);
2495    }
2496
2497    #[test]
2498    fn page_markers_produce_pages_and_prov() {
2499        let mut doc = DoclingDocument::new("t");
2500        doc.push(Node::PageInfo {
2501            page_no: 1,
2502            width: 512.0,
2503            height: 1024.0,
2504        });
2505        doc.push(Node::Located {
2506            location: [128, 64, 256, 128], // quarter/eighth points of the grid
2507            inner: Box::new(Node::Paragraph {
2508                text: "hello".into(),
2509            }),
2510        });
2511        doc.push(Node::Table(Table {
2512            rows: vec![vec!["a".into()]],
2513            location: Some([0, 0, 512, 512]),
2514            ..Table::default()
2515        }));
2516        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2517        assert_eq!(v["pages"]["1"]["page_no"], 1);
2518        assert_eq!(v["pages"]["1"]["size"]["width"], 512.0);
2519        assert_eq!(v["pages"]["1"]["size"]["height"], 1024.0);
2520        // 512-wide page: grid x scales 1:1; 1024-high: grid y doubles, then
2521        // flips to the BOTTOMLEFT origin (t from grid-top 64 → 1024-128=896).
2522        let prov = &v["texts"][0]["prov"][0];
2523        assert_eq!(prov["page_no"], 1);
2524        assert_eq!(prov["bbox"]["l"], 128.0);
2525        assert_eq!(prov["bbox"]["t"], 896.0);
2526        assert_eq!(prov["bbox"]["r"], 256.0);
2527        assert_eq!(prov["bbox"]["b"], 768.0);
2528        assert_eq!(prov["bbox"]["coord_origin"], "BOTTOMLEFT");
2529        assert_eq!(prov["charspan"][1], 5);
2530        // The table adopts its own location field; charspan is [0, 0].
2531        let tprov = &v["tables"][0]["prov"][0];
2532        assert_eq!(tprov["bbox"]["t"], 1024.0);
2533        assert_eq!(tprov["bbox"]["b"], 0.0);
2534        assert_eq!(tprov["charspan"][1], 0);
2535
2536        // No markers → the pre-#171 shape, byte for byte.
2537        let mut plain = DoclingDocument::new("t");
2538        plain.push(Node::Located {
2539            location: [1, 2, 3, 4],
2540            inner: Box::new(Node::Paragraph { text: "x".into() }),
2541        });
2542        let v: Value = serde_json::from_str(&plain.export_to_json()).unwrap();
2543        assert_eq!(v["pages"], serde_json::json!({}));
2544        assert_eq!(v["texts"][0]["prov"], serde_json::json!([]));
2545    }
2546
2547    /// PDF page headers/footers reach the JSON as docling writes them:
2548    /// body-parented text items on the furniture layer, with their box.
2549    #[test]
2550    fn page_furniture_becomes_furniture_layer_text() {
2551        let mut doc = DoclingDocument::new("t");
2552        doc.push(Node::PageInfo {
2553            page_no: 1,
2554            width: 512.0,
2555            height: 512.0,
2556        });
2557        doc.push(Node::PageFurniture {
2558            footer: false,
2559            location: [10, 0, 100, 20],
2560            text: "Chapter 1".into(),
2561        });
2562        doc.push(Node::Paragraph {
2563            text: "body".into(),
2564        });
2565        doc.push(Node::PageFurniture {
2566            footer: true,
2567            location: [400, 490, 500, 512],
2568            text: "1.10.2".into(),
2569        });
2570        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2571        let texts = v["texts"].as_array().unwrap();
2572        assert_eq!(texts.len(), 3);
2573        assert_eq!(texts[0]["label"], "page_header");
2574        assert_eq!(texts[0]["content_layer"], "furniture");
2575        assert_eq!(texts[0]["parent"]["$ref"], "#/body");
2576        assert_eq!(texts[0]["prov"][0]["bbox"]["l"], 10.0);
2577        assert_eq!(texts[1]["content_layer"], "body");
2578        assert_eq!(texts[1]["prov"], serde_json::json!([]));
2579        assert_eq!(texts[2]["label"], "page_footer");
2580        assert_eq!(texts[2]["text"], "1.10.2");
2581        assert_eq!(texts[2]["content_layer"], "furniture");
2582    }
2583
2584    #[test]
2585    fn picture_image_in_markdown_modes_and_json() {
2586        let doc = doc_with_image();
2587        // placeholder (default) ignores the image
2588        assert!(doc.export_to_markdown().contains("<!-- image -->"));
2589        // embedded → base64 data URI (b"foobar" → "Zm9vYmFy")
2590        let (md, files) = doc.export_to_markdown_with_images(ImageMode::Embedded, "artifacts");
2591        assert!(
2592            md.contains("![Image](data:image/png;base64,Zm9vYmFy)"),
2593            "got:\n{md}"
2594        );
2595        assert!(files.is_empty());
2596        // referenced → file link + collected bytes
2597        let (md, files) = doc.export_to_markdown_with_images(ImageMode::Referenced, "artifacts");
2598        assert!(
2599            md.contains("![Image](artifacts/image_000000.png)"),
2600            "got:\n{md}"
2601        );
2602        assert_eq!(
2603            files,
2604            vec![("artifacts/image_000000.png".to_string(), b"foobar".to_vec())]
2605        );
2606        // JSON carries the ImageRef (data URI + size — floats, as docling's
2607        // `Size` is — placed before `annotations`).
2608        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2609        assert_eq!(v["pictures"][0]["image"]["mimetype"], "image/png");
2610        assert_eq!(v["pictures"][0]["image"]["size"]["width"], 4.0);
2611        let keys: Vec<&str> = v["pictures"][0]
2612            .as_object()
2613            .unwrap()
2614            .keys()
2615            .map(String::as_str)
2616            .collect();
2617        assert_eq!(&keys[keys.len() - 2..], ["image", "annotations"]);
2618        assert_eq!(
2619            v["pictures"][0]["image"]["uri"],
2620            "data:image/png;base64,Zm9vYmFy"
2621        );
2622    }
2623
2624    #[test]
2625    fn exports_docling_schema() {
2626        let mut doc = DoclingDocument::new("t");
2627        doc.push(Node::Heading {
2628            level: 1,
2629            text: "Title".into(),
2630        });
2631        doc.push(Node::Heading {
2632            level: 2,
2633            text: "Sec".into(),
2634        });
2635        doc.push(Node::Paragraph {
2636            text: "Body &amp; more".into(),
2637        }); // markdown-escaped
2638        doc.push(Node::ListItem {
2639            ordered: false,
2640            number: 0,
2641            first_in_list: true,
2642            text: "one".into(),
2643            level: 0,
2644            marker: None,
2645            location: None,
2646            dclx: None,
2647            href: None,
2648            layer: None,
2649        });
2650        doc.push(Node::ListItem {
2651            ordered: false,
2652            number: 0,
2653            first_in_list: false,
2654            text: "two".into(),
2655            level: 0,
2656            marker: None,
2657            location: None,
2658            dclx: None,
2659            href: None,
2660            layer: None,
2661        });
2662        doc.push(Node::Table(Table {
2663            rows: vec![vec!["A".into(), "B".into()]],
2664            location: None,
2665            structure: None,
2666            cell_blocks: None,
2667            cells: None,
2668            caption: None,
2669            caption_parent: Default::default(),
2670            caption_location: None,
2671        }));
2672
2673        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2674        assert_eq!(v["schema_name"], "DoclingDocument");
2675        assert_eq!(v["version"], "1.10.0");
2676        assert_eq!(v["texts"][0]["label"], "title");
2677        assert_eq!(v["texts"][1]["label"], "section_header");
2678        assert_eq!(v["texts"][1]["level"], 1); // heading level 2 → docling level 1
2679        assert_eq!(v["texts"][2]["text"], "Body & more"); // un-escaped for the wire format
2680                                                          // consecutive list items fold into one list group, parented to it
2681        assert_eq!(v["groups"][0]["label"], "list");
2682        assert_eq!(v["groups"][0]["children"].as_array().unwrap().len(), 2);
2683        assert_eq!(v["texts"][3]["parent"]["$ref"], "#/groups/0");
2684        assert_eq!(v["texts"][3]["marker"], "-");
2685        // table grid + header flag
2686        assert_eq!(v["tables"][0]["data"]["num_cols"], 2);
2687        assert_eq!(v["tables"][0]["data"]["grid"][0][0]["column_header"], true);
2688    }
2689    /// A named group on a non-body layer — docling's hidden spreadsheet sheet:
2690    /// the group carries the sheet's name and the `invisible` layer, and every
2691    /// item inside it carries the layer too.
2692    #[test]
2693    fn a_layered_group_stamps_its_whole_subtree() {
2694        let doc = DoclingDocument {
2695            name: "s".into(),
2696            nodes: vec![
2697                Node::Group {
2698                    label: "sheet".into(),
2699                    name: Some("Sheet1".into()),
2700                    layer: None,
2701                    children: vec![Node::Paragraph {
2702                        text: "visible".into(),
2703                    }],
2704                },
2705                Node::Group {
2706                    label: "sheet".into(),
2707                    name: Some("Sheet2".into()),
2708                    layer: Some(ContentLayer::Invisible),
2709                    children: vec![Node::Paragraph {
2710                        text: "hidden".into(),
2711                    }],
2712                },
2713            ],
2714            ..DoclingDocument::new("s")
2715        };
2716        let v = crate::json::to_json(&doc);
2717        assert_eq!(v["groups"][0]["label"], "sheet");
2718        assert_eq!(v["groups"][0]["name"], "Sheet1");
2719        assert_eq!(v["groups"][0]["content_layer"], "body");
2720        assert_eq!(v["texts"][0]["content_layer"], "body");
2721        assert_eq!(v["groups"][1]["name"], "Sheet2");
2722        assert_eq!(v["groups"][1]["content_layer"], "invisible");
2723        assert_eq!(v["texts"][1]["content_layer"], "invisible");
2724        // The group's children are the items, and the body holds the groups.
2725        assert_eq!(v["groups"][1]["children"][0]["$ref"], "#/texts/1");
2726        assert_eq!(v["body"]["children"][1]["$ref"], "#/groups/1");
2727    }
2728
2729    /// A backend-built item tree is serialized as it is: items numbered in
2730    /// creation order per bucket (a field region's part texts included), the
2731    /// tree's parents / children / layers, docling's field order for
2732    /// `formatting`, `hyperlink`, `level`, `enumerated`/`marker`, a rich
2733    /// cell's `ref` on `table_cells` only, raw cell text.
2734    /// The DOCX tree's extras: an item `delete`d (docling's `delete_items`,
2735    /// the spacer between two items of a resumed list) is neither written nor
2736    /// numbered, `comments` back-refs sit between `prov` and `orig`, and a
2737    /// chart picture carries `classification` plus `tabular_chart`.
2738    #[test]
2739    fn deleted_items_comment_refs_and_chart_meta_in_the_tree() {
2740        use crate::tree::{ItemTree, TreeKind};
2741        let mut t = ItemTree::default();
2742        let text = |txt: &str| TreeKind::Text {
2743            label: "text".into(),
2744            text: txt.into(),
2745            orig: None,
2746            formatting: None,
2747            hyperlink: None,
2748            level: None,
2749            list: None,
2750        };
2751        let a = t.add(None, None, text("a"));
2752        let blank = t.add(None, None, text(""));
2753        let b = t.add(None, None, text("b"));
2754        t.delete(blank);
2755        let group = t.add(
2756            None,
2757            Some(ContentLayer::Notes),
2758            TreeKind::Group {
2759                label: "comment_section".into(),
2760                name: "comment-0".into(),
2761            },
2762        );
2763        t.add(Some(group), Some(ContentLayer::Notes), text("note"));
2764        t.items[a].comments.push(group);
2765        t.add(
2766            None,
2767            None,
2768            TreeKind::Picture {
2769                captions: Vec::new(),
2770                image: None,
2771                classification: Some("bar_chart".into()),
2772                confidence: None,
2773                chart: Some(Table {
2774                    rows: vec![vec!["".into(), "s".into()], vec!["c".into(), "1".into()]],
2775                    ..Table::default()
2776                }),
2777                dpi: None,
2778            },
2779        );
2780        assert_eq!(t.last_text(), Some(4), "the note; the blank is skipped");
2781        assert_eq!(t.bucket_index(b), 1, "numbered past the deleted item");
2782        let mut doc = DoclingDocument::new("t");
2783        doc.tree = Some(t);
2784        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2785        let texts = v["texts"].as_array().unwrap();
2786        assert_eq!(texts.len(), 3);
2787        assert_eq!(texts[1]["text"], "b");
2788        assert_eq!(texts[1]["self_ref"], "#/texts/1");
2789        assert_eq!(
2790            v["body"]["children"],
2791            serde_json::json!([{"$ref": "#/texts/0"}, {"$ref": "#/texts/1"}, {"$ref": "#/groups/0"}, {"$ref": "#/pictures/0"}])
2792        );
2793        let keys: Vec<&str> = texts[0]
2794            .as_object()
2795            .unwrap()
2796            .keys()
2797            .map(String::as_str)
2798            .collect();
2799        assert_eq!(
2800            keys,
2801            vec![
2802                "self_ref",
2803                "parent",
2804                "children",
2805                "content_layer",
2806                "label",
2807                "prov",
2808                "comments",
2809                "orig",
2810                "text"
2811            ]
2812        );
2813        assert_eq!(
2814            texts[0]["comments"],
2815            serde_json::json!([{"$ref": "#/groups/0"}])
2816        );
2817        assert!(texts[1].get("comments").is_none());
2818        let meta = &v["pictures"][0]["meta"];
2819        assert_eq!(
2820            meta["classification"]["predictions"][0]["class_name"],
2821            "bar_chart"
2822        );
2823        assert_eq!(meta["tabular_chart"]["chart_data"]["num_rows"], 2);
2824    }
2825
2826    /// A tree item's `TreeProv` is written verbatim — a raw EMU box with
2827    /// whatever origin tag the backend set (`BOTTOMLEFT` here) and a per-item
2828    /// charspan, a note's zero `TOPLEFT` box — a picture's `image.dpi` is the file's when the backend
2829    /// read one, an item without provenance writes `prov: []`, and the page
2830    /// map still comes from the flat stream's markers.
2831    #[test]
2832    fn tree_items_carry_exact_provenance_and_dpi() {
2833        use crate::tree::{ItemTree, TreeKind, TreeProv};
2834        let text = |label: &str, t: &str| TreeKind::Text {
2835            label: label.into(),
2836            text: t.into(),
2837            orig: None,
2838            formatting: None,
2839            hyperlink: None,
2840            level: None,
2841            list: None,
2842        };
2843        let mut t = ItemTree::default();
2844        let slide = t.add(
2845            None,
2846            None,
2847            TreeKind::Group {
2848                label: "chapter".into(),
2849                name: "slide-0".into(),
2850            },
2851        );
2852        t.add_with_prov(
2853            Some(slide),
2854            None,
2855            text("paragraph", "héllo"),
2856            TreeProv {
2857                page_no: 1,
2858                bbox: [914400.0, 1828800.0, 2743200.0, 457200.0],
2859                bottom_left: true,
2860                charspan: [0, 5],
2861            },
2862        );
2863        t.add_with_prov(
2864            Some(slide),
2865            None,
2866            TreeKind::Picture {
2867                captions: Vec::new(),
2868                image: Some(crate::PictureImage {
2869                    dpi: crate::PictureImage::DEFAULT_DPI,
2870                    mimetype: "image/png".into(),
2871                    width: 2,
2872                    height: 2,
2873                    data: vec![0],
2874                }),
2875                classification: None,
2876                confidence: None,
2877                chart: None,
2878                dpi: Some(300),
2879            },
2880            TreeProv {
2881                page_no: 1,
2882                bbox: [0.0; 4],
2883                bottom_left: false,
2884                charspan: [0, 0],
2885            },
2886        );
2887        t.add(
2888            Some(slide),
2889            Some(ContentLayer::Notes),
2890            text("text", "no geometry"),
2891        );
2892        let mut doc = DoclingDocument::new("t");
2893        doc.push(Node::PageInfo {
2894            page_no: 1,
2895            width: 9144000.0,
2896            height: 6858000.0,
2897        });
2898        doc.tree = Some(t);
2899        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2900        assert_eq!(
2901            v["texts"][0]["prov"],
2902            serde_json::json!([{
2903                "page_no": 1,
2904                "bbox": { "l": 914400.0, "t": 1828800.0, "r": 2743200.0, "b": 457200.0, "coord_origin": "BOTTOMLEFT" },
2905                "charspan": [0, 5],
2906            }])
2907        );
2908        assert_eq!(v["texts"][0]["label"], "paragraph");
2909        assert_eq!(
2910            v["pictures"][0]["prov"][0]["bbox"]["coord_origin"],
2911            "TOPLEFT"
2912        );
2913        assert_eq!(v["pictures"][0]["image"]["dpi"], 300);
2914        assert_eq!(v["texts"][1]["prov"], serde_json::json!([]));
2915        assert_eq!(v["texts"][1]["content_layer"], "notes");
2916        assert_eq!(v["pages"]["1"]["size"]["width"], 9144000.0);
2917        assert_eq!(v["pages"]["1"]["page_no"], 1);
2918    }
2919
2920    /// docling-core's `validate_document` clamps every provenance box (and a
2921    /// one-page table's cell boxes) into its page — the state every
2922    /// `ConversionResult` leaves a document in, so the state docling's JSON
2923    /// shows. A box on a page the document does not describe is left alone.
2924    #[test]
2925    fn provenance_boxes_are_clamped_to_their_page() {
2926        let mut doc = DoclingDocument::new("t");
2927        doc.push(Node::PageInfo {
2928            page_no: 1,
2929            width: 10.0,
2930            height: 8.0,
2931        });
2932        doc.push(Node::Prov {
2933            page_no: 1,
2934            bbox: [-1.0, 2.0, 12.0, 9.5],
2935            charspan: [0, 1],
2936            seq: None,
2937            inner: Box::new(Node::Paragraph { text: "x".into() }),
2938        });
2939        let mut table = Table {
2940            rows: vec![vec!["a".into()]],
2941            ..Table::default()
2942        };
2943        table.cells = Some(vec![crate::TableCell {
2944            text: "a".into(),
2945            bbox: Some([1.0, 1.0, 11.0, 9.0]),
2946            start_row: 0,
2947            start_col: 0,
2948            row_span: 1,
2949            col_span: 1,
2950            column_header: false,
2951            row_header: false,
2952            row_section: false,
2953        }]);
2954        doc.push(Node::Prov {
2955            page_no: 1,
2956            bbox: [0.0, 0.0, 10.0, 8.0],
2957            charspan: [0, 0],
2958            seq: None,
2959            inner: Box::new(Node::Table(table)),
2960        });
2961        doc.push(Node::Prov {
2962            page_no: 7,
2963            bbox: [-5.0, 0.0, 50.0, 50.0],
2964            charspan: [0, 1],
2965            seq: None,
2966            inner: Box::new(Node::Paragraph { text: "y".into() }),
2967        });
2968        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2969        assert_eq!(
2970            v["texts"][0]["prov"][0]["bbox"],
2971            serde_json::json!({ "l": 0.0, "t": 2.0, "r": 10.0, "b": 8.0, "coord_origin": "TOPLEFT" })
2972        );
2973        let cell = &v["tables"][0]["data"]["table_cells"][0]["bbox"];
2974        assert_eq!(
2975            (cell["l"].as_f64(), cell["r"].as_f64(), cell["b"].as_f64()),
2976            (Some(1.0), Some(10.0), Some(8.0))
2977        );
2978        assert_eq!(v["tables"][0]["data"]["grid"][0][0]["bbox"]["r"], 10.0);
2979        assert_eq!(
2980            v["texts"][1]["prov"][0]["bbox"]["r"], 50.0,
2981            "page 7 is not described"
2982        );
2983    }
2984
2985    /// docling-core's `validate_misplaced_list_items`, as it re-homes list
2986    /// items outside a `list` group (#527) — the refs below are what
2987    /// docling-core 2.99 writes for the same document: the two consecutive
2988    /// items on the body share a group, each item in another group gets its
2989    /// own, the runs are handled last-first (new groups and re-added texts
2990    /// numbered in that order), and a well-placed item is left alone.
2991    #[test]
2992    fn misplaced_list_items_are_wrapped_like_docling_core() {
2993        use crate::tree::{ItemTree, ListMeta, TreeKind};
2994        let mut t = ItemTree::default();
2995        let li = |txt: &str| TreeKind::Text {
2996            label: "list_item".into(),
2997            text: txt.into(),
2998            orig: None,
2999            formatting: None,
3000            hyperlink: None,
3001            level: None,
3002            list: Some(ListMeta {
3003                enumerated: false,
3004                marker: "-".into(),
3005            }),
3006        };
3007        let group = |label: &str, name: &str| TreeKind::Group {
3008            label: label.into(),
3009            name: name.into(),
3010        };
3011        t.add(None, None, li("A"));
3012        t.add(None, None, li("B"));
3013        t.add(
3014            None,
3015            None,
3016            TreeKind::Text {
3017                label: "text".into(),
3018                text: "plain".into(),
3019                orig: None,
3020                formatting: None,
3021                hyperlink: None,
3022                level: None,
3023                list: None,
3024            },
3025        );
3026        let cell = t.add(None, None, group("unspecified", "cell"));
3027        t.add(Some(cell), None, li("C"));
3028        t.add(Some(cell), None, li("D"));
3029        let list = t.add(None, None, group("list", "list"));
3030        t.add(Some(list), None, li("E"));
3031        let doc = DoclingDocument {
3032            tree: Some(t),
3033            ..DoclingDocument::new("t")
3034        };
3035        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
3036        let refs = |x: &Value| -> Vec<String> {
3037            x.as_array()
3038                .unwrap()
3039                .iter()
3040                .map(|r| r["$ref"].as_str().unwrap().to_string())
3041                .collect()
3042        };
3043        assert_eq!(
3044            refs(&v["body"]["children"]),
3045            ["#/groups/4", "#/texts/0", "#/groups/0", "#/groups/1"]
3046        );
3047        assert_eq!(
3048            refs(&v["groups"][0]["children"]),
3049            ["#/groups/3", "#/groups/2"]
3050        );
3051        for (g, name, kids) in [
3052            (2, "group", vec!["#/texts/2"]),
3053            (3, "group", vec!["#/texts/3"]),
3054            (4, "group", vec!["#/texts/4", "#/texts/5"]),
3055            (1, "list", vec!["#/texts/1"]),
3056        ] {
3057            assert_eq!(v["groups"][g]["label"], "list");
3058            assert_eq!(v["groups"][g]["name"], name);
3059            assert_eq!(refs(&v["groups"][g]["children"]), kids);
3060        }
3061        let texts: Vec<&str> = v["texts"]
3062            .as_array()
3063            .unwrap()
3064            .iter()
3065            .map(|t| t["text"].as_str().unwrap())
3066            .collect();
3067        assert_eq!(texts, ["plain", "E", "D", "C", "A", "B"]);
3068        assert_eq!(v["texts"][2]["parent"]["$ref"], "#/groups/2");
3069    }
3070
3071    /// A child the tree still lists after deleting it is left out instead
3072    /// of written as `"$ref": ""`, which docling-core rejects (#527).
3073    #[test]
3074    fn a_deleted_child_is_not_written_as_an_empty_ref() {
3075        use crate::tree::{ItemTree, TreeKind};
3076        let mut t = ItemTree::default();
3077        let text = |txt: &str| TreeKind::Text {
3078            label: "text".into(),
3079            text: txt.into(),
3080            orig: None,
3081            formatting: None,
3082            hyperlink: None,
3083            level: None,
3084            list: None,
3085        };
3086        let g = t.add(
3087            None,
3088            None,
3089            TreeKind::Group {
3090                label: "unspecified".into(),
3091                name: "g".into(),
3092            },
3093        );
3094        let gone = t.add(Some(g), None, text(""));
3095        t.add(Some(g), None, text("kept"));
3096        t.items[gone].deleted = true; // still in `g`'s children
3097        let doc = DoclingDocument {
3098            tree: Some(t),
3099            ..DoclingDocument::new("t")
3100        };
3101        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
3102        assert_eq!(
3103            v["groups"][0]["children"],
3104            serde_json::json!([{"$ref": "#/texts/0"}])
3105        );
3106    }
3107
3108    #[test]
3109    fn a_backend_item_tree_is_written_verbatim() {
3110        use crate::tree::{Formatting, ItemTree, ListMeta, TreeKind};
3111        let mut t = ItemTree::default();
3112        let text = |label: &str, txt: &str| TreeKind::Text {
3113            label: label.into(),
3114            text: txt.into(),
3115            orig: None,
3116            formatting: None,
3117            hyperlink: None,
3118            level: None,
3119            list: None,
3120        };
3121        let title = t.add(None, Some(ContentLayer::Furniture), text("title", "Page"));
3122        let h = t.add(None, None, text("title", "Heading"));
3123        let group = t.add(
3124            Some(h),
3125            None,
3126            TreeKind::Group {
3127                label: "inline".into(),
3128                name: "group".into(),
3129            },
3130        );
3131        t.add(
3132            Some(group),
3133            None,
3134            TreeKind::Text {
3135                label: "text".into(),
3136                text: "bold".into(),
3137                orig: None,
3138                formatting: Some(Formatting {
3139                    bold: true,
3140                    ..Formatting::default()
3141                }),
3142                hyperlink: Some("https://example.com/".into()),
3143                level: None,
3144                list: None,
3145            },
3146        );
3147        t.add(
3148            Some(group),
3149            None,
3150            TreeKind::Code {
3151                text: "x = 1".into(),
3152                orig: None,
3153                language: Some("python".into()),
3154                formatting: None,
3155                hyperlink: None,
3156            },
3157        );
3158        let sub = t.add(
3159            Some(h),
3160            None,
3161            TreeKind::Text {
3162                label: "section_header".into(),
3163                text: "Sub".into(),
3164                orig: Some("Sub\u{2019}".into()),
3165                formatting: None,
3166                hyperlink: None,
3167                level: Some(1),
3168                list: None,
3169            },
3170        );
3171        let item = t.add(
3172            Some(sub),
3173            None,
3174            TreeKind::Text {
3175                label: "list_item".into(),
3176                text: "item".into(),
3177                orig: None,
3178                formatting: None,
3179                hyperlink: None,
3180                level: None,
3181                list: Some(ListMeta {
3182                    enumerated: true,
3183                    marker: "3.".into(),
3184                }),
3185            },
3186        );
3187        let _region = t.add(
3188            Some(sub),
3189            None,
3190            TreeKind::FieldRegion {
3191                items: vec![crate::FieldItem {
3192                    marker: None,
3193                    key: Some("Name".into()),
3194                    value: Some("Duck".into()),
3195                    value_kind: Some("read_only".into()),
3196                }],
3197            },
3198        );
3199        let table = t.add(
3200            Some(sub),
3201            None,
3202            TreeKind::Table {
3203                table: Table {
3204                    rows: vec![vec!["a  \n&lt;".into(), "b".into()]],
3205                    cells: Some(vec![
3206                        crate::TableCell {
3207                            text: "a  \n&lt;".into(),
3208                            bbox: None,
3209                            start_row: 0,
3210                            start_col: 0,
3211                            row_span: 3,
3212                            col_span: 1,
3213                            column_header: false,
3214                            row_header: true,
3215                            row_section: false,
3216                        },
3217                        crate::TableCell {
3218                            text: "b".into(),
3219                            bbox: None,
3220                            start_row: 0,
3221                            start_col: 1,
3222                            row_span: 1,
3223                            col_span: 1,
3224                            column_header: false,
3225                            row_header: false,
3226                            row_section: false,
3227                        },
3228                    ]),
3229                    ..Table::default()
3230                },
3231                rich_cells: vec![(0, 1, 0)], // patched below
3232                captions: Vec::new(),
3233            },
3234        );
3235        let cell_group = t.add(
3236            Some(table),
3237            None,
3238            TreeKind::Group {
3239                label: "unspecified".into(),
3240                name: "rich_cell_group_1_0_0".into(),
3241            },
3242        );
3243        if let TreeKind::Table { rich_cells, .. } = &mut t.items[table].kind {
3244            *rich_cells = vec![(0, 1, cell_group)];
3245        }
3246        let after = t.add(Some(sub), None, text("text", "after the region"));
3247        let _ = (title, after);
3248        // A list item belongs in a `list` group — one outside it would be
3249        // re-homed by `wrap_misplaced_list_items` (created last, so the
3250        // other groups keep their numbers).
3251        let list = t.add(
3252            Some(sub),
3253            None,
3254            TreeKind::Group {
3255                label: "list".into(),
3256                name: "list".into(),
3257            },
3258        );
3259        t.reparent(item, Some(list));
3260
3261        let doc = DoclingDocument {
3262            tree: Some(t),
3263            ..DoclingDocument::new("t")
3264        };
3265        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
3266        // Creation order: Page, Heading, bold, x = 1, Sub, item, [Name, Duck], after.
3267        let texts: Vec<&str> = v["texts"]
3268            .as_array()
3269            .unwrap()
3270            .iter()
3271            .map(|t| t["text"].as_str().unwrap())
3272            .collect();
3273        assert_eq!(
3274            texts,
3275            [
3276                "Page",
3277                "Heading",
3278                "bold",
3279                "x = 1",
3280                "Sub",
3281                "item",
3282                "Name",
3283                "Duck",
3284                "after the region"
3285            ]
3286        );
3287        assert_eq!(
3288            v["body"]["children"],
3289            serde_json::json!([{"$ref": "#/texts/0"}, {"$ref": "#/texts/1"}])
3290        );
3291        assert_eq!(v["texts"][0]["content_layer"], "furniture");
3292        assert_eq!(
3293            v["texts"][1]["children"],
3294            serde_json::json!([{"$ref": "#/groups/0"}, {"$ref": "#/texts/4"}])
3295        );
3296        let bold = &v["texts"][2];
3297        assert_eq!(bold["parent"]["$ref"], "#/groups/0");
3298        let keys: Vec<&str> = bold
3299            .as_object()
3300            .unwrap()
3301            .keys()
3302            .map(String::as_str)
3303            .collect();
3304        assert_eq!(
3305            keys,
3306            [
3307                "self_ref",
3308                "parent",
3309                "children",
3310                "content_layer",
3311                "label",
3312                "prov",
3313                "orig",
3314                "text",
3315                "formatting",
3316                "hyperlink"
3317            ]
3318        );
3319        assert_eq!(
3320            bold["formatting"],
3321            serde_json::json!({"bold": true, "italic": false, "underline": false, "strikethrough": false, "script": "baseline"})
3322        );
3323        let code = &v["texts"][3];
3324        assert_eq!(code["label"], "code");
3325        assert_eq!(code["code_language"], "Python");
3326        let sub = &v["texts"][4];
3327        assert_eq!(sub["orig"], "Sub\u{2019}");
3328        assert_eq!(sub["level"], 1);
3329        let item = &v["texts"][5];
3330        let keys: Vec<&str> = item
3331            .as_object()
3332            .unwrap()
3333            .keys()
3334            .map(String::as_str)
3335            .collect();
3336        assert_eq!(
3337            keys,
3338            [
3339                "self_ref",
3340                "parent",
3341                "children",
3342                "content_layer",
3343                "label",
3344                "prov",
3345                "orig",
3346                "text",
3347                "enumerated",
3348                "marker"
3349            ]
3350        );
3351        assert_eq!(item["marker"], "3.");
3352        assert_eq!(v["texts"][7]["kind"], "read_only");
3353        assert_eq!(v["field_regions"][0]["parent"]["$ref"], "#/texts/4");
3354        let table = &v["tables"][0];
3355        assert_eq!(
3356            table["children"],
3357            serde_json::json!([{"$ref": "#/groups/1"}])
3358        );
3359        let cells = table["data"]["table_cells"].as_array().unwrap();
3360        assert_eq!(
3361            cells[0]["text"], "a  \n&lt;",
3362            "raw cell text is written verbatim"
3363        );
3364        assert_eq!(
3365            cells[0]["end_row_offset_idx"], 3,
3366            "declared spans are not clamped"
3367        );
3368        assert_eq!(cells[1]["ref"], serde_json::json!({"$ref": "#/groups/1"}));
3369        assert!(cells[0].get("ref").is_none());
3370        assert!(
3371            table["data"]["grid"][0][1].get("ref").is_none(),
3372            "the grid shows plain cells"
3373        );
3374        assert_eq!(v["groups"][1]["name"], "rich_cell_group_1_0_0");
3375    }
3376
3377    /// A comment section that links its note text rather than its group — the
3378    /// spreadsheet shape, where docling-core's `add_comment` appends the text
3379    /// item's ref to each target.
3380    #[test]
3381    fn a_comment_section_can_be_referenced_by_its_note_text() {
3382        let doc = DoclingDocument {
3383            name: "c".into(),
3384            nodes: vec![
3385                Node::Commented {
3386                    comments: vec![0],
3387                    inner: Box::new(Node::Paragraph {
3388                        text: "annotated".into(),
3389                    }),
3390                },
3391                Node::CommentSection {
3392                    name: "comment-Sheet1-A1".into(),
3393                    text: "[author: A]: note".into(),
3394                    refs_note_text: true,
3395                    grouped: true,
3396                },
3397            ],
3398            ..DoclingDocument::new("c")
3399        };
3400        let v = crate::json::to_json(&doc);
3401        assert_eq!(v["groups"][0]["name"], "comment-Sheet1-A1");
3402        assert_eq!(v["texts"][0]["comments"][0]["$ref"], "#/texts/1");
3403    }
3404
3405    /// docx reviewer comments: a `comment_section` group on the notes layer
3406    /// holding the note text, and a `comments` back-ref on the annotated item —
3407    /// keyed between `prov` and `orig`, the slot docling emits it in.
3408    #[test]
3409    fn comment_sections_link_back_to_their_items() {
3410        let doc = DoclingDocument {
3411            name: "c".into(),
3412            nodes: vec![
3413                Node::Commented {
3414                    comments: vec![0],
3415                    inner: Box::new(Node::Paragraph {
3416                        text: "annotated".into(),
3417                    }),
3418                },
3419                Node::Paragraph {
3420                    text: "plain".into(),
3421                },
3422                Node::CommentSection {
3423                    name: "comment-7".into(),
3424                    text: "[time: t]: note".into(),
3425                    refs_note_text: false,
3426                    grouped: true,
3427                },
3428            ],
3429            ..DoclingDocument::new("c")
3430        };
3431        let v = crate::json::to_json(&doc);
3432        // The group is the comment section; its only child is the notes text.
3433        assert_eq!(v["groups"][0]["label"], "comment_section");
3434        assert_eq!(v["groups"][0]["name"], "comment-7");
3435        assert_eq!(v["groups"][0]["content_layer"], "notes");
3436        assert_eq!(v["groups"][0]["children"][0]["$ref"], "#/texts/2");
3437        assert_eq!(v["texts"][2]["content_layer"], "notes");
3438        // The annotated item points back at the group; the plain one has no key.
3439        assert_eq!(v["texts"][0]["comments"][0]["$ref"], "#/groups/0");
3440        assert!(v["texts"][1].get("comments").is_none());
3441        // docling's key order: … prov, comments, orig, text.
3442        let keys: Vec<&str> = v["texts"][0]
3443            .as_object()
3444            .unwrap()
3445            .keys()
3446            .map(String::as_str)
3447            .collect();
3448        assert_eq!(
3449            &keys[keys.len() - 4..],
3450            &["prov", "comments", "orig", "text"]
3451        );
3452    }
3453
3454    fn picture(caption: &str, caption_parent: CaptionParent) -> Node {
3455        Node::Picture {
3456            caption: Some(caption.into()),
3457            caption_href: None,
3458            image: None,
3459            classification: None,
3460            caption_parent,
3461            caption_location: None,
3462        }
3463    }
3464
3465    fn group(children: Vec<Node>) -> Node {
3466        Node::Group {
3467            label: "section".into(),
3468            name: None,
3469            layer: None,
3470            children,
3471        }
3472    }
3473
3474    fn refs(v: &Value) -> Vec<&str> {
3475        v.as_array()
3476            .unwrap()
3477            .iter()
3478            .map(|r| r["$ref"].as_str().unwrap())
3479            .collect()
3480    }
3481
3482    /// #390: a declarative backend's caption is docling's `add_text` default —
3483    /// a body child, appended as it is created — wherever the picture sits:
3484    /// ahead of a top-level picture, behind the top-level item enclosing a
3485    /// nested one. The picture references it either way and has no children.
3486    #[test]
3487    fn a_body_caption_follows_the_enclosing_top_level_item() {
3488        let mut doc = DoclingDocument::new("t");
3489        doc.push(picture("top", CaptionParent::Body));
3490        doc.push(group(vec![
3491            Node::Paragraph { text: "p".into() },
3492            picture("nested", CaptionParent::Body),
3493        ]));
3494        doc.push(Node::Paragraph {
3495            text: "after".into(),
3496        });
3497        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
3498        assert_eq!(
3499            refs(&v["body"]["children"]),
3500            [
3501                "#/texts/0",
3502                "#/pictures/0",
3503                "#/groups/0",
3504                "#/texts/2",
3505                "#/texts/3"
3506            ]
3507        );
3508        assert_eq!(
3509            refs(&v["groups"][0]["children"]),
3510            ["#/texts/1", "#/pictures/1"]
3511        );
3512        for (cap, pic) in [(0, 0), (2, 1)] {
3513            assert_eq!(v["texts"][cap]["label"], "caption");
3514            assert_eq!(v["texts"][cap]["parent"]["$ref"], "#/body");
3515            assert_eq!(
3516                refs(&v["pictures"][pic]["captions"]),
3517                [format!("#/texts/{cap}")]
3518            );
3519            assert_eq!(v["pictures"][pic]["children"], serde_json::json!([]));
3520        }
3521    }
3522
3523    /// The PDF pipeline's caption is the picture's (or table's) own child,
3524    /// as docling attaches a layout caption.
3525    #[test]
3526    fn an_item_caption_is_the_items_first_child() {
3527        let mut doc = DoclingDocument::new("t");
3528        doc.push(picture("fig", CaptionParent::Item));
3529        doc.push(Node::Table(Table {
3530            rows: vec![vec!["a".into()]],
3531            caption: Some("tab".into()),
3532            caption_parent: CaptionParent::Item,
3533            ..Table::default()
3534        }));
3535        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
3536        assert_eq!(refs(&v["body"]["children"]), ["#/pictures/0", "#/tables/0"]);
3537        assert_eq!(v["texts"][0]["parent"]["$ref"], "#/pictures/0");
3538        assert_eq!(refs(&v["pictures"][0]["children"]), ["#/texts/0"]);
3539        assert_eq!(refs(&v["pictures"][0]["captions"]), ["#/texts/0"]);
3540        assert_eq!(v["texts"][1]["parent"]["$ref"], "#/tables/0");
3541        assert_eq!(refs(&v["tables"][0]["children"]), ["#/texts/1"]);
3542        assert_eq!(refs(&v["tables"][0]["captions"]), ["#/texts/1"]);
3543    }
3544
3545    /// A PDF picture's contained text (`Node::PictureChildren`) is written as
3546    /// docling's `_add_child_elements` writes it: items parented to the
3547    /// picture, after its caption in the picture's `children`, never in the
3548    /// body; a list item opens its own list group under the picture. The
3549    /// Markdown and the chunker's refs are unaffected.
3550    #[test]
3551    fn picture_children_hang_off_the_picture_after_its_caption() {
3552        let mut doc = DoclingDocument::new("t");
3553        doc.push(picture("fig", CaptionParent::Item));
3554        doc.push(Node::PictureChildren(vec![
3555            Node::Heading {
3556                level: 2,
3557                text: "in-figure title".into(),
3558            },
3559            Node::Paragraph {
3560                text: "axis label".into(),
3561            },
3562            Node::ListItem {
3563                ordered: false,
3564                number: 0,
3565                first_in_list: true,
3566                text: "callout".into(),
3567                level: 0,
3568                marker: None,
3569                location: None,
3570                dclx: None,
3571                href: None,
3572                layer: None,
3573            },
3574        ]));
3575        doc.push(Node::Paragraph {
3576            text: "after".into(),
3577        });
3578        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
3579        assert_eq!(refs(&v["body"]["children"]), ["#/pictures/0", "#/texts/4"]);
3580        assert_eq!(
3581            refs(&v["pictures"][0]["children"]),
3582            ["#/texts/0", "#/texts/1", "#/texts/2", "#/groups/0"]
3583        );
3584        assert_eq!(refs(&v["pictures"][0]["captions"]), ["#/texts/0"]);
3585        assert_eq!(v["texts"][1]["label"], "section_header");
3586        assert_eq!(v["texts"][2]["label"], "text");
3587        for t in 1..=2 {
3588            assert_eq!(v["texts"][t]["parent"]["$ref"], "#/pictures/0");
3589            assert_eq!(v["texts"][t]["content_layer"], "body");
3590        }
3591        assert_eq!(v["groups"][0]["parent"]["$ref"], "#/pictures/0");
3592        assert_eq!(v["texts"][3]["parent"]["$ref"], "#/groups/0");
3593        let md = doc.export_to_markdown();
3594        assert!(
3595            !md.contains("axis label") && !md.contains("callout"),
3596            "{md}"
3597        );
3598        assert!(md.contains("after"), "{md}");
3599    }
3600
3601    /// A container caption sits beside its item under the item's parent —
3602    /// ahead of it (an office chart's title) or behind it (an HTML
3603    /// `<figure>`'s table, whose figcaption docling adds after the table).
3604    #[test]
3605    fn a_container_caption_is_the_items_sibling() {
3606        let mut doc = DoclingDocument::new("t");
3607        doc.push(group(vec![
3608            picture("chart", CaptionParent::Container),
3609            Node::Table(Table {
3610                rows: vec![vec!["a".into()]],
3611                caption: Some("figcaption".into()),
3612                caption_parent: CaptionParent::ContainerAfter,
3613                ..Table::default()
3614            }),
3615        ]));
3616        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
3617        assert_eq!(refs(&v["body"]["children"]), ["#/groups/0"]);
3618        assert_eq!(
3619            refs(&v["groups"][0]["children"]),
3620            ["#/texts/0", "#/pictures/0", "#/tables/0", "#/texts/1"]
3621        );
3622        assert_eq!(v["texts"][0]["parent"]["$ref"], "#/groups/0");
3623        assert_eq!(v["texts"][1]["parent"]["$ref"], "#/groups/0");
3624        assert_eq!(v["pictures"][0]["children"], serde_json::json!([]));
3625        assert_eq!(v["tables"][0]["children"], serde_json::json!([]));
3626    }
3627}