Skip to main content

docling_core/
json.rs

1//! Export a [`DoclingDocument`] to docling-core's native JSON wire format
2//! (`DoclingDocument` schema v1.11.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, Map, Value};
12
13use crate::document::{CaptionParent, ContentLayer, DoclingDocument, Node, Table};
14
15const SCHEMA_VERSION: &str = "1.11.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.
87/// The length in characters of a node's Markdown-escaped `text` as the JSON
88/// export writes it (unescaped): the unit of docling's `charspan`. The PDF
89/// assembler counts a joined paragraph's fragments with it (#1127).
90pub fn text_char_len(md: &str) -> usize {
91    unescape_text(md).chars().count()
92}
93
94pub fn code_language_label(lang: &str) -> &'static str {
95    code_language(Some(lang))
96}
97
98pub(crate) fn code_language(lang: Option<&str>) -> &'static str {
99    match lang {
100        Some(l) => CODE_LANGUAGES
101            .iter()
102            .find(|c| c.eq_ignore_ascii_case(l))
103            .copied()
104            .unwrap_or("unknown"),
105        None => "unknown",
106    }
107}
108
109/// An item's exact provenance, written verbatim (see [`Builder::prov_json`]):
110/// a [`Node::Prov`] wrapper's top-left page box, or a tree item's
111/// [`TreeProv`](crate::tree::TreeProv).
112#[derive(Clone, Copy)]
113struct ExactProv {
114    page_no: usize,
115    bbox: [f64; 4],
116    bottom_left: bool,
117    charspan: [usize; 2],
118}
119
120impl From<&crate::tree::TreeProv> for ExactProv {
121    fn from(p: &crate::tree::TreeProv) -> Self {
122        ExactProv {
123            page_no: p.page_no,
124            bbox: p.bbox,
125            bottom_left: p.bottom_left,
126            charspan: p.charspan,
127        }
128    }
129}
130
131/// Page sizes by page number; the first entry per page wins.
132type PageSizes = std::collections::HashMap<usize, (f64, f64)>;
133
134fn page_sizes(pages: &[(usize, f64, f64)]) -> PageSizes {
135    let mut sizes = PageSizes::with_capacity(pages.len());
136    for &(p, w, h) in pages {
137        sizes.entry(p).or_insert((w, h));
138    }
139    sizes
140}
141
142/// docling-core's `_clamp_provenance_bboxes_to_pages`: each `prov` box of
143/// every item on a known page is clamped to `[0, width] × [0, height]`
144/// (whatever its `coord_origin` — docling clamps the stored numbers), and a
145/// table whose provenance sits on one page has its cell boxes clamped too.
146/// Runs over the finished `texts`, `pictures`, `tables` and
147/// `key_value_items` (the form-field buckets are left as built).
148fn clamp_boxes_to_pages(b: &mut Builder) {
149    if b.pages.is_empty() {
150        return;
151    }
152    // A map, not a scan per box: that was items × pages on long documents.
153    let sizes = page_sizes(&b.pages);
154    for item in &mut b.texts {
155        match item {
156            Item::Text(t) => t.prov.clamp(&sizes),
157            Item::Json(v) => {
158                clamp_item(v, &sizes);
159            }
160        }
161    }
162    for item in b.pictures.iter_mut().chain(b.key_value_items.iter_mut()) {
163        clamp_item(item, &sizes);
164    }
165    for t in &mut b.tables {
166        if let Some(size) = clamp_item(&mut t.item, &sizes) {
167            t.data.clamp(size);
168        }
169    }
170}
171
172/// Clamp `item`'s `prov` boxes; returns the size of the page when the item
173/// sits on exactly one known page — a table's cells are clamped to it.
174fn clamp_item(item: &mut Value, sizes: &PageSizes) -> Option<(f64, f64)> {
175    let size = |page_no: &Value| -> Option<(f64, f64)> {
176        let n = page_no.as_u64()? as usize;
177        sizes.get(&n).copied()
178    };
179    let clamp_bbox = |bbox: &mut Value, (w, h): (f64, f64)| {
180        for (key, hi) in [("l", w), ("r", w), ("t", h), ("b", h)] {
181            if let Some(v) = bbox.get(key).and_then(Value::as_f64) {
182                bbox[key] = json!(round2(v.clamp(0.0, hi.max(0.0))));
183            }
184        }
185    };
186    let mut table_page: Option<Option<(f64, f64)>> = None;
187    if let Some(provs) = item.get_mut("prov").and_then(Value::as_array_mut) {
188        let mut page_nos: Vec<u64> = Vec::new();
189        for prov in provs.iter_mut() {
190            if let Some(n) = prov.get("page_no").and_then(Value::as_u64) {
191                page_nos.push(n);
192            }
193            let Some(sz) = prov.get("page_no").and_then(size) else {
194                continue;
195            };
196            if let Some(bbox) = prov.get_mut("bbox") {
197                clamp_bbox(bbox, sz);
198            }
199        }
200        page_nos.sort_unstable();
201        page_nos.dedup();
202        if let [only] = page_nos[..] {
203            table_page = Some(size(&json!(only)));
204        }
205    }
206    table_page.flatten()
207}
208
209/// docling-core's `Formatting` model, every field written.
210fn formatting_json(f: &crate::tree::Formatting) -> Value {
211    json!({
212        "bold": f.bold,
213        "italic": f.italic,
214        "underline": f.underline,
215        "strikethrough": f.strikethrough,
216        "script": match f.script {
217            crate::Script::Baseline => "baseline",
218            crate::Script::Sub => "sub",
219            crate::Script::Super => "super",
220        },
221    })
222}
223
224/// docling's `TrackSource` entry: `kind`, the two offsets, then the optional
225/// `identifier` / `voice` (dropped when `None`, as `exclude_none` does).
226fn track_json(t: &crate::tree::TreeTrack) -> Value {
227    let mut m = serde_json::Map::new();
228    m.insert("kind".into(), json!("track"));
229    m.insert("start_time".into(), json!(t.start_time));
230    m.insert("end_time".into(), json!(t.end_time));
231    if let Some(id) = &t.identifier {
232        m.insert("identifier".into(), json!(id));
233    }
234    if let Some(v) = &t.voice {
235        m.insert("voice".into(), json!(v));
236    }
237    Value::Object(m)
238}
239
240/// docling-core's `ImageRef` (pydantic field order: mimetype, dpi, size —
241/// as floats — uri), with the bytes inlined as a `data:` URI — a PNG, like
242/// `ImageRef.from_pil`'s (`pixel_digest::docling_data_uri`).
243fn image_ref_json(img: &crate::PictureImage) -> Value {
244    let (mimetype, uri) = crate::pixel_digest::docling_data_uri(img);
245    json!({
246        "mimetype": mimetype,
247        "dpi": img.dpi,
248        "size": { "width": img.width as f64, "height": img.height as f64 },
249        "uri": uri,
250    })
251}
252
253/// Build the docling-core JSON object for `doc`.
254pub fn to_json(doc: &DoclingDocument) -> Value {
255    build_parts(doc, false).into_value(None)
256}
257
258/// The key a table's `data` is replaced by in [`to_json_typed_tables`]'s
259/// `Value`: the index of its [`TableData`] beside it.
260pub(crate) const TYPED_TABLE: &str = "_typed_table";
261
262/// [`to_json`] for the serializers that walk the `Value` (HTML, Pandoc,
263/// WebVTT), with each table's `data` left typed (#875): the item carries
264/// `{"_typed_table": i}` and the cells are `tables[i]`, read through
265/// [`table_view`]. As a `Value` a table cost two maps of eleven owned keys
266/// per cell (its `table_cells` record and its `grid` copy) — 2.6 GB of an
267/// HTML export's peak on a 640,000-cell CSV. `note_keys` adds the Pandoc
268/// writer's keys ([`to_json_with_notes`]).
269pub(crate) fn to_json_typed_tables(
270    doc: &DoclingDocument,
271    note_keys: bool,
272) -> (Value, Vec<TableData>) {
273    let mut tables = Vec::new();
274    let value = build_parts(doc, note_keys).into_value(Some(&mut tables));
275    (value, tables)
276}
277
278/// [`to_json`] plus the note calls docling's model cannot express: a text
279/// item calling footnotes carries `"_notes": [[offset, text], …]`, a
280/// footnote item that is such a note's body `"_note_body": true` (#538),
281/// a text item that is a link destination `"_anchors": ["id", …]` (#849),
282/// a heading whose text opens with generated numbering `"_number": "1.2"`
283/// (#850), a run kept as a tracked change `"_revision": {"kind":
284/// "insertion" | "deletion", "author", "date"}` (#851),
285/// a picture's image its displayed size `"_display": [width, height]` in
286/// inches (#834), and the document's `metadata` whether or not the JSON
287/// export was asked for it (#836). The Pandoc writer reads these; nothing
288/// is ever exported with them. The tables stay typed, as in
289/// [`to_json_typed_tables`].
290pub(crate) fn to_json_with_notes(doc: &DoclingDocument) -> (Value, Vec<TableData>) {
291    to_json_typed_tables(doc, true)
292}
293
294fn build_parts(doc: &DoclingDocument, note_keys: bool) -> Parts {
295    let mut b = Builder {
296        note_keys,
297        ..Builder::default()
298    };
299    // A backend that built docling's item tree ([`crate::tree`]) has already
300    // decided every parent, child and creation index; serialize that. The
301    // flat nodes are for the other serializers.
302    let body = match &doc.tree {
303        Some(tree) => {
304            // The page map still comes from the flat stream's markers (a
305            // PPTX slide's EMU size): the tree holds items, not pages.
306            for n in &doc.nodes {
307                if let Node::PageInfo {
308                    page_no,
309                    width,
310                    height,
311                } = n
312                {
313                    if *page_no > 0 {
314                        b.pages.push((*page_no, *width as f64, *height as f64));
315                    }
316                }
317            }
318            // docling-core's `validate_misplaced_list_items` runs on every
319            // document it serializes; apply it the same way (keeping the
320            // items' children, which docling-core drops — #586).
321            let mut tree = tree.clone();
322            // Schema 1.11.0's inline runs own their whitespace (#997); a
323            // backend still building trimmed runs gets the old join back in
324            // the runs, as docling-core migrates a pre-1.11 document on load.
325            if !tree.inline_whitespace {
326                tree.separate_legacy_inline_runs();
327            }
328            tree.wrap_misplaced_list_items();
329            b.write_tree(&tree).into_iter().map(Child::json).collect()
330        }
331        None => b.walk_into(&doc.nodes, "#/body"),
332    };
333    b.link_comments();
334    b.link_script_runs();
335
336    // docling-core's `validate_document` — a pydantic `model_validator` every
337    // `DoclingDocument` passes through when a `ConversionResult` (or a
338    // serializer) is built around it — clamps every provenance box, and a
339    // table's cell boxes, into its page's bounds in place
340    // (`_clamp_provenance_bboxes_to_pages`). The JSON docling writes therefore
341    // carries the clamped boxes: a spreadsheet region whose page was sized
342    // `right − left` × `bottom − top` loses its offset, a slide shape hanging
343    // off the slide edge is cut at it. Reproduce that on the finished items.
344    clamp_boxes_to_pages(&mut b);
345
346    let pages = b
347        .pages
348        .iter()
349        .map(|(n, w, h)| {
350            let r2 = |v: f64| (v * 100.0).round() / 100.0;
351            // docling-core's `PageItem` field order: size, image, page_no
352            // (#520 — the image only when page images were generated).
353            let mut page = serde_json::Map::new();
354            page.insert("size".into(), json!({ "width": r2(*w), "height": r2(*h) }));
355            if let Some(img) = doc.page_images.get(n) {
356                page.insert("image".into(), image_ref_json(img));
357            }
358            page.insert("page_no".into(), json!(n));
359            (n.to_string(), Value::Object(page))
360        })
361        .collect::<serde_json::Map<String, Value>>();
362    // docling only emits `field_regions` / `field_items` when a document has
363    // form fields, and places them just before `pages`.
364    let fields = (!b.field_regions.is_empty()).then_some((b.field_regions, b.field_items));
365    Parts {
366        name: doc.name.clone(),
367        // The Pandoc writer (`note_keys`) always gets the metadata, for
368        // its `meta` (#836); the JSON export only when asked.
369        metadata: (doc.metadata_output.in_json() || note_keys)
370            .then(|| doc.metadata.to_json())
371            .filter(|m| m.as_object().is_some_and(|o| !o.is_empty())),
372        origin: json!({
373            "mimetype": "text/plain",
374            "binary_hash": fnv1a(&doc.name),
375            "filename": doc.name,
376        }),
377        furniture: json!({
378            "self_ref": "#/furniture",
379            "children": [],
380            "content_layer": "furniture",
381            "name": "_root_",
382            "label": "unspecified",
383        }),
384        body,
385        groups: b.groups,
386        texts: b.texts,
387        pictures: b.pictures,
388        tables: b.tables,
389        key_value_items: b.key_value_items,
390        fields,
391        pages,
392    }
393}
394
395/// The finished document, before it is a `Value`: one representation
396/// behind both [`to_json`] (a `Value`) and [`write_json`] (bytes, with no
397/// `Value` ever built — the text items stay compact [`Item`]s throughout).
398/// Both produce the same keys in the same order.
399struct Parts {
400    name: String,
401    /// The document's metadata (#679), after `origin`, only when the
402    /// document's output mode asks for it and there is any.
403    metadata: Option<Value>,
404    origin: Value,
405    furniture: Value,
406    /// The body's `children`; the rest of the body object is fixed.
407    body: Vec<Child>,
408    groups: Vec<Value>,
409    texts: Vec<Item>,
410    pictures: Vec<Value>,
411    tables: Vec<TableItem>,
412    key_value_items: Vec<Value>,
413    /// `field_regions` and `field_items`, present only for a document with
414    /// form fields (non-form documents' JSON has neither key).
415    fields: Option<(Vec<Value>, Vec<Value>)>,
416    pages: serde_json::Map<String, Value>,
417}
418
419impl Parts {
420    /// The document `Value`; with `typed`, the tables' `data` goes there
421    /// instead (see [`to_json_typed_tables`]).
422    fn into_value(self, mut typed: Option<&mut Vec<TableData>>) -> Value {
423        // Moved in, never through `json!`, which would deep-copy each array.
424        let mut out = serde_json::Map::with_capacity(15);
425        out.insert("schema_name".into(), "DoclingDocument".into());
426        out.insert("version".into(), SCHEMA_VERSION.into());
427        out.insert("name".into(), Value::String(self.name));
428        out.insert("origin".into(), self.origin);
429        if let Some(m) = self.metadata {
430            out.insert("metadata".into(), m);
431        }
432        out.insert("furniture".into(), self.furniture);
433        out.insert(
434            "body".into(),
435            object([
436                ("self_ref", "#/body".into()),
437                (
438                    "children",
439                    Value::Array(self.body.into_iter().map(Child::into_value).collect()),
440                ),
441                ("content_layer", "body".into()),
442                ("name", "_root_".into()),
443                ("label", "unspecified".into()),
444            ]),
445        );
446        out.insert("groups".into(), Value::Array(self.groups));
447        out.insert(
448            "texts".into(),
449            Value::Array(
450                self.texts
451                    .into_iter()
452                    .enumerate()
453                    .map(|(i, item)| item.into_value(i))
454                    .collect(),
455            ),
456        );
457        out.insert("pictures".into(), Value::Array(self.pictures));
458        out.insert(
459            "tables".into(),
460            Value::Array(
461                self.tables
462                    .into_iter()
463                    .map(|t| match typed.as_deref_mut() {
464                        Some(store) => {
465                            let TableItem { mut item, data } = t;
466                            if let Some(slot) = item.get_mut("data") {
467                                *slot = object([(TYPED_TABLE, store.len().into())]);
468                            }
469                            store.push(data);
470                            item
471                        }
472                        None => t.into_value(),
473                    })
474                    .collect(),
475            ),
476        );
477        out.insert("key_value_items".into(), Value::Array(self.key_value_items));
478        out.insert("form_items".into(), Value::Array(Vec::new()));
479        if let Some((regions, items)) = self.fields {
480            out.insert("field_regions".into(), Value::Array(regions));
481            out.insert("field_items".into(), Value::Array(items));
482        }
483        out.insert("pages".into(), Value::Object(self.pages));
484        Value::Object(out)
485    }
486}
487
488/// [`Parts`] with `extras` — top-level keys a caller appends after
489/// `pages`, as inserting them into [`to_json`]'s `Value` would.
490struct PartsWith<'a>(&'a Parts, &'a [(&'a str, &'a Value)]);
491
492impl serde::Serialize for PartsWith<'_> {
493    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
494        use serde::ser::SerializeMap;
495        let PartsWith(parts, extras) = *self;
496        let mut m = s.serialize_map(Some(
497            13 + 2 * usize::from(parts.fields.is_some())
498                + usize::from(parts.metadata.is_some())
499                + extras.len(),
500        ))?;
501        m.serialize_entry("schema_name", "DoclingDocument")?;
502        m.serialize_entry("version", SCHEMA_VERSION)?;
503        m.serialize_entry("name", &parts.name)?;
504        m.serialize_entry("origin", &parts.origin)?;
505        if let Some(meta) = &parts.metadata {
506            m.serialize_entry("metadata", meta)?;
507        }
508        m.serialize_entry("furniture", &parts.furniture)?;
509        m.serialize_entry("body", &Body(&parts.body))?;
510        m.serialize_entry("groups", &parts.groups)?;
511        m.serialize_entry("texts", &Texts(&parts.texts))?;
512        m.serialize_entry("pictures", &parts.pictures)?;
513        m.serialize_entry("tables", &parts.tables)?;
514        m.serialize_entry("key_value_items", &parts.key_value_items)?;
515        m.serialize_entry("form_items", &[(); 0])?;
516        if let Some((regions, items)) = &parts.fields {
517            m.serialize_entry("field_regions", regions)?;
518            m.serialize_entry("field_items", items)?;
519        }
520        m.serialize_entry("pages", &parts.pages)?;
521        for (k, v) in extras {
522            m.serialize_entry(k, v)?;
523        }
524        m.end()
525    }
526}
527
528/// The body object: fixed keys around its `children`.
529struct Body<'a>(&'a [Child]);
530
531impl serde::Serialize for Body<'_> {
532    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
533        use serde::ser::SerializeMap;
534        let mut m = s.serialize_map(Some(5))?;
535        m.serialize_entry("self_ref", "#/body")?;
536        m.serialize_entry("children", self.0)?;
537        m.serialize_entry("content_layer", "body")?;
538        m.serialize_entry("name", "_root_")?;
539        m.serialize_entry("label", "unspecified")?;
540        m.end()
541    }
542}
543
544/// Write `doc`'s docling JSON to `w` — byte for byte what serializing
545/// [`to_json`]'s `Value` writes (compact, or `pretty` as
546/// `serde_json::to_writer_pretty` indents it), without building that
547/// `Value`. On a long PDF the `Value` is most of the export's memory: ~2.7 KB
548/// per text item (an owned-key map per JSON object) against a few hundred
549/// bytes here.
550pub fn write_json<W: std::io::Write>(
551    doc: &DoclingDocument,
552    w: W,
553    pretty: bool,
554) -> serde_json::Result<()> {
555    write_json_with(doc, w, pretty, &[])
556}
557
558/// [`write_json`] with `extras` appended after `pages` — byte for byte
559/// serializing [`to_json`]'s `Value` with each `value[k] = v` inserted (the
560/// keys must be new to it, as docling-serve's `confidence` is).
561pub fn write_json_with<W: std::io::Write>(
562    doc: &DoclingDocument,
563    w: W,
564    pretty: bool,
565    extras: &[(&str, &Value)],
566) -> serde_json::Result<()> {
567    use serde::Serialize;
568    let parts = build_parts(doc, false);
569    let parts = PartsWith(&parts, extras);
570    if pretty {
571        parts.serialize(&mut serde_json::Serializer::pretty(w))
572    } else {
573        parts.serialize(&mut serde_json::Serializer::new(w))
574    }
575}
576
577/// A DocumentPictureClassifier's predictions as the picture's `meta` — they
578/// land twice, exactly like docling 2.x writes them: the newer
579/// `meta.classification` field (pydantic field order: confidence, created_by,
580/// class_name) and the deprecated-but-still-emitted `classification`
581/// annotation, carried here under an `annotations` key that `add_picture`
582/// lifts onto the item.
583fn classification_meta(classes: &[crate::PictureClass]) -> Value {
584    json!({
585        "classification": {
586            "predictions": classes.iter().map(|c| json!({
587                "confidence": c.confidence as f64,
588                "created_by": "DocumentPictureClassifier",
589                "class_name": c.class_name,
590            })).collect::<Vec<_>>(),
591        },
592        "annotations": [{
593            "kind": "classification",
594            "provenance": "DocumentPictureClassifier",
595            "predicted_classes": classes.iter().map(|c| json!({
596                "class_name": c.class_name,
597                "confidence": c.confidence as f64,
598            })).collect::<Vec<_>>(),
599        }],
600    })
601}
602
603/// The picture-OCR enrichment's text (#645) as docling writes a picture
604/// description: `meta.description` — a `DescriptionMetaField`, pydantic
605/// field order `created_by` (the model, here the OCR engine) then `text` —
606/// plus the deprecated-but-still-emitted `PictureDescriptionData`
607/// annotation (`kind`, `text`, `provenance`), both exactly what
608/// `PictureDescriptionBaseModel` attaches. Carried like
609/// [`classification_meta`]'s: `annotations` is lifted onto the item.
610fn description_meta(desc: &crate::PictureDescription) -> Value {
611    json!({
612        "description": {
613            "created_by": desc.provenance,
614            "text": desc.text,
615        },
616        "annotations": [{
617            "kind": "description",
618            "text": desc.text,
619            "provenance": desc.provenance,
620        }],
621    })
622}
623
624/// A flat picture node's `meta`: the classifier's predictions and/or the
625/// OCR description, merged — `description` precedes `classification` in
626/// `PictureMeta`'s field order (it is inherited from the floating-item
627/// base), the annotations run in the order docling's enrichment pipeline
628/// appends them (classification, then description).
629fn picture_meta(
630    classes: Option<&[crate::PictureClass]>,
631    desc: Option<&crate::PictureDescription>,
632) -> Option<Value> {
633    let mut meta = Map::new();
634    let mut annotations = Vec::new();
635    if let Some(desc) = desc {
636        if desc.is_docling_meta() {
637            // docling's backend-written description: `text` alone, and no
638            // legacy annotation mirrors it (docling#5015).
639            meta.insert("description".into(), json!({ "text": desc.text }));
640        } else {
641            let mut m = description_meta(desc);
642            annotations.push(m["annotations"][0].take());
643            meta.insert("description".into(), m["description"].take());
644        }
645    }
646    if let Some(classes) = classes {
647        let mut m = classification_meta(classes);
648        annotations.insert(0, m["annotations"][0].take());
649        meta.insert("classification".into(), m["classification"].take());
650    }
651    if meta.is_empty() {
652        return None;
653    }
654    meta.insert("annotations".into(), Value::Array(annotations));
655    Some(Value::Object(meta))
656}
657
658/// One table cell of docling's `TableCell`, typed (#875): the table's cells
659/// stay these until the export writes them, rather than a `serde_json` map
660/// of eleven owned keys each — and a second copy of that map in every grid
661/// slot the cell covers. As maps a short numeric CSV cell cost ~7.5 KB of
662/// export peak; typed it is this struct plus its text.
663#[derive(Clone)]
664pub(crate) struct GridCell {
665    row_span: usize,
666    col_span: usize,
667    start_row: usize,
668    end_row: usize,
669    start_col: usize,
670    end_col: usize,
671    text: Box<str>,
672    column_header: bool,
673    row_header: bool,
674    row_section: bool,
675    /// `l t r b`, top-left origin — the backend's `f32` box widened to the
676    /// `f64` a `Value` would hold it as, so both paths print the same digits.
677    bbox: Option<[f64; 4]>,
678    /// A `RichTableCell`'s `ref` to the group holding its content — written
679    /// on `table_cells` only; the `grid` shows the plain cell.
680    cell_ref: Option<Box<Value>>,
681}
682
683impl GridCell {
684    /// docling's empty filler for a grid position no cell covers.
685    fn filler(r: usize, c: usize) -> Self {
686        GridCell {
687            row_span: 1,
688            col_span: 1,
689            start_row: r,
690            end_row: r + 1,
691            start_col: c,
692            end_col: c + 1,
693            text: "".into(),
694            column_header: false,
695            row_header: false,
696            row_section: false,
697            bbox: None,
698            cell_ref: None,
699        }
700    }
701
702    /// The cell as a `Value`: the eleven fields in pydantic order, `bbox`
703    /// appended when the cell carries one, then the rich cell's `ref`
704    /// (`with_ref`, the `table_cells` copy). Built straight into a `Map`
705    /// sized for its entries rather than through `json!`'s doubling map.
706    fn to_value(&self, with_ref: bool) -> Value {
707        let mut m = serde_json::Map::with_capacity(13);
708        m.insert("row_span".into(), self.row_span.into());
709        m.insert("col_span".into(), self.col_span.into());
710        m.insert("start_row_offset_idx".into(), self.start_row.into());
711        m.insert("end_row_offset_idx".into(), self.end_row.into());
712        m.insert("start_col_offset_idx".into(), self.start_col.into());
713        m.insert("end_col_offset_idx".into(), self.end_col.into());
714        m.insert("text".into(), Value::String(self.text.to_string()));
715        m.insert("column_header".into(), self.column_header.into());
716        m.insert("row_header".into(), self.row_header.into());
717        m.insert("row_section".into(), self.row_section.into());
718        m.insert("fillable".into(), false.into());
719        if let Some([l, t, r, b]) = self.bbox {
720            m.insert(
721                "bbox".into(),
722                object([
723                    ("l", l.into()),
724                    ("t", t.into()),
725                    ("r", r.into()),
726                    ("b", b.into()),
727                    ("coord_origin", "TOPLEFT".into()),
728                ]),
729            );
730        }
731        if let Some(r) = self.cell_ref.as_deref().filter(|_| with_ref) {
732            m.insert("ref".into(), r.clone());
733        }
734        Value::Object(m)
735    }
736}
737
738/// [`GridCell::to_value`] written in place: the same keys in the same order.
739struct CellOut<'a>(&'a GridCell, bool);
740
741impl serde::Serialize for CellOut<'_> {
742    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
743        use serde::ser::SerializeMap;
744        let CellOut(c, with_ref) = *self;
745        let cell_ref = c.cell_ref.as_deref().filter(|_| with_ref);
746        let mut m = s.serialize_map(Some(
747            11 + usize::from(c.bbox.is_some()) + usize::from(cell_ref.is_some()),
748        ))?;
749        m.serialize_entry("row_span", &c.row_span)?;
750        m.serialize_entry("col_span", &c.col_span)?;
751        m.serialize_entry("start_row_offset_idx", &c.start_row)?;
752        m.serialize_entry("end_row_offset_idx", &c.end_row)?;
753        m.serialize_entry("start_col_offset_idx", &c.start_col)?;
754        m.serialize_entry("end_col_offset_idx", &c.end_col)?;
755        m.serialize_entry("text", &c.text)?;
756        m.serialize_entry("column_header", &c.column_header)?;
757        m.serialize_entry("row_header", &c.row_header)?;
758        m.serialize_entry("row_section", &c.row_section)?;
759        m.serialize_entry("fillable", &false)?;
760        if let Some(b) = c.bbox {
761            struct Bbox([f64; 4]);
762            impl serde::Serialize for Bbox {
763                fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
764                    let mut m = s.serialize_map(Some(5))?;
765                    for (k, v) in ["l", "t", "r", "b"].iter().zip(self.0) {
766                        m.serialize_entry(k, &v)?;
767                    }
768                    m.serialize_entry("coord_origin", "TOPLEFT")?;
769                    m.end()
770                }
771            }
772            m.serialize_entry("bbox", &Bbox(b))?;
773        }
774        if let Some(r) = cell_ref {
775            m.serialize_entry("ref", r)?;
776        }
777        m.end()
778    }
779}
780
781/// What a `grid` position shows: the cell covering it (an index into
782/// [`TableData::cells`] — docling repeats the whole cell at every position
783/// it spans), docling's empty filler cell, or `null`.
784#[derive(Clone, Copy)]
785enum GridSlot {
786    Cell(usize),
787    Filler,
788    Null,
789}
790
791/// docling's `TableData` for a table: `table_cells`, `num_rows`/`num_cols`
792/// and the `grid` that repeats each cell at every position it covers —
793/// typed (#875), each cell stored once and the grid as slots pointing at
794/// it, so a table costs its cells rather than a map per cell and per slot.
795/// Shared by table items and a chart picture's `meta.tabular_chart.chart_data`.
796pub(crate) struct TableData {
797    cells: Vec<GridCell>,
798    num_rows: usize,
799    num_cols: usize,
800    /// Row-major, `num_rows × num_cols`.
801    grid: Vec<GridSlot>,
802}
803
804/// One position of docling's `TableData.grid`, as the DocLang tree
805/// serializer reads it (`doclang_tree.rs`): the covering cell's anchor,
806/// text and header roles — an empty filler where no cell covers the
807/// position, which is what docling's computed `grid` holds there.
808pub(crate) struct GridPos<'a> {
809    pub(crate) start_row: usize,
810    pub(crate) start_col: usize,
811    pub(crate) text: &'a str,
812    pub(crate) column_header: bool,
813    pub(crate) row_header: bool,
814    pub(crate) row_section: bool,
815}
816
817/// [`TableData`] of a backend-built tree's table (raw cell text).
818pub(crate) fn raw_table_data(t: &Table) -> TableData {
819    table_data_with(t, true)
820}
821
822impl TableData {
823    /// `(num_rows, num_cols)`.
824    pub(crate) fn dims(&self) -> (usize, usize) {
825        (self.num_rows, self.num_cols)
826    }
827
828    /// Whether `table_cells` holds any cell.
829    pub(crate) fn has_cells(&self) -> bool {
830        !self.cells.is_empty()
831    }
832
833    /// The grid position `(r, c)`.
834    pub(crate) fn at(&self, r: usize, c: usize) -> GridPos<'_> {
835        match self.grid[r * self.num_cols + c] {
836            GridSlot::Cell(i) => {
837                let cell = &self.cells[i];
838                GridPos {
839                    start_row: cell.start_row,
840                    start_col: cell.start_col,
841                    text: &cell.text,
842                    column_header: cell.column_header,
843                    row_header: cell.row_header,
844                    row_section: cell.row_section,
845                }
846            }
847            GridSlot::Filler | GridSlot::Null => GridPos {
848                start_row: r,
849                start_col: c,
850                text: "",
851                column_header: false,
852                row_header: false,
853                row_section: false,
854            },
855        }
856    }
857}
858
859impl TableData {
860    fn slot_cell(
861        &self,
862        slot: GridSlot,
863        r: usize,
864        c: usize,
865    ) -> Option<std::borrow::Cow<'_, GridCell>> {
866        match slot {
867            GridSlot::Cell(i) => Some(std::borrow::Cow::Borrowed(&self.cells[i])),
868            GridSlot::Filler => Some(std::borrow::Cow::Owned(GridCell::filler(r, c))),
869            GridSlot::Null => None,
870        }
871    }
872
873    fn into_value(self) -> Value {
874        let cells = Value::Array(self.cells.iter().map(|c| c.to_value(true)).collect());
875        let mut data = serde_json::Map::with_capacity(5);
876        data.insert("table_cells".into(), cells);
877        data.insert("num_rows".into(), self.num_rows.into());
878        data.insert("num_cols".into(), self.num_cols.into());
879        data.insert("orientation".into(), "rot_0".into());
880        let mut rows = Vec::with_capacity(self.num_rows);
881        for r in 0..self.num_rows {
882            let mut row = Vec::with_capacity(self.num_cols);
883            for c in 0..self.num_cols {
884                let slot = self.grid[r * self.num_cols + c];
885                row.push(match self.slot_cell(slot, r, c) {
886                    Some(cell) => cell.to_value(false),
887                    None => Value::Null,
888                });
889            }
890            rows.push(Value::Array(row));
891        }
892        data.insert("grid".into(), Value::Array(rows));
893        Value::Object(data)
894    }
895
896    /// docling's page clamp ([`clamp_boxes_to_pages`]) on every cell box —
897    /// once per cell: the grid's copies are the same cells.
898    fn clamp(&mut self, (w, h): (f64, f64)) {
899        for bbox in self.cells.iter_mut().filter_map(|c| c.bbox.as_mut()) {
900            for (v, hi) in bbox.iter_mut().zip([w, h, w, h]) {
901                // A non-finite coordinate is `null` in the JSON, which the
902                // clamp leaves alone.
903                if v.is_finite() {
904                    *v = round2(v.clamp(0.0, hi.max(0.0)));
905                }
906            }
907        }
908    }
909}
910
911impl serde::Serialize for TableData {
912    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
913        use serde::ser::{SerializeMap, SerializeSeq};
914        struct Cells<'a>(&'a [GridCell]);
915        impl serde::Serialize for Cells<'_> {
916            fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
917                let mut seq = s.serialize_seq(Some(self.0.len()))?;
918                for c in self.0 {
919                    seq.serialize_element(&CellOut(c, true))?;
920                }
921                seq.end()
922            }
923        }
924        struct Row<'a>(&'a TableData, usize);
925        impl serde::Serialize for Row<'_> {
926            fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
927                let Row(t, r) = *self;
928                let mut seq = s.serialize_seq(Some(t.num_cols))?;
929                for c in 0..t.num_cols {
930                    match t.slot_cell(t.grid[r * t.num_cols + c], r, c) {
931                        Some(cell) => seq.serialize_element(&CellOut(&cell, false))?,
932                        None => seq.serialize_element(&())?,
933                    }
934                }
935                seq.end()
936            }
937        }
938        struct Grid<'a>(&'a TableData);
939        impl serde::Serialize for Grid<'_> {
940            fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
941                let mut seq = s.serialize_seq(Some(self.0.num_rows))?;
942                for r in 0..self.0.num_rows {
943                    seq.serialize_element(&Row(self.0, r))?;
944                }
945                seq.end()
946            }
947        }
948        let mut m = s.serialize_map(Some(5))?;
949        m.serialize_entry("table_cells", &Cells(&self.cells))?;
950        m.serialize_entry("num_rows", &self.num_rows)?;
951        m.serialize_entry("num_cols", &self.num_cols)?;
952        m.serialize_entry("orientation", "rot_0")?;
953        m.serialize_entry("grid", &Grid(self))?;
954        m.end()
955    }
956}
957
958/// A table cell as the `Value`-walking serializers read it — from a typed
959/// [`GridCell`] or from a `table_cells` entry of docling JSON (a document
960/// Python docling wrote, read by [`crate::pandoc::from_docling_json`]): a
961/// missing field reads as `0` / `""` / `false`, like the `Value` getters
962/// those serializers used.
963pub(crate) struct CellView<'a> {
964    pub start_row: usize,
965    pub end_row: usize,
966    pub start_col: usize,
967    pub end_col: usize,
968    pub row_span: usize,
969    pub col_span: usize,
970    pub text: &'a str,
971    pub column_header: bool,
972    pub row_header: bool,
973    pub row_section: bool,
974    /// A rich cell's `ref.$ref`.
975    pub cell_ref: Option<&'a str>,
976}
977
978/// A table's `data` as [`CellView`]s: `num_rows`, `num_cols` and the
979/// `table_cells` (the derived `grid` is not read).
980pub(crate) struct TableView<'a> {
981    pub num_rows: usize,
982    pub num_cols: usize,
983    pub cells: Vec<CellView<'a>>,
984}
985
986/// The [`TableView`] of a table item's `data`: the typed table it names
987/// ([`TYPED_TABLE`], an index into `typed`), or the JSON's own fields.
988pub(crate) fn table_view<'a>(data: &'a Value, typed: &'a [TableData]) -> TableView<'a> {
989    let ref_of = |r: Option<&'a Value>| r.and_then(|r| r.get("$ref")).and_then(Value::as_str);
990    if let Some(t) = data
991        .get(TYPED_TABLE)
992        .and_then(Value::as_u64)
993        .and_then(|i| typed.get(i as usize))
994    {
995        return TableView {
996            num_rows: t.num_rows,
997            num_cols: t.num_cols,
998            cells: t
999                .cells
1000                .iter()
1001                .map(|c| CellView {
1002                    start_row: c.start_row,
1003                    end_row: c.end_row,
1004                    start_col: c.start_col,
1005                    end_col: c.end_col,
1006                    row_span: c.row_span,
1007                    col_span: c.col_span,
1008                    text: &c.text,
1009                    column_header: c.column_header,
1010                    row_header: c.row_header,
1011                    row_section: c.row_section,
1012                    cell_ref: ref_of(c.cell_ref.as_deref()),
1013                })
1014                .collect(),
1015        };
1016    }
1017    let num = |v: &Value, k: &str| v.get(k).and_then(Value::as_u64).unwrap_or(0) as usize;
1018    let flag = |v: &Value, k: &str| v.get(k).and_then(Value::as_bool).unwrap_or(false);
1019    TableView {
1020        num_rows: num(data, "num_rows"),
1021        num_cols: num(data, "num_cols"),
1022        cells: data
1023            .get("table_cells")
1024            .and_then(Value::as_array)
1025            .into_iter()
1026            .flatten()
1027            .map(|c| CellView {
1028                start_row: num(c, "start_row_offset_idx"),
1029                end_row: num(c, "end_row_offset_idx"),
1030                start_col: num(c, "start_col_offset_idx"),
1031                end_col: num(c, "end_col_offset_idx"),
1032                row_span: num(c, "row_span"),
1033                col_span: num(c, "col_span"),
1034                text: c.get("text").and_then(Value::as_str).unwrap_or(""),
1035                column_header: flag(c, "column_header"),
1036                row_header: flag(c, "row_header"),
1037                row_section: flag(c, "row_section"),
1038                cell_ref: ref_of(c.get("ref")),
1039            })
1040            .collect(),
1041    }
1042}
1043
1044/// A `tables` entry: the item's JSON with a `null` stand-in under `data`
1045/// — so every edit of the item (children, content layer, comment
1046/// back-refs) works on the `Value` as before and keeps its key order —
1047/// and the typed [`TableData`] that takes the stand-in's place when the
1048/// item is written or turned into a `Value`.
1049struct TableItem {
1050    item: Value,
1051    data: TableData,
1052}
1053
1054impl TableItem {
1055    fn into_value(self) -> Value {
1056        let TableItem { mut item, data } = self;
1057        if let Some(slot) = item.get_mut("data") {
1058            *slot = data.into_value();
1059        }
1060        item
1061    }
1062}
1063
1064impl serde::Serialize for TableItem {
1065    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1066        use serde::ser::SerializeMap;
1067        let Value::Object(obj) = &self.item else {
1068            return self.item.serialize(s);
1069        };
1070        let mut m = s.serialize_map(Some(obj.len()))?;
1071        for (k, v) in obj {
1072            if k == "data" {
1073                m.serialize_entry(k, &self.data)?;
1074            } else {
1075                m.serialize_entry(k, v)?;
1076            }
1077        }
1078        m.end()
1079    }
1080}
1081
1082/// `TableData` from a table whose cell text is Markdown-flavoured (the flat
1083/// nodes: escapes to undo, GFM hard-break markers to strip).
1084fn table_data(t: &Table) -> TableData {
1085    table_data_with(t, false)
1086}
1087
1088/// `TableData`; with `raw` the cell text is docling's own raw cell text (a
1089/// backend-built tree) and is written verbatim.
1090fn table_data_with(t: &Table, raw: bool) -> TableData {
1091    let cell_text = |s: &str| -> Box<str> {
1092        if raw {
1093            s.into()
1094        } else {
1095            unescape_text(&crate::markdown::strip_hard_breaks(s)).into()
1096        }
1097    };
1098    let widen = |b: [f32; 4]| b.map(f64::from);
1099    let mut num_rows = t.rows.len();
1100    let mut num_cols = t.rows.iter().map(Vec::len).max().unwrap_or(0);
1101    // Rectangular `rows` are the grid, and cells reaching past it are
1102    // clipped — docling's own `TableData.grid` on a USPTO table whose
1103    // replicated cells outrun `num_cols`, or an HTML rowspan past the last
1104    // row. Ragged rows are no grid at all: a backend that compacts them
1105    // (xlsx `skip_empty_cells`, #271) keeps the true offsets in first-class
1106    // cells, so there the grid spans every cell's extent and the omitted
1107    // positions come back as docling's empty filler cells.
1108    let ragged = t.rows.iter().any(|r| r.len() != num_cols);
1109    if let Some(first_class) = t.cells.as_ref().filter(|c| ragged && !c.is_empty()) {
1110        let (mut rows, mut cols) = (num_rows, num_cols);
1111        for c in first_class {
1112            rows = rows.max(c.start_row.saturating_add(c.row_span));
1113            cols = cols.max(c.start_col.saturating_add(c.col_span));
1114        }
1115        // A cell whose declared extent reaches past the cell budget (#861)
1116        // does not size the slot map; the grid stays the rows' own and the
1117        // cell is clipped to it, like any other cell reaching past the grid.
1118        if rows.saturating_mul(cols) <= crate::limits::max_table_cells() {
1119            num_rows = rows;
1120            num_cols = cols;
1121        }
1122    }
1123    let mut cells = Vec::new();
1124    // Grid slot → the cell covering it, row-major — no per-slot copy and
1125    // nothing hashed.
1126    let mut grid: Vec<GridSlot>;
1127    if let Some(first_class) = t.cells.as_ref().filter(|c| !c.is_empty()) {
1128        // A position no cell covers is docling's empty filler cell.
1129        grid = vec![GridSlot::Filler; num_rows * num_cols];
1130        cells.reserve(first_class.len());
1131        for c in first_class {
1132            let idx = cells.len();
1133            cells.push(GridCell {
1134                row_span: c.row_span,
1135                col_span: c.col_span,
1136                start_row: c.start_row,
1137                end_row: c.start_row + c.row_span,
1138                start_col: c.start_col,
1139                end_col: c.start_col + c.col_span,
1140                text: cell_text(&c.text),
1141                column_header: c.column_header,
1142                row_header: c.row_header,
1143                row_section: c.row_section,
1144                bbox: c.bbox.map(widen),
1145                cell_ref: None,
1146            });
1147            for r in c.start_row..(c.start_row + c.row_span).min(num_rows) {
1148                for k in c.start_col..(c.start_col + c.col_span).min(num_cols) {
1149                    grid[r * num_cols + k] = GridSlot::Cell(idx);
1150                }
1151            }
1152        }
1153    } else {
1154        grid = vec![GridSlot::Null; num_rows * num_cols];
1155        let s = t.structure.as_ref();
1156        let flag = |grid: Option<&Vec<Vec<bool>>>, r: usize, c: usize| -> bool {
1157            grid.and_then(|g| g.get(r))
1158                .and_then(|row| row.get(c))
1159                .copied()
1160                .unwrap_or(false)
1161        };
1162        let anchor_of = |r: usize, c: usize| -> (usize, usize) {
1163            let (mut r0, mut c0) = (r, c);
1164            while c0 > 0 && flag(s.map(|s| &s.col_continuation), r, c0) {
1165                c0 -= 1;
1166            }
1167            while r0 > 0 && flag(s.map(|s| &s.row_continuation), r0, c0) {
1168                r0 -= 1;
1169            }
1170            (r0, c0)
1171        };
1172        // Each slot's anchor, computed once; the anchor's extent is the
1173        // farthest slot that resolves to it.
1174        let anchors: Vec<(usize, usize)> = (0..num_rows)
1175            .flat_map(|r| (0..num_cols).map(move |c| (r, c)))
1176            .map(|(r, c)| anchor_of(r, c))
1177            .collect();
1178        let mut extent: Vec<(usize, usize)> = (0..num_rows)
1179            .flat_map(|r| (0..num_cols).map(move |c| (r, c)))
1180            .collect();
1181        for (i, &(ar, ac)) in anchors.iter().enumerate() {
1182            let (r, c) = (i / num_cols.max(1), i % num_cols.max(1));
1183            let e = &mut extent[ar * num_cols + ac];
1184            e.0 = e.0.max(r);
1185            e.1 = e.1.max(c);
1186        }
1187        // An anchor's cell, by slot, once it is created (anchors precede
1188        // the slots they cover in row-major order).
1189        let mut anchor_cell: Vec<Option<usize>> = vec![None; num_rows * num_cols];
1190        for (r, row) in t.rows.iter().enumerate() {
1191            for c in 0..num_cols {
1192                let (ar, ac) = anchors[r * num_cols + c];
1193                if (ar, ac) == (r, c) {
1194                    let (er, ec) = extent[r * num_cols + c];
1195                    let text = row.get(c).map(|s| cell_text(s)).unwrap_or_default();
1196                    let column_header = match s.filter(|s| !s.col_header.is_empty()) {
1197                        Some(s) => flag(Some(&s.col_header), r, c),
1198                        None => r == 0,
1199                    };
1200                    anchor_cell[r * num_cols + c] = Some(cells.len());
1201                    cells.push(GridCell {
1202                        row_span: er - r + 1,
1203                        col_span: ec - c + 1,
1204                        start_row: r,
1205                        end_row: er + 1,
1206                        start_col: c,
1207                        end_col: ec + 1,
1208                        text,
1209                        column_header,
1210                        row_header: flag(s.map(|s| &s.row_header), r, c),
1211                        row_section: false,
1212                        bbox: None,
1213                        cell_ref: None,
1214                    });
1215                }
1216                if let Some(i) = anchor_cell[ar * num_cols + ac] {
1217                    grid[r * num_cols + c] = GridSlot::Cell(i);
1218                }
1219            }
1220        }
1221    }
1222    TableData {
1223        cells,
1224        num_rows,
1225        num_cols,
1226        grid,
1227    }
1228}
1229
1230/// An item's `prov` array as the builder holds it: empty, or docling's one
1231/// `ProvenanceItem` — kept typed so a text item need not be a `Value` until
1232/// it is written (see [`Item`]).
1233#[derive(Clone, Copy)]
1234enum ProvSlot {
1235    None,
1236    One {
1237        page_no: usize,
1238        /// `l t r b`, already rounded to 2 decimals.
1239        bbox: [f64; 4],
1240        bottom_left: bool,
1241        charspan: [usize; 2],
1242    },
1243}
1244
1245impl ProvSlot {
1246    fn origin(bottom_left: bool) -> &'static str {
1247        if bottom_left {
1248            "BOTTOMLEFT"
1249        } else {
1250            "TOPLEFT"
1251        }
1252    }
1253
1254    /// The `prov` array: `page_no`, `bbox` (`l t r b` + `coord_origin`) and
1255    /// `charspan`, in pydantic field order.
1256    fn to_value(self) -> Value {
1257        let ProvSlot::One {
1258            page_no,
1259            bbox: [l, t, r, b],
1260            bottom_left,
1261            charspan,
1262        } = self
1263        else {
1264            return Value::Array(Vec::new());
1265        };
1266        let bbox = object([
1267            ("l", l.into()),
1268            ("t", t.into()),
1269            ("r", r.into()),
1270            ("b", b.into()),
1271            ("coord_origin", Self::origin(bottom_left).into()),
1272        ]);
1273        let span = Value::Array(vec![charspan[0].into(), charspan[1].into()]);
1274        Value::Array(vec![object([
1275            ("page_no", page_no.into()),
1276            ("bbox", bbox),
1277            ("charspan", span),
1278        ])])
1279    }
1280
1281    /// docling's page clamp ([`clamp_boxes_to_pages`]) on the typed box.
1282    fn clamp(&mut self, sizes: &PageSizes) {
1283        if let ProvSlot::One { page_no, bbox, .. } = self {
1284            if let Some(&(w, h)) = sizes.get(page_no) {
1285                for (v, hi) in bbox.iter_mut().zip([w, h, w, h]) {
1286                    // A non-finite coordinate is `null` in the JSON, which the
1287                    // clamp leaves alone.
1288                    if v.is_finite() {
1289                        *v = round2(v.clamp(0.0, hi.max(0.0)));
1290                    }
1291                }
1292            }
1293        }
1294    }
1295}
1296
1297impl serde::Serialize for ProvSlot {
1298    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1299        use serde::ser::{SerializeMap, SerializeSeq};
1300        let ProvSlot::One {
1301            page_no,
1302            bbox: [l, t, r, b],
1303            bottom_left,
1304            charspan,
1305        } = *self
1306        else {
1307            return s.serialize_seq(Some(0))?.end();
1308        };
1309        struct Bbox([f64; 4], &'static str);
1310        impl serde::Serialize for Bbox {
1311            fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1312                let mut m = s.serialize_map(Some(5))?;
1313                for (k, v) in ["l", "t", "r", "b"].iter().zip(self.0) {
1314                    m.serialize_entry(k, &v)?;
1315                }
1316                m.serialize_entry("coord_origin", self.1)?;
1317                m.end()
1318            }
1319        }
1320        struct Entry(usize, Bbox, [usize; 2]);
1321        impl serde::Serialize for Entry {
1322            fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1323                let mut m = s.serialize_map(Some(3))?;
1324                m.serialize_entry("page_no", &self.0)?;
1325                m.serialize_entry("bbox", &self.1)?;
1326                m.serialize_entry("charspan", &self.2)?;
1327                m.end()
1328            }
1329        }
1330        let mut seq = s.serialize_seq(Some(1))?;
1331        seq.serialize_element(&Entry(
1332            page_no,
1333            Bbox([l, t, r, b], Self::origin(bottom_left)),
1334            charspan,
1335        ))?;
1336        seq.end()
1337    }
1338}
1339
1340/// The plain text item — docling's `TextItem` with no children, on the body
1341/// layer, `orig` equal to `text` and no extra fields: what a PDF's text layer
1342/// is made of, millions of times over on a long document. As a `Value` each
1343/// cost ~2.7 KB (a map of owned keys per object); typed it is ~150 bytes, and
1344/// it serializes to exactly the same JSON. Its `self_ref` is its position
1345/// (`#/texts/{i}`), so it is not stored.
1346struct TextItem {
1347    parent: Box<str>,
1348    label: Box<str>,
1349    prov: ProvSlot,
1350    text: Box<str>,
1351}
1352
1353impl TextItem {
1354    fn into_value(self, index: usize) -> Value {
1355        let text = String::from(self.text);
1356        object([
1357            ("self_ref", Value::String(format!("#/texts/{index}"))),
1358            ("parent", ref_value(self.parent)),
1359            ("children", Value::Array(Vec::new())),
1360            ("content_layer", "body".into()),
1361            ("label", Value::String(self.label.into())),
1362            ("prov", self.prov.to_value()),
1363            ("orig", Value::String(text.clone())),
1364            ("text", Value::String(text)),
1365        ])
1366    }
1367}
1368
1369/// A `texts` entry: the compact [`TextItem`] until something needs to edit
1370/// it as JSON (a nested list's children, a content-layer move, a comment
1371/// back-ref), then the `Value` it stands for. Both boxed: a slot is 16 bytes.
1372enum Item {
1373    Text(Box<TextItem>),
1374    Json(Box<Value>),
1375}
1376
1377impl Item {
1378    fn json(v: Value) -> Self {
1379        Item::Json(Box::new(v))
1380    }
1381
1382    /// The item at `texts[index]` as an editable `Value`, converting a
1383    /// [`TextItem`] in place.
1384    fn value_mut(&mut self, index: usize) -> &mut Value {
1385        if let Item::Text(t) = self {
1386            let t = std::mem::replace(
1387                t,
1388                Box::new(TextItem {
1389                    parent: "".into(),
1390                    label: "".into(),
1391                    prov: ProvSlot::None,
1392                    text: "".into(),
1393                }),
1394            );
1395            *self = Item::json(t.into_value(index));
1396        }
1397        match self {
1398            Item::Json(v) => v,
1399            Item::Text(_) => unreachable!("converted above"),
1400        }
1401    }
1402
1403    fn into_value(self, index: usize) -> Value {
1404        match self {
1405            Item::Text(t) => t.into_value(index),
1406            Item::Json(v) => *v,
1407        }
1408    }
1409}
1410
1411/// The `texts` array, serialized in place.
1412struct Texts<'a>(&'a [Item]);
1413
1414impl serde::Serialize for Texts<'_> {
1415    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1416        use serde::ser::{SerializeMap, SerializeSeq};
1417        struct Text<'a>(usize, &'a TextItem);
1418        impl serde::Serialize for Text<'_> {
1419            fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1420                let Text(i, t) = *self;
1421                let mut m = s.serialize_map(Some(8))?;
1422                m.serialize_entry("self_ref", &format_args!("#/texts/{i}"))?;
1423                m.serialize_entry("parent", &Child::Ref(t.parent.clone()))?;
1424                m.serialize_entry("children", &[(); 0])?;
1425                m.serialize_entry("content_layer", "body")?;
1426                m.serialize_entry("label", &t.label)?;
1427                m.serialize_entry("prov", &t.prov)?;
1428                m.serialize_entry("orig", &t.text)?;
1429                m.serialize_entry("text", &t.text)?;
1430                m.end()
1431            }
1432        }
1433        let mut seq = s.serialize_seq(Some(self.0.len()))?;
1434        for (i, item) in self.0.iter().enumerate() {
1435            match item {
1436                Item::Text(t) => seq.serialize_element(&Text(i, t))?,
1437                Item::Json(v) => seq.serialize_element(v)?,
1438            }
1439        }
1440        seq.end()
1441    }
1442}
1443
1444/// An entry of a `children` list as the walk collects it: a `{"$ref": …}`
1445/// held as its target string (a body of millions of refs costs ~40 bytes
1446/// each, not a ~270-byte `Value` map), or any other JSON.
1447enum Child {
1448    Ref(Box<str>),
1449    Json(Box<Value>),
1450}
1451
1452impl Child {
1453    fn json(v: Value) -> Self {
1454        Child::Json(Box::new(v))
1455    }
1456
1457    fn into_value(self) -> Value {
1458        match self {
1459            Child::Ref(r) => ref_value(r),
1460            Child::Json(v) => *v,
1461        }
1462    }
1463}
1464
1465impl serde::Serialize for Child {
1466    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1467        use serde::ser::SerializeMap;
1468        match self {
1469            Child::Ref(r) => {
1470                let mut m = s.serialize_map(Some(1))?;
1471                m.serialize_entry("$ref", r)?;
1472                m.end()
1473            }
1474            Child::Json(v) => v.serialize(s),
1475        }
1476    }
1477}
1478
1479fn round2(v: f64) -> f64 {
1480    (v * 100.0).round() / 100.0
1481}
1482
1483#[derive(Default)]
1484struct Builder {
1485    /// Write the internal `_notes` / `_note_body` keys of tree text items
1486    /// ([`crate::tree::TreeItem::notes`]) — for the Pandoc writer only
1487    /// ([`to_json_with_notes`]); docling's JSON has no such fields.
1488    note_keys: bool,
1489    texts: Vec<Item>,
1490    groups: Vec<Value>,
1491    tables: Vec<TableItem>,
1492    pictures: Vec<Value>,
1493    field_regions: Vec<Value>,
1494    field_items: Vec<Value>,
1495    key_value_items: Vec<Value>,
1496    /// Pages seen so far (`page_no`, width, height in points) — from the
1497    /// [`Node::PageInfo`] markers the PDF paths emit; empty for every other
1498    /// backend, which keeps their JSON byte-identical (`"pages": {}`, no prov).
1499    pages: Vec<(usize, f64, f64)>,
1500    /// The page the walk is currently on (0 before the first marker).
1501    cur_page: usize,
1502    cur_w: f64,
1503    cur_h: f64,
1504    /// The enclosing [`Node::Located`] wrapper's 0–511 grid box, waiting to be
1505    /// consumed as the next item's provenance.
1506    pending_loc: Option<[u16; 4]>,
1507    /// The enclosing [`Node::Prov`] wrapper's (or the tree item's) exact
1508    /// provenance, which takes precedence over the grid box.
1509    pending_exact: Option<ExactProv>,
1510    /// The enclosing [`Node::Track`]'s timing, for the text item it wraps
1511    /// (#614).
1512    pending_track: Option<(crate::tree::TreeTrack, String)>,
1513    /// [`Node::Anchor`]s met since the last text item (#852): that item's
1514    /// `_anchors` on the Pandoc path.
1515    pending_anchors: Vec<String>,
1516    /// `$ref`s an item wants placed in its parent's `children` *before* its
1517    /// own — a chart's caption item, which docling's office backends add to
1518    /// the container ahead of the picture that references it.
1519    pending_siblings: Vec<Value>,
1520    /// `$ref`s an item wants placed in its parent's `children` right *after*
1521    /// its own — an HTML `<figure>`-wrapped table's caption
1522    /// ([`CaptionParent::ContainerAfter`]).
1523    pending_after: Vec<Value>,
1524    /// Caption `$ref`s that hang off `#/body` while their item sits deeper
1525    /// ([`CaptionParent::Body`]): docling appends them to the body's children
1526    /// as they are created, so they follow the top-level item being walked.
1527    pending_body: Vec<Value>,
1528    /// What each [`Node::CommentSection`] is referenced by, in document order —
1529    /// its group `$ref`, or its note text's when the section says so. The index
1530    /// is what a [`Node::Commented`] annotation carries.
1531    comment_groups: Vec<String>,
1532    /// The last `comment_section` group emitted, as `(name, self_ref)`: a
1533    /// following section of the same name adds its note to that group rather
1534    /// than opening another — one `comment-{sheet}-{cell}` group holds every
1535    /// message of a threaded comment (docling#4353).
1536    last_comment_section: Option<(String, String)>,
1537    /// Annotated items awaiting their refs: comments are usually emitted
1538    /// *after* the body they annotate (docx appends them), so the link is
1539    /// patched in once the whole document has been walked.
1540    pending_comments: Vec<(String, Vec<usize>)>,
1541    /// The items the script-position stage marked (#1005), with their runs
1542    /// and the label and link the runs take: docling adds the inline groups
1543    /// once the document is assembled, so their groups and run items come
1544    /// after every other item.
1545    pending_scripts: Vec<(String, Vec<crate::ScriptRun>, String)>,
1546    /// The last `#/texts/N` index created: the item a following
1547    /// [`Node::ProvContinuation`] belongs to (#1127).
1548    last_text: Option<usize>,
1549    /// [`Node::ProvContinuation`] fragments waiting for their page. The
1550    /// marker stands right after its item, before the page it is on.
1551    pending_continuations: Vec<PendingContinuation>,
1552}
1553
1554/// A [`Node::ProvContinuation`] the JSON walk met, waiting for its page.
1555struct PendingContinuation {
1556    /// The `#/texts/N` index of the item it continues.
1557    item: usize,
1558    /// Page markers still to pass before the fragment's page.
1559    skip: usize,
1560    location: [u16; 4],
1561    prev_end: usize,
1562    span: [usize; 2],
1563}
1564
1565impl Builder {
1566    /// Consume the pending location (if any) into a docling `prov` array: the
1567    /// 0-511 grid denormalized against the current page into BOTTOMLEFT
1568    /// points, rounded to 2 decimals like docling's own export. `char_len` is
1569    /// the item's text length in characters (0 for tables and pictures, whose
1570    /// charspan docling emits as `[0, 0]`).
1571    fn take_prov(&mut self, char_len: usize) -> Value {
1572        self.take_prov_slot(char_len).to_value()
1573    }
1574
1575    /// [`Self::take_prov`], typed.
1576    fn take_prov_slot(&mut self, char_len: usize) -> ProvSlot {
1577        let prov = self.prov_slot(char_len, false);
1578        self.pending_exact = None;
1579        self.pending_loc = None;
1580        prov
1581    }
1582
1583    /// The pending provenance without consuming it. An exact [`Node::Prov`]
1584    /// box wins over the grid; its own `charspan` is used unless
1585    /// `span_over_text` asks for `[0, char_len]` (a chart caption's span
1586    /// covers the caption text where the chart's is `[0, 0]`).
1587    fn prov_slot(&self, char_len: usize, span_over_text: bool) -> ProvSlot {
1588        let r2 = round2;
1589        if let Some(ExactProv {
1590            page_no,
1591            bbox: [l, t, r, b],
1592            bottom_left,
1593            charspan,
1594        }) = self.pending_exact
1595        {
1596            let charspan = if span_over_text {
1597                [0, char_len]
1598            } else {
1599                charspan
1600            };
1601            return ProvSlot::One {
1602                page_no,
1603                bbox: [r2(l), r2(t), r2(r), r2(b)],
1604                bottom_left,
1605                charspan,
1606            };
1607        }
1608        let Some([x0, y0, x1, y1]) = self.pending_loc else {
1609            return ProvSlot::None;
1610        };
1611        // An all-zero grid box is the sentinel for "this item has no geometry"
1612        // (a slide's speaker notes, say). docling writes a zero bbox for it,
1613        // not a box spanning the page, which is what denormalizing would give.
1614        if [x0, y0, x1, y1] == [0, 0, 0, 0] {
1615            return ProvSlot::One {
1616                page_no: self.cur_page,
1617                bbox: [0.0; 4],
1618                bottom_left: true,
1619                charspan: [0, char_len],
1620            };
1621        }
1622        ProvSlot::One {
1623            page_no: self.cur_page,
1624            bbox: [
1625                r2(x0 as f64 * self.cur_w / 512.0),
1626                r2(self.cur_h - y0 as f64 * self.cur_h / 512.0),
1627                r2(x1 as f64 * self.cur_w / 512.0),
1628                r2(self.cur_h - y1 as f64 * self.cur_h / 512.0),
1629            ],
1630            bottom_left: true,
1631            charspan: [0, char_len],
1632        }
1633    }
1634
1635    /// The 0–511 grid box `loc` denormalized against the current page into
1636    /// BOTTOMLEFT points, rounded to 2 decimals.
1637    fn grid_bbox(&self, [x0, y0, x1, y1]: [u16; 4]) -> [f64; 4] {
1638        [
1639            round2(x0 as f64 * self.cur_w / 512.0),
1640            round2(self.cur_h - y0 as f64 * self.cur_h / 512.0),
1641            round2(x1 as f64 * self.cur_w / 512.0),
1642            round2(self.cur_h - y1 as f64 * self.cur_h / 512.0),
1643        ]
1644    }
1645
1646    /// A page marker passed: every [`Node::ProvContinuation`] fragment on
1647    /// this page becomes one more `prov` entry of its item, after the entry
1648    /// before it is ended at `prev_end` — docling's merged paragraph, one
1649    /// `prov` per fragment, each with its `charspan` into the joined text.
1650    fn resolve_continuations(&mut self) {
1651        if self.pending_continuations.is_empty() {
1652            return;
1653        }
1654        let pending = std::mem::take(&mut self.pending_continuations);
1655        for mut p in pending {
1656            if p.skip > 1 {
1657                p.skip -= 1;
1658                self.pending_continuations.push(p);
1659                continue;
1660            }
1661            let PendingContinuation {
1662                item: idx,
1663                location: loc,
1664                prev_end,
1665                span,
1666                ..
1667            } = p;
1668            if self.cur_page == 0 || loc == [0, 0, 0, 0] {
1669                continue;
1670            }
1671            let [l, t, r, b] = self.grid_bbox(loc);
1672            let page_no = self.cur_page;
1673            let Some(item) = self.texts.get_mut(idx).map(|it| it.value_mut(idx)) else {
1674                continue;
1675            };
1676            // Clamped to the item's text: a later pass (the wrap-mark strip,
1677            // redaction) may have shortened it since the assembler counted.
1678            let total = item["text"].as_str().map_or(0, |t| t.chars().count());
1679            let Some(provs) = item.get_mut("prov").and_then(Value::as_array_mut) else {
1680                continue;
1681            };
1682            // No first fragment to continue: the item has no geometry.
1683            let Some(last) = provs.last_mut() else {
1684                continue;
1685            };
1686            last["charspan"][1] = json!(prev_end.min(total));
1687            provs.push(json!({
1688                "page_no": page_no,
1689                "bbox": {"l": l, "t": t, "r": r, "b": b, "coord_origin": "BOTTOMLEFT"},
1690                "charspan": [span[0].min(total), span[1].min(total)],
1691            }));
1692        }
1693    }
1694
1695    /// Adopt a node's own location field (tables, formulas, list items carry
1696    /// one instead of a [`Node::Located`] wrapper) when no wrapper is pending.
1697    fn adopt_loc(&mut self, loc: Option<[u16; 4]>) {
1698        if self.pending_loc.is_none() && self.cur_page > 0 {
1699            self.pending_loc = loc;
1700        }
1701    }
1702
1703    /// Give each item the script-position stage marked (#1005) its inline
1704    /// group, after the walk as docling's post-assembly stage does: the group
1705    /// is the item's first child (`insert_inline_group(…, after=False)` /
1706    /// `add_inline_group`), and each run is a text item with the item's label,
1707    /// its own `prov` (the box of its characters, per page) and
1708    /// `formatting.script` when it is raised or lowered. A linked footnote's
1709    /// link rides on its baseline runs only, so a marker stays out of it.
1710    fn link_script_runs(&mut self) {
1711        for (item, runs, label) in std::mem::take(&mut self.pending_scripts) {
1712            let group = format!("#/groups/{}", self.groups.len());
1713            let layer = self
1714                .item_mut(&item)
1715                .and_then(|v| v.get("content_layer").cloned())
1716                .unwrap_or_else(|| json!("body"));
1717            let mut children = Vec::with_capacity(runs.len());
1718            for run in &runs {
1719                let self_ref = format!("#/texts/{}", self.texts.len());
1720                children.push(ref_value(&self_ref));
1721                let prov: Vec<Value> = run
1722                    .prov
1723                    .iter()
1724                    .map(|p| {
1725                        let [l, t, r, b] = p.bbox.map(|v| round2(f64::from(v)));
1726                        json!({
1727                            "page_no": p.page_no,
1728                            "bbox": {"l": l, "t": t, "r": r, "b": b, "coord_origin": "BOTTOMLEFT"},
1729                            "charspan": p.charspan,
1730                        })
1731                    })
1732                    .collect();
1733                let mut m = serde_json::Map::new();
1734                m.insert("self_ref".into(), json!(self_ref));
1735                m.insert("parent".into(), ref_value(&group));
1736                m.insert("children".into(), json!([]));
1737                m.insert("content_layer".into(), layer.clone());
1738                m.insert("label".into(), json!(label));
1739                m.insert("prov".into(), Value::Array(prov));
1740                m.insert("orig".into(), json!(run.text));
1741                m.insert("text".into(), json!(run.text));
1742                if run.script != crate::Script::Baseline {
1743                    m.insert(
1744                        "formatting".into(),
1745                        formatting_json(&crate::tree::Formatting {
1746                            script: run.script,
1747                            ..Default::default()
1748                        }),
1749                    );
1750                }
1751                if let Some(url) = &run.hyperlink {
1752                    m.insert("hyperlink".into(), json!(url));
1753                }
1754                self.texts.push(Item::json(Value::Object(m)));
1755            }
1756            self.groups.push(json!({
1757                "self_ref": group,
1758                "parent": ref_value(&item),
1759                "children": children,
1760                "content_layer": layer,
1761                "name": "group",
1762                "label": "inline",
1763            }));
1764            if let Some(obj) = self.item_mut(&item).and_then(Value::as_object_mut) {
1765                let mut kids = vec![ref_value(&group)];
1766                if let Some(Value::Array(old)) = obj.get("children") {
1767                    kids.extend(old.iter().cloned());
1768                }
1769                obj.insert("children".into(), Value::Array(kids));
1770            }
1771        }
1772    }
1773
1774    /// Resolve the [`Node::Commented`] annotations collected during the walk
1775    /// into docling's `comments: [{"$ref": "#/groups/N"}]` key on the annotated
1776    /// item. It has to run after the whole walk: docx appends its comment
1777    /// bodies, so the groups they live in are usually allocated *later* than
1778    /// the paragraphs pointing at them. docling emits the key between `prov`
1779    /// and `orig`, so insert it in place rather than appending (serde_json runs
1780    /// with `preserve_order`, i.e. key order is output order).
1781    fn link_comments(&mut self) {
1782        let refs: Vec<(String, Vec<Value>)> = std::mem::take(&mut self.pending_comments)
1783            .into_iter()
1784            .map(|(item, comments)| {
1785                let refs = comments
1786                    .iter()
1787                    .filter_map(|i| self.comment_groups.get(*i))
1788                    .map(ref_value)
1789                    .collect();
1790                (item, refs)
1791            })
1792            .collect();
1793        for (item, comment_refs) in refs {
1794            if comment_refs.is_empty() {
1795                continue;
1796            }
1797            let Some(target) = self.item_mut(&item) else {
1798                continue;
1799            };
1800            let Some(obj) = target.as_object_mut() else {
1801                continue;
1802            };
1803            let tail: Vec<(String, Value)> = obj
1804                .iter()
1805                .skip_while(|(k, _)| k.as_str() != "prov")
1806                .skip(1)
1807                .map(|(k, v)| (k.clone(), v.clone()))
1808                .collect();
1809            for (k, _) in &tail {
1810                // Without `preserve-order` the map is sorted and the position
1811                // is moot (#970); `remove` is the only removal it has.
1812                #[cfg(feature = "preserve-order")]
1813                obj.shift_remove(k);
1814                #[cfg(not(feature = "preserve-order"))]
1815                obj.remove(k);
1816            }
1817            obj.insert("comments".into(), Value::Array(comment_refs));
1818            for (k, v) in tail {
1819                obj.insert(k, v);
1820            }
1821        }
1822    }
1823
1824    /// The stored JSON object a `#/texts/N`-style self-ref points at.
1825    fn item_mut(&mut self, self_ref: &str) -> Option<&mut Value> {
1826        let idx = ref_index(self_ref)?;
1827        if self_ref.starts_with("#/texts/") {
1828            return self.texts.get_mut(idx).map(|item| item.value_mut(idx));
1829        }
1830        if self_ref.starts_with("#/tables/") {
1831            return self.tables.get_mut(idx).map(|t| &mut t.item);
1832        }
1833        let bucket = if self_ref.starts_with("#/pictures/") {
1834            &mut self.pictures
1835        } else if self_ref.starts_with("#/groups/") {
1836            &mut self.groups
1837        } else {
1838            return None;
1839        };
1840        bucket.get_mut(idx)
1841    }
1842
1843    /// Serialize a backend-built [`ItemTree`](crate::tree::ItemTree): every
1844    /// item in creation order into its bucket, with the parent / children /
1845    /// layer the tree recorded. Returns the body's `children` refs.
1846    fn write_tree(&mut self, tree: &crate::tree::ItemTree) -> Vec<Value> {
1847        use crate::tree::TreeKind;
1848        // Every item's `self_ref` first: children may be listed before they
1849        // are written (a rich cell's group is created after its content).
1850        let mut refs: Vec<String> = Vec::with_capacity(tree.items.len());
1851        let (mut nt, mut ng, mut ntb, mut np, mut nf, mut nk) = (0, 0, 0, 0, 0, 0);
1852        for item in &tree.items {
1853            if item.deleted {
1854                refs.push(String::new());
1855                continue;
1856            }
1857            let r = match &item.kind {
1858                TreeKind::Text { .. } | TreeKind::Code { .. } => {
1859                    nt += 1;
1860                    format!("#/texts/{}", nt - 1)
1861                }
1862                TreeKind::Group { .. } => {
1863                    ng += 1;
1864                    format!("#/groups/{}", ng - 1)
1865                }
1866                TreeKind::Table { .. } => {
1867                    ntb += 1;
1868                    format!("#/tables/{}", ntb - 1)
1869                }
1870                TreeKind::Picture { .. } => {
1871                    np += 1;
1872                    format!("#/pictures/{}", np - 1)
1873                }
1874                TreeKind::FieldRegion { items } => {
1875                    // A region's marker / key / value parts are text items
1876                    // too, numbered where docling creates them.
1877                    nt += items
1878                        .iter()
1879                        .map(|i| {
1880                            [&i.marker, &i.key, &i.value]
1881                                .iter()
1882                                .filter(|p| p.is_some())
1883                                .count()
1884                        })
1885                        .sum::<usize>();
1886                    nf += 1;
1887                    format!("#/field_regions/{}", nf - 1)
1888                }
1889                TreeKind::KeyValueGraph { .. } => {
1890                    nk += 1;
1891                    format!("#/key_value_items/{}", nk - 1)
1892                }
1893            };
1894            refs.push(r);
1895        }
1896        let ref_of = |id: usize| ref_value(refs[id].as_str());
1897        for (id, item) in tree.items.iter().enumerate() {
1898            if item.deleted {
1899                continue;
1900            }
1901            let parent = item.parent.map_or("#/body", |p| refs[p].as_str());
1902            // A deleted item has no ref; one still listed as a child (a stale
1903            // backend link) is left out rather than written as `"$ref": ""`,
1904            // which docling-core rejects on load (#527).
1905            let children: Vec<Value> = item
1906                .children
1907                .iter()
1908                .filter(|&&c| !tree.items[c].deleted)
1909                .map(|&c| ref_of(c))
1910                .collect();
1911            let layer = item.layer.map_or("body", |l| l.value());
1912            // The item's own provenance, consumed by the writer below
1913            // (`take_prov`); an item without one writes `prov: []`.
1914            self.pending_exact = item.prov.as_ref().map(ExactProv::from);
1915            let self_ref = match &item.kind {
1916                TreeKind::Text {
1917                    label,
1918                    text,
1919                    orig,
1920                    formatting,
1921                    hyperlink,
1922                    level,
1923                    list,
1924                } => {
1925                    // docling's field order: …, text, formatting, hyperlink,
1926                    // then the subclass fields (`level`; `enumerated`, `marker`).
1927                    let mut tail = serde_json::Map::new();
1928                    if let Some(f) = formatting {
1929                        tail.insert("formatting".into(), formatting_json(f));
1930                    }
1931                    if let Some(h) = hyperlink {
1932                        tail.insert("hyperlink".into(), json!(h));
1933                    }
1934                    if let Some(l) = level {
1935                        tail.insert("level".into(), json!(l));
1936                    }
1937                    if let Some(l) = list {
1938                        tail.insert("enumerated".into(), json!(l.enumerated));
1939                        tail.insert("marker".into(), json!(l.marker));
1940                    }
1941                    let r = format!("#/texts/{}", self.texts.len());
1942                    let prov = self.take_prov(text.chars().count());
1943                    let mut item_json = json!({
1944                        "self_ref": r,
1945                        "parent": { "$ref": parent },
1946                        "children": children,
1947                        "content_layer": layer,
1948                        "label": label,
1949                        "prov": prov,
1950                    });
1951                    // docling's `comments` back-refs sit between `prov` and
1952                    // `orig`, and are written only when set.
1953                    if !item.comments.is_empty() {
1954                        item_json["comments"] =
1955                            Value::Array(item.comments.iter().map(|&c| ref_of(c)).collect());
1956                    }
1957                    // `DocItem.source`, likewise only when set: a WebVTT
1958                    // cue's `TrackSource`, whose `None` fields are omitted.
1959                    if let Some(track) = &item.source {
1960                        item_json["source"] = json!([track_json(track)]);
1961                    }
1962                    merge(
1963                        &mut item_json,
1964                        json!({
1965                            "orig": orig.as_deref().unwrap_or(text),
1966                            "text": text,
1967                        }),
1968                    );
1969                    merge(&mut item_json, Value::Object(tail));
1970                    if self.note_keys {
1971                        if !item.notes.is_empty() {
1972                            item_json["_notes"] = Value::Array(
1973                                item.notes
1974                                    .iter()
1975                                    .map(|n| json!([n.offset, n.text]))
1976                                    .collect(),
1977                            );
1978                        }
1979                        if item.note_body {
1980                            item_json["_note_body"] = json!(true);
1981                        }
1982                        if !item.anchors.is_empty() {
1983                            item_json["_anchors"] = json!(item.anchors);
1984                        }
1985                        if let Some(number) = &item.number {
1986                            item_json["_number"] = json!(number);
1987                        }
1988                        if let Some(rev) = &item.revision {
1989                            let mut r = serde_json::Map::new();
1990                            r.insert("kind".into(), json!(rev.kind.as_str()));
1991                            if let Some(a) = &rev.author {
1992                                r.insert("author".into(), json!(a));
1993                            }
1994                            if let Some(d) = &rev.date {
1995                                r.insert("date".into(), json!(d));
1996                            }
1997                            item_json["_revision"] = Value::Object(r);
1998                        }
1999                    }
2000                    self.texts.push(Item::json(item_json));
2001                    r
2002                }
2003                TreeKind::Code {
2004                    text,
2005                    orig,
2006                    language,
2007                    formatting,
2008                    hyperlink,
2009                    captions,
2010                } => {
2011                    let r = format!("#/texts/{}", self.texts.len());
2012                    let prov = self.take_prov(text.chars().count());
2013                    let mut item_json = json!({
2014                        "self_ref": r,
2015                        "parent": { "$ref": parent },
2016                        "children": children,
2017                        "content_layer": layer,
2018                        "label": "code",
2019                        "prov": prov,
2020                    });
2021                    if !item.comments.is_empty() {
2022                        item_json["comments"] =
2023                            Value::Array(item.comments.iter().map(|&c| ref_of(c)).collect());
2024                    }
2025                    merge(
2026                        &mut item_json,
2027                        json!({
2028                            "orig": orig.as_deref().unwrap_or(text),
2029                            "text": text,
2030                        }),
2031                    );
2032                    if let Some(f) = formatting {
2033                        item_json["formatting"] = formatting_json(f);
2034                    }
2035                    if let Some(h) = hyperlink {
2036                        item_json["hyperlink"] = json!(h);
2037                    }
2038                    merge(
2039                        &mut item_json,
2040                        json!({
2041                            "captions": captions.iter().map(|&c| ref_of(c)).collect::<Vec<_>>(),
2042                            "references": [],
2043                            "footnotes": [],
2044                            "code_language": code_language(language.as_deref()),
2045                        }),
2046                    );
2047                    self.texts.push(Item::json(item_json));
2048                    r
2049                }
2050                TreeKind::Group { label, name } => {
2051                    self.pending_exact = None;
2052                    let r = format!("#/groups/{}", self.groups.len());
2053                    self.groups.push(json!({
2054                        "self_ref": r,
2055                        "parent": { "$ref": parent },
2056                        "children": children,
2057                        "content_layer": layer,
2058                        "name": name,
2059                        "label": label,
2060                    }));
2061                    r
2062                }
2063                TreeKind::Table {
2064                    table,
2065                    rich_cells,
2066                    captions,
2067                    footnotes,
2068                } => {
2069                    // docling's raw cell text: nothing to unescape or strip.
2070                    let r = self.add_table_with(table, parent, true);
2071                    let idx = ref_index(&r).expect("table ref");
2072                    let t = &mut self.tables[idx];
2073                    t.item["children"] = Value::Array(children);
2074                    t.item["content_layer"] = json!(layer);
2075                    t.item["captions"] =
2076                        Value::Array(captions.iter().map(|&c| ref_of(c)).collect());
2077                    t.item["footnotes"] =
2078                        Value::Array(footnotes.iter().map(|&c| ref_of(c)).collect());
2079                    // A `RichTableCell` is the plain cell plus a `ref` to the
2080                    // group holding its content — on `table_cells` only; the
2081                    // derived `grid` shows plain cells.
2082                    for &(row, col, group) in rich_cells {
2083                        let cell_ref = ref_of(group);
2084                        for c in t.data.cells.iter_mut() {
2085                            if c.start_row == row && c.start_col == col {
2086                                c.cell_ref = Some(Box::new(cell_ref.clone()));
2087                            }
2088                        }
2089                    }
2090                    r
2091                }
2092                TreeKind::Picture {
2093                    captions,
2094                    image,
2095                    classification,
2096                    extra_classes,
2097                    description,
2098                    confidence,
2099                    chart,
2100                    dpi,
2101                } => {
2102                    // A chart's meta: the kind as the one classification
2103                    // prediction (pydantic's field order puts `confidence`
2104                    // first when present), then the reconstructed data grid
2105                    // (#405).
2106                    let mut meta = classification.as_ref().map(|c| {
2107                        let mut pred = serde_json::Map::new();
2108                        if let Some(conf) = confidence {
2109                            pred.insert("confidence".into(), json!(conf));
2110                        }
2111                        pred.insert("class_name".into(), json!(c));
2112                        let mut preds = vec![Value::Object(pred)];
2113                        preds.extend(extra_classes.iter().map(|c| json!({ "class_name": c })));
2114                        json!({ "classification": { "predictions": preds } })
2115                    });
2116                    if let (Some(m), Some(t)) = (meta.as_mut(), chart) {
2117                        if !t.rows.is_empty() {
2118                            m["tabular_chart"] =
2119                                object([("chart_data", table_data(t).into_value())]);
2120                        }
2121                    }
2122                    // The OCR description (#645) goes first in the meta —
2123                    // `PictureMeta` field order — and as the annotation the
2124                    // flat node writes (see `description_meta`).
2125                    if let Some(desc) = description {
2126                        let mut d = description_meta(desc);
2127                        let mut merged = Map::new();
2128                        merged.insert("description".into(), d["description"].take());
2129                        if let Some(Value::Object(rest)) = meta {
2130                            merged.extend(rest);
2131                        }
2132                        merged.insert("annotations".into(), d["annotations"].take());
2133                        meta = Some(Value::Object(merged));
2134                    }
2135                    // The source of a picture no engine rendered (a LaTeX
2136                    // `tikzpicture`): `PictureMeta.code`.
2137                    if let Some((text, language)) = &item.code_meta {
2138                        let code = json!({ "text": text, "language": language });
2139                        match meta.as_mut() {
2140                            Some(Value::Object(m)) => {
2141                                m.insert("code".into(), code);
2142                            }
2143                            _ => meta = Some(json!({ "code": code })),
2144                        }
2145                    }
2146                    let prov = self.take_prov(0);
2147                    let r = self.push_picture(
2148                        prov,
2149                        captions.iter().map(|&c| ref_of(c)).collect(),
2150                        children,
2151                        image.as_ref(),
2152                        meta,
2153                        parent,
2154                    );
2155                    if let Some(idx) = ref_index(&r) {
2156                        self.pictures[idx]["content_layer"] = json!(layer);
2157                        // The image's dpi is the file's when the backend read
2158                        // it (python-pptx does); the default 72 otherwise.
2159                        if let (Some(dpi), Some(img)) = (dpi, self.pictures[idx].get_mut("image")) {
2160                            img["dpi"] = json!(dpi);
2161                        }
2162                    }
2163                    r
2164                }
2165                TreeKind::FieldRegion { items } => {
2166                    self.pending_exact = None;
2167                    let r = self.add_field_region(items, parent);
2168                    if let Some(region) = self.field_regions.last_mut() {
2169                        region["content_layer"] = json!(layer);
2170                    }
2171                    r
2172                }
2173                TreeKind::KeyValueGraph { cells, links } => {
2174                    self.pending_exact = None;
2175                    let r = self.add_key_value_graph(cells, links, parent);
2176                    if let Some(item) = self.key_value_items.last_mut() {
2177                        item["content_layer"] = json!(layer);
2178                    }
2179                    r
2180                }
2181            };
2182            debug_assert_eq!(self_ref, refs[id], "tree item {id} numbered out of order");
2183            // An item over several boxes (a DocLang thread read back, #1207):
2184            // one `prov` entry per box.
2185            if !item.more_prov.is_empty() {
2186                if let Some(provs) = self
2187                    .item_mut(&self_ref)
2188                    .and_then(|v| v.get_mut("prov"))
2189                    .and_then(Value::as_array_mut)
2190                {
2191                    for p in &item.more_prov {
2192                        let r2 = round2;
2193                        let [l, t, r, b] = p.bbox;
2194                        let slot = ProvSlot::One {
2195                            page_no: p.page_no,
2196                            bbox: [r2(l), r2(t), r2(r), r2(b)],
2197                            bottom_left: p.bottom_left,
2198                            charspan: p.charspan,
2199                        };
2200                        if let Value::Array(mut one) = slot.to_value() {
2201                            provs.append(&mut one);
2202                        }
2203                    }
2204                }
2205            }
2206            // A float's own footnotes (`FloatingItem.footnotes`).
2207            if !item.footnotes.is_empty() {
2208                let notes: Vec<Value> = item
2209                    .footnotes
2210                    .iter()
2211                    .filter(|&&f| !tree.items[f].deleted)
2212                    .map(|&f| ref_of(f))
2213                    .collect();
2214                if let Some(v) = self.item_mut(&self_ref) {
2215                    v["footnotes"] = Value::Array(notes);
2216                }
2217            }
2218        }
2219        tree.body
2220            .iter()
2221            .filter(|&&c| !tree.items[c].deleted)
2222            .map(|&c| ref_of(c))
2223            .collect()
2224    }
2225
2226    fn add_node(&mut self, node: &Node, parent: &str) -> Option<String> {
2227        match node {
2228            Node::Heading { level: 1, text } => {
2229                Some(self.add_text("title", text, parent, json!({})))
2230            }
2231            Node::Heading { level, text } => Some(self.add_text(
2232                "section_header",
2233                text,
2234                parent,
2235                json!({ "level": level.saturating_sub(1) }),
2236            )),
2237            Node::Caption { text, href } => {
2238                let extra = match href {
2239                    Some(url) => json!({ "hyperlink": url }),
2240                    None => json!({}),
2241                };
2242                Some(self.add_text("caption", text, parent, extra))
2243            }
2244            // A marked PDF item (#1005, docling's `ScriptPositionModel._apply`):
2245            // the item keeps its place and its `prov`, its text moves into an
2246            // inline group of the runs (see `link_script_runs`).
2247            Node::ScriptText { inner, runs } => {
2248                let label = match inner.as_ref() {
2249                    Node::LabeledText { label, .. } => label.clone(),
2250                    _ => "text".to_string(),
2251                };
2252                let r = self.add_node(inner, parent)?;
2253                let link = runs.iter().find_map(|run| run.hyperlink.clone());
2254                if let Some(obj) = self.item_mut(&r).and_then(Value::as_object_mut) {
2255                    obj.insert("orig".into(), json!(""));
2256                    obj.insert("text".into(), json!(""));
2257                    // The item keeps its own link, as docling's does.
2258                    if let Some(url) = link {
2259                        obj.insert("hyperlink".into(), json!(url));
2260                    }
2261                }
2262                self.pending_scripts.push((r.clone(), runs.clone(), label));
2263                Some(r)
2264            }
2265            // A PDF footnote: docling's own label, and its link as the item's
2266            // `hyperlink` rather than Markdown baked into the text.
2267            Node::LabeledText { label, text, href } => {
2268                let extra = match href {
2269                    Some(url) => json!({ "hyperlink": url }),
2270                    None => json!({}),
2271                };
2272                Some(self.add_text(label, text, parent, extra))
2273            }
2274            Node::Paragraph { text } | Node::ListText { text, .. } => {
2275                // A whole-paragraph display equation is a formula item (docling
2276                // wraps it in `$$…$$` and, unlike a text item, never escapes it).
2277                let t = text.trim();
2278                match t.strip_prefix("$$").and_then(|s| s.strip_suffix("$$")) {
2279                    Some(inner) if !inner.is_empty() => Some(self.add_formula(inner, parent)),
2280                    _ => Some(self.add_text("text", text, parent, json!({}))),
2281                }
2282            }
2283            Node::CheckboxItem { checked, text } => {
2284                // docling's checkbox item: the `checkbox_selected` /
2285                // `checkbox_unselected` label carries the state and the text
2286                // is the bare option label (right_to_left_03's `خير`,
2287                // docx_checkboxes' `Orange juice`). The `- [x]` task-list
2288                // marker is Markdown's rendering of it, not item text (#609).
2289                let label = if *checked {
2290                    "checkbox_selected"
2291                } else {
2292                    "checkbox_unselected"
2293                };
2294                Some(self.add_text(label, text, parent, json!({})))
2295            }
2296            Node::Code {
2297                language,
2298                text,
2299                orig,
2300                ..
2301            } => Some(self.add_code(text, language.as_deref(), orig.as_deref(), parent)),
2302            // A CodeFormula-decoded display formula: `text` carries the LaTeX,
2303            // `orig` the raw glyph extraction (docling's enriched shape).
2304            Node::Formula {
2305                latex,
2306                orig,
2307                location,
2308            } => {
2309                self.adopt_loc(*location);
2310                Some(self.add_formula_item(latex, orig, parent))
2311            }
2312            // docling's notes-layer `comment_section` group holding the
2313            // comment's text item. What the annotated items point at differs
2314            // upstream: the docx backend links the group (so a comment's
2315            // replies group together), everything going through
2316            // docling-core's `add_comment` links the note text itself.
2317            Node::CommentSection {
2318                name,
2319                text,
2320                refs_note_text,
2321                grouped,
2322            } => {
2323                if !*grouped {
2324                    // docling-core's bare `add_comment`: the note text sits
2325                    // directly under the parent and is what the back-refs
2326                    // point at.
2327                    let child =
2328                        self.add_text("text", text, parent, json!({ "content_layer": "notes" }));
2329                    self.comment_groups.push(child.clone());
2330                    return Some(child);
2331                }
2332                if let Some((_, self_ref)) = self
2333                    .last_comment_section
2334                    .as_ref()
2335                    .filter(|(n, _)| n == name)
2336                    .cloned()
2337                {
2338                    // Another message of the same thread: a further note in
2339                    // the group already open for this cell.
2340                    let child =
2341                        self.add_text("text", text, &self_ref, json!({ "content_layer": "notes" }));
2342                    if let Some(children) =
2343                        self.groups[group_index(&self_ref)]["children"].as_array_mut()
2344                    {
2345                        children.push(ref_value(child.as_str()));
2346                    }
2347                    self.comment_groups.push(if *refs_note_text {
2348                        child
2349                    } else {
2350                        self_ref.clone()
2351                    });
2352                    // The group is already its parent's child: listing it
2353                    // again put a thread's group in the body once per message.
2354                    return None;
2355                }
2356                let self_ref = format!("#/groups/{}", self.groups.len());
2357                self.groups.push(Value::Null);
2358                let child =
2359                    self.add_text("text", text, &self_ref, json!({ "content_layer": "notes" }));
2360                self.groups[group_index(&self_ref)] = json!({
2361                    "self_ref": self_ref,
2362                    "parent": { "$ref": parent },
2363                    "children": [{ "$ref": child }],
2364                    "content_layer": "notes",
2365                    "name": name,
2366                    "label": "comment_section",
2367                });
2368                self.last_comment_section = Some((name.clone(), self_ref.clone()));
2369                self.comment_groups.push(if *refs_note_text {
2370                    child
2371                } else {
2372                    self_ref.clone()
2373                });
2374                Some(self_ref)
2375            }
2376            // The annotation itself is a cross-reference: emit the item, then
2377            // remember it so the group refs can be filled in at the end.
2378            Node::Commented { comments, inner } => {
2379                let item = self.add_node(inner, parent)?;
2380                if !comments.is_empty() {
2381                    self.pending_comments.push((item.clone(), comments.clone()));
2382                }
2383                Some(item)
2384            }
2385            Node::Table(t) => Some(self.add_table(t, parent)),
2386            Node::Picture {
2387                caption,
2388                caption_href,
2389                image,
2390                classification,
2391                description,
2392                caption_parent,
2393                caption_location,
2394            } => Some(self.add_picture(
2395                caption.as_deref(),
2396                caption_href.as_deref(),
2397                image.as_ref(),
2398                picture_meta(classification.as_deref(), description.as_ref()),
2399                parent,
2400                (*caption_parent, *caption_location),
2401            )),
2402            // A chart is a picture item in the JSON with docling's chart
2403            // meta — `classification` (the chart kind, as the one prediction)
2404            // and `tabular_chart.chart_data`, the series reconstructed as a
2405            // `TableData` (#405) — and no image payload.
2406            Node::Chart {
2407                kind,
2408                table,
2409                caption,
2410                location,
2411            } => {
2412                self.adopt_loc(*location);
2413                let mut meta = json!({
2414                    "classification": { "predictions": [{ "class_name": kind }] },
2415                });
2416                if !table.rows.is_empty() {
2417                    meta["tabular_chart"] =
2418                        object([("chart_data", table_data(table).into_value())]);
2419                }
2420                // docling's office backends add the chart's title as a caption
2421                // item of the *container* (the sheet group, the slide), listed
2422                // before the picture that references it, with the chart's own
2423                // box and a charspan over the caption text — not as a child
2424                // of the picture, which is where a PDF caption lives.
2425                let mut captions = Vec::new();
2426                if let Some(cap) = caption.as_deref().filter(|c| !c.is_empty()) {
2427                    let prov = self.prov_slot(unescape_text(cap).chars().count(), true);
2428                    let cap_ref = self.add_text_with("caption", cap, parent, json!({}), prov);
2429                    self.pending_siblings.push(ref_value(cap_ref.as_str()));
2430                    captions.push(ref_value(cap_ref));
2431                }
2432                let prov = self.take_prov(0);
2433                Some(self.push_picture(prov, captions, Vec::new(), None, Some(meta), parent))
2434            }
2435            // A DocLang-only node is omitted from the JSON body.
2436            Node::DoclangOnly(_) => None,
2437            Node::Group {
2438                label,
2439                name,
2440                layer,
2441                children,
2442            } => Some(self.add_group(label, name.as_deref(), *layer, children, parent)),
2443            Node::FieldRegion { items } => Some(self.add_field_region(items, parent)),
2444            Node::KeyValueGraph { cells, links } => {
2445                Some(self.add_key_value_graph(cells, links, parent))
2446            }
2447            // A rich inline group is a text item over its Markdown text; the
2448            // structured runs are DocLang-only, so the JSON matches a paragraph.
2449            Node::InlineGroup { md_text, .. } => {
2450                Some(self.add_text("text", md_text, parent, json!({})))
2451            }
2452            // A plain-text backend dump is a single text item over the file body.
2453            Node::TextDump(text) => Some(self.add_text("text", text, parent, json!({}))),
2454            // Speaker notes are content a deck carries, and docling puts them
2455            // in the JSON on their own layer, so a consumer reading only JSON
2456            // can pick them (#402). Page furniture stays out of the flat
2457            // path; a backend that builds docling's item tree (HTML) puts its
2458            // furniture-layer items in the JSON through `write_tree`.
2459            Node::Furniture {
2460                layer: ContentLayer::Notes,
2461                inner,
2462            } => {
2463                let item = self.add_node(inner, parent)?;
2464                self.set_layer(&item, "notes");
2465                Some(item)
2466            }
2467            Node::Furniture { .. } => None,
2468            // PDF page headers and footers: docling writes them as body-parented
2469            // `page_header`/`page_footer` text items on the furniture layer, so a
2470            // JSON consumer can read running headers (printed page ids, dates).
2471            Node::PageFurniture {
2472                footer,
2473                location,
2474                text,
2475            } => {
2476                if self.cur_page > 0 {
2477                    self.pending_loc = Some(*location);
2478                }
2479                let label = if *footer {
2480                    "page_footer"
2481                } else {
2482                    "page_header"
2483                };
2484                let item = self.add_text(label, text, parent, json!({}));
2485                self.pending_loc = None;
2486                self.set_layer(&item, "furniture");
2487                Some(item)
2488            }
2489            // A labelled furniture paragraph (a `.doc` header / footer or
2490            // note body, #535): the item docling's office backends write.
2491            Node::FurnitureText { label, text } => {
2492                let item = self.add_text(label, text, parent, json!({}));
2493                self.set_layer(&item, "furniture");
2494                Some(item)
2495            }
2496            // A PDF picture's contained text (docling's `_add_child_elements`):
2497            // items parented to the picture just written, listed after its
2498            // caption in that picture's `children`.
2499            Node::PictureChildren(children) => {
2500                let pic = self.pictures.len().checked_sub(1)?;
2501                let pic_ref = format!("#/pictures/{pic}");
2502                let refs = self.walk_into(children, &pic_ref);
2503                if let Some(list) = self.pictures[pic]["children"].as_array_mut() {
2504                    list.extend(refs.into_iter().map(Child::into_value));
2505                }
2506                None
2507            }
2508            // A location wrapper turns into the wrapped item's `prov` entry —
2509            // but only on pages the PDF paths described with a PageInfo marker
2510            // (other geometry-bearing backends, e.g. PPTX shapes, keep their
2511            // pre-#171 provenance-less JSON until they emit markers too).
2512            Node::Located { location, inner } => {
2513                if self.cur_page > 0 {
2514                    self.pending_loc = Some(*location);
2515                }
2516                let r = self.add_node(inner, parent);
2517                self.pending_loc = None;
2518                r
2519            }
2520            Node::Anchor { id } => {
2521                self.pending_anchors.push(id.clone());
2522                None
2523            }
2524            Node::Track { track, cue, inner } => {
2525                self.pending_track = Some((track.clone(), cue.clone()));
2526                let r = self.add_node(inner, parent);
2527                self.pending_track = None;
2528                r
2529            }
2530            Node::Prov {
2531                page_no,
2532                bbox,
2533                charspan,
2534                bottom_left,
2535                inner,
2536                ..
2537            } => {
2538                self.pending_exact = Some(ExactProv {
2539                    page_no: *page_no,
2540                    bbox: bbox.map(f64::from),
2541                    bottom_left: *bottom_left,
2542                    charspan: *charspan,
2543                });
2544                let r = self.add_node(inner, parent);
2545                self.pending_exact = None;
2546                r
2547            }
2548            // Page breaks are DocLang-only; docling omits them from the JSON body.
2549            Node::PageBreak => None,
2550            // A continuation fragment of the item just written (#1127): its box
2551            // is on a later page, resolved when that page's marker comes.
2552            Node::ProvContinuation {
2553                location,
2554                prev_end,
2555                span,
2556                page_skip,
2557                exact,
2558            } => {
2559                // A docling-JSON input's further `prov` entry (#1207): written
2560                // as read, at once.
2561                if let (Some(idx), Some(p)) = (self.last_text, exact) {
2562                    let r2 = round2;
2563                    let [l, t, r, b] = p.bbox.map(f64::from);
2564                    let entry = object([
2565                        ("page_no", p.page_no.into()),
2566                        (
2567                            "bbox",
2568                            object([
2569                                ("l", r2(l).into()),
2570                                ("t", r2(t).into()),
2571                                ("r", r2(r).into()),
2572                                ("b", r2(b).into()),
2573                                ("coord_origin", ProvSlot::origin(p.bottom_left).into()),
2574                            ]),
2575                        ),
2576                        ("charspan", json!([span[0], span[1]])),
2577                    ]);
2578                    if let Some(provs) = self
2579                        .texts
2580                        .get_mut(idx)
2581                        .map(|it| it.value_mut(idx))
2582                        .and_then(|item| item.get_mut("prov"))
2583                        .and_then(Value::as_array_mut)
2584                        .filter(|provs| !provs.is_empty())
2585                    {
2586                        if let Some(last) = provs.last_mut() {
2587                            last["charspan"][1] = json!(*prev_end);
2588                        }
2589                        provs.push(entry);
2590                    }
2591                    return None;
2592                }
2593                if let Some(idx) = self.last_text.filter(|_| self.cur_page > 0) {
2594                    self.pending_continuations.push(PendingContinuation {
2595                        item: idx,
2596                        skip: *page_skip,
2597                        location: *location,
2598                        prev_end: *prev_end,
2599                        span: *span,
2600                    });
2601                }
2602                None
2603            }
2604            // The page marker: record the page's number and size for the
2605            // `pages` map, and denormalize every following location against it.
2606            Node::PageInfo {
2607                page_no,
2608                width,
2609                height,
2610            } => {
2611                self.cur_page = *page_no;
2612                self.cur_w = *width as f64;
2613                self.cur_h = *height as f64;
2614                if *page_no > 0 {
2615                    self.pages.push((*page_no, self.cur_w, self.cur_h));
2616                }
2617                self.resolve_continuations();
2618                None
2619            }
2620            // Handled by `add_list` in `walk`.
2621            Node::ListItem { .. } => None,
2622        }
2623    }
2624
2625    /// A form key-value region: `field_regions/N` holds the region, each field is
2626    /// a `field_items/M` whose children are its `marker` / `field_key` /
2627    /// `field_value` texts (absent parts are simply omitted).
2628    fn add_field_region(&mut self, items: &[crate::FieldItem], parent: &str) -> String {
2629        let self_ref = format!("#/field_regions/{}", self.field_regions.len());
2630        self.field_regions.push(Value::Null);
2631        let region_index = self.field_regions.len() - 1;
2632        let mut item_refs = Vec::new();
2633        for item in items {
2634            item_refs.push(ref_value(self.add_field_item(item, &self_ref)));
2635        }
2636        self.field_regions[region_index] = json!({
2637            "self_ref": self_ref,
2638            "parent": { "$ref": parent },
2639            "children": item_refs,
2640            "content_layer": "body",
2641            "label": "field_region",
2642            "prov": [],
2643        });
2644        self_ref
2645    }
2646
2647    /// A `KeyValueItem`: docling's `GraphData` written cell for cell and link
2648    /// for link (`key_value_items/N`), the item itself childless and without
2649    /// provenance, the way the XBRL backend creates it.
2650    fn add_key_value_graph(
2651        &mut self,
2652        cells: &[crate::GraphCell],
2653        links: &[crate::GraphLink],
2654        parent: &str,
2655    ) -> String {
2656        let self_ref = format!("#/key_value_items/{}", self.key_value_items.len());
2657        let cells: Vec<Value> = cells
2658            .iter()
2659            .map(|c| {
2660                json!({
2661                    "label": c.label,
2662                    "cell_id": c.cell_id,
2663                    "text": c.text,
2664                    "orig": c.orig,
2665                })
2666            })
2667            .collect();
2668        let links: Vec<Value> = links
2669            .iter()
2670            .map(|l| {
2671                json!({
2672                    "label": l.label,
2673                    "source_cell_id": l.source_cell_id,
2674                    "target_cell_id": l.target_cell_id,
2675                })
2676            })
2677            .collect();
2678        self.key_value_items.push(json!({
2679            "self_ref": self_ref,
2680            "parent": { "$ref": parent },
2681            "children": [],
2682            "content_layer": "body",
2683            "label": "key_value_region",
2684            "prov": [],
2685            "captions": [],
2686            "references": [],
2687            "footnotes": [],
2688            "graph": { "cells": cells, "links": links },
2689        }));
2690        self_ref
2691    }
2692
2693    fn add_field_item(&mut self, item: &crate::FieldItem, parent: &str) -> String {
2694        let self_ref = format!("#/field_items/{}", self.field_items.len());
2695        self.field_items.push(Value::Null);
2696        let item_index = self.field_items.len() - 1;
2697        let mut child_refs = Vec::new();
2698        for (label, text) in [
2699            ("marker", &item.marker),
2700            ("field_key", &item.key),
2701            ("field_value", &item.value),
2702        ] {
2703            if let Some(text) = text {
2704                // A value's `kind` (docling's `read_only` / `fillable`)
2705                // follows its text.
2706                let extra = match (label, &item.value_kind) {
2707                    ("field_value", Some(kind)) => json!({ "kind": kind }),
2708                    _ => json!({}),
2709                };
2710                child_refs.push(ref_value(self.add_text(label, text, &self_ref, extra)));
2711            }
2712        }
2713        self.field_items[item_index] = json!({
2714            "self_ref": self_ref,
2715            "parent": { "$ref": parent },
2716            "children": child_refs,
2717            "content_layer": "body",
2718            "label": "field_item",
2719            "prov": [],
2720        });
2721        self_ref
2722    }
2723
2724    /// Move an already-emitted item onto a content layer. Notes are single
2725    /// text items today; a deeper notes subtree would need its children moved
2726    /// too, and no backend builds one.
2727    fn set_layer(&mut self, self_ref: &str, layer: &str) {
2728        if let Some(item) = self.item_mut(self_ref) {
2729            item["content_layer"] = json!(layer);
2730        }
2731    }
2732
2733    fn add_text(&mut self, label: &str, text: &str, parent: &str, extra: Value) -> String {
2734        let prov = self.take_prov_slot(unescape_text(text).chars().count());
2735        self.add_text_with(label, text, parent, extra, prov)
2736    }
2737
2738    /// [`Self::add_text`] with an explicit `prov` (a chart caption shares the
2739    /// chart's box without consuming it).
2740    fn add_text_with(
2741        &mut self,
2742        label: &str,
2743        text: &str,
2744        parent: &str,
2745        extra: Value,
2746        prov: ProvSlot,
2747    ) -> String {
2748        let index = self.texts.len();
2749        self.last_text = Some(index);
2750        let self_ref = format!("#/texts/{index}");
2751        // A [`Node::Track`] item is docling's ASR text item (#614): the
2752        // segment's words as `text`, its timing as `source` — the `[time: …]`
2753        // prefix the wrapped paragraph shows is Markdown's alone. It carries a
2754        // field the compact [`TextItem`] doesn't, so it is built as JSON.
2755        let mut item = match self.pending_track.take() {
2756            None => Item::Text(Box::new(TextItem {
2757                parent: parent.into(),
2758                label: label.into(),
2759                prov,
2760                text: unescape_text(text).into(),
2761            })),
2762            Some((track, cue)) => {
2763                let mut m = serde_json::Map::with_capacity(9);
2764                m.insert("self_ref".into(), Value::String(self_ref.clone()));
2765                m.insert("parent".into(), ref_value(parent));
2766                m.insert("children".into(), Value::Array(Vec::new()));
2767                m.insert("content_layer".into(), "body".into());
2768                m.insert("label".into(), label.into());
2769                m.insert("prov".into(), prov.to_value());
2770                // `DocItem.source` follows `prov` (docling's field order).
2771                m.insert("source".into(), Value::Array(vec![track_json(&track)]));
2772                m.insert("orig".into(), Value::String(cue.clone()));
2773                m.insert("text".into(), Value::String(cue));
2774                Item::json(Value::Object(m))
2775            }
2776        };
2777        if extra.as_object().is_some_and(|e| !e.is_empty()) {
2778            merge(item.value_mut(index), extra);
2779        }
2780        // The link destinations met before this item (#852), on the Pandoc
2781        // path only — docling's model has no field for them.
2782        let anchors = std::mem::take(&mut self.pending_anchors);
2783        if self.note_keys && !anchors.is_empty() {
2784            merge(item.value_mut(index), json!({ "_anchors": anchors }));
2785        }
2786        self.texts.push(item);
2787        self_ref
2788    }
2789
2790    /// A display-math formula item. `latex` is the raw content (no `$$`); docling
2791    /// re-wraps it and never escapes it.
2792    fn add_formula(&mut self, latex: &str, parent: &str) -> String {
2793        let self_ref = format!("#/texts/{}", self.texts.len());
2794        let prov = self.take_prov(latex.chars().count());
2795        self.texts.push(Item::json(json!({
2796            "self_ref": self_ref,
2797            "parent": { "$ref": parent },
2798            "children": [],
2799            "content_layer": "body",
2800            "label": "formula",
2801            "prov": prov,
2802            "orig": latex,
2803            "text": latex,
2804        })));
2805        self_ref
2806    }
2807
2808    /// A CodeFormula-enriched display formula: `text` is the model's LaTeX
2809    /// while `orig` keeps the raw glyph extraction (docling's enriched shape;
2810    /// the plain [`Self::add_formula`] above sets both to the same string).
2811    fn add_formula_item(&mut self, latex: &str, orig: &str, parent: &str) -> String {
2812        let self_ref = format!("#/texts/{}", self.texts.len());
2813        // docling stamps the provenance when the item is assembled, from the
2814        // region's raw text: the charspan is `orig`'s length, decoded or not
2815        // (the enriched groundtruth: `text` 19 characters, charspan [0, 11]).
2816        let prov = self.take_prov(orig.chars().count());
2817        self.texts.push(Item::json(json!({
2818            "self_ref": self_ref,
2819            "parent": { "$ref": parent },
2820            "children": [],
2821            "content_layer": "body",
2822            "label": "formula",
2823            "prov": prov,
2824            "orig": orig,
2825            "text": latex,
2826        })));
2827        self_ref
2828    }
2829
2830    fn add_code(
2831        &mut self,
2832        text: &str,
2833        language: Option<&str>,
2834        orig: Option<&str>,
2835        parent: &str,
2836    ) -> String {
2837        let self_ref = format!("#/texts/{}", self.texts.len());
2838        let raw = unescape_text(text);
2839        let prov = self.take_prov(raw.chars().count());
2840        self.texts.push(Item::json(json!({
2841            "self_ref": self_ref,
2842            "parent": { "$ref": parent },
2843            "children": [],
2844            "content_layer": "body",
2845            "label": "code",
2846            "prov": prov,
2847            // With code enrichment, `text` is the model's rewrite while `orig`
2848            // keeps the raw extraction; otherwise both are the same string.
2849            "orig": orig.map(unescape_text).unwrap_or_else(|| raw.clone()),
2850            "text": raw,
2851            "captions": [],
2852            "references": [],
2853            "footnotes": [],
2854            "code_language": code_language(language),
2855        })));
2856        self_ref
2857    }
2858
2859    /// Build a list group from a run of (possibly multi-level) list items. A
2860    /// deeper level starts a nested list under the preceding item.
2861    fn add_list(&mut self, items: &[Node], parent: &str) -> String {
2862        let self_ref = format!("#/groups/{}", self.groups.len());
2863        // reserve the slot so nested groups get later indices
2864        self.groups.push(Value::Null);
2865        let base = level_of(&items[0]);
2866        let mut children = Vec::new();
2867        let mut i = 0;
2868        while i < items.len() {
2869            // Empty paragraphs absorbed into the run (blank lines between items)
2870            // are not list items — skip them.
2871            if !matches!(items[i], Node::ListItem { .. }) {
2872                i += 1;
2873                continue;
2874            }
2875            let lvl = level_of(&items[i]);
2876            if lvl > base {
2877                // shouldn't happen at the head; skip defensively
2878                i += 1;
2879                continue;
2880            }
2881            let item_ref = self.add_list_item(&items[i], &self_ref);
2882            // collect any deeper items that nest under this one
2883            let mut j = i + 1;
2884            while j < items.len() && level_of(&items[j]) > base {
2885                j += 1;
2886            }
2887            if j > i + 1 {
2888                let mut nested = Vec::new();
2889                self.add_sibling_lists(&items[i + 1..j], &item_ref, &mut nested);
2890                // the nested list group(s) are children of this item
2891                if let Some(idx) = ref_index(&item_ref) {
2892                    self.texts[idx].value_mut(idx)["children"]
2893                        .as_array_mut()
2894                        .unwrap()
2895                        .extend(nested);
2896                }
2897            }
2898            children.push(ref_value(item_ref));
2899            i = j;
2900        }
2901        self.groups[group_index(&self_ref)] = json!({
2902            "self_ref": self_ref,
2903            "parent": { "$ref": parent },
2904            "children": children,
2905            "content_layer": "body",
2906            "name": "list",
2907            "label": "list",
2908        });
2909        self_ref
2910    }
2911
2912    fn add_list_item(&mut self, node: &Node, parent: &str) -> String {
2913        let Node::ListItem {
2914            ordered,
2915            number,
2916            text,
2917            location,
2918            split,
2919            ..
2920        } = node
2921        else {
2922            unreachable!()
2923        };
2924        self.adopt_loc(*location);
2925        let self_ref = format!("#/texts/{}", self.texts.len());
2926        // A page pipeline's item (PDF) is written as docling's
2927        // `ListItemMarkerProcessor` leaves it: `orig` with the marker, `text`
2928        // without, the marker itself, `enumerated` for any numbered one.
2929        let (orig, raw, enumerated, marker) = match split.as_deref() {
2930            Some(s) => (
2931                s.orig.clone(),
2932                s.text.clone(),
2933                s.enumerated,
2934                s.marker.clone(),
2935            ),
2936            None => {
2937                let raw = unescape_text(text);
2938                let marker = if *ordered {
2939                    format!("{number}.")
2940                } else {
2941                    "-".to_string()
2942                };
2943                (raw.clone(), raw, *ordered, marker)
2944            }
2945        };
2946        let prov = self.take_prov(orig.chars().count());
2947        self.texts.push(Item::json(json!({
2948            "self_ref": self_ref,
2949            "parent": { "$ref": parent },
2950            "children": [],
2951            "content_layer": "body",
2952            "label": "list_item",
2953            "prov": prov,
2954            "orig": orig,
2955            "text": raw,
2956            "enumerated": enumerated,
2957            "marker": marker,
2958        })));
2959        self_ref
2960    }
2961
2962    fn add_table(&mut self, t: &Table, parent: &str) -> String {
2963        self.add_table_with(t, parent, false)
2964    }
2965
2966    /// [`Self::add_table`]; `raw` cell text is written verbatim (see
2967    /// [`table_data_with`]).
2968    fn add_table_with(&mut self, t: &Table, parent: &str, raw: bool) -> String {
2969        let self_ref = format!("#/tables/{}", self.tables.len());
2970        self.adopt_loc(t.location);
2971        let prov = self.take_prov(0);
2972        // The caption is a separate text item the table references (docling's
2973        // `TableItem.captions`), added before the grid so its box isn't
2974        // inherited by a later item.
2975        let (captions, children) = match t.caption.as_deref().filter(|c| !c.is_empty()) {
2976            Some(cap) => self.add_caption(
2977                cap,
2978                json!({}),
2979                &self_ref,
2980                parent,
2981                (t.caption_parent, t.caption_location),
2982            ),
2983            None => (Vec::new(), Vec::new()),
2984        };
2985        // docling-core#675 (#1009): each footnote is a `footnote` text item
2986        // under the table, added after it (docling's backends attach notes
2987        // once the table exists) and listed in its `footnotes`.
2988        // The item-tree path (`raw`) writes its own footnote items.
2989        let (mut children, mut footnotes) = (children, Vec::new());
2990        for note in t.footnotes.iter().filter(|n| !raw && !n.is_empty()) {
2991            let r = ref_value(self.add_text("footnote", note, &self_ref, json!({})));
2992            children.push(r.clone());
2993            footnotes.push(r);
2994        }
2995        let mut data = table_data_with(t, raw);
2996        if !raw {
2997            self.add_cell_pictures(t, &self_ref, &mut data, &mut children);
2998        }
2999        let item = json!({
3000            "self_ref": self_ref,
3001            "parent": { "$ref": parent },
3002            "children": children,
3003            "content_layer": "body",
3004            // docling's `DocItemLabel.DOCUMENT_INDEX` for a table of
3005            // contents (#1091), a plain `table` otherwise.
3006            "label": if t.document_index { "document_index" } else { "table" },
3007            "prov": prov,
3008            "captions": captions,
3009            "references": [],
3010            "footnotes": footnotes,
3011            // The typed `data` takes this stand-in's place on output.
3012            "data": null,
3013            "annotations": [],
3014        });
3015        self.tables.push(TableItem { item, data });
3016        self_ref
3017    }
3018
3019    /// The pictures placed in a table's cells (the XLSX "Place in Cell"
3020    /// image, docling#5015) and the rich cells of a [`crate::rich_cell_group`]
3021    /// (#1119): a cell whose blocks are exactly one
3022    /// [`Node::Prov`]-wrapped picture is docling's `RichTableCell` over a
3023    /// picture item — the picture is the table's child, the cell keeps an
3024    /// empty text and a `ref` to it. Other rich cells (and the PDF
3025    /// pipeline's [`Node::Located`] in-cell pictures) keep their flat cell.
3026    /// The cells' blocks are parallel to `rows`; a ragged (compacted) row
3027    /// pairs its blocks with that row's first-class cells in column order.
3028    fn add_cell_pictures(
3029        &mut self,
3030        t: &Table,
3031        self_ref: &str,
3032        data: &mut TableData,
3033        children: &mut Vec<Value>,
3034    ) {
3035        let Some(blocks) = t.cell_blocks.as_ref() else {
3036            return;
3037        };
3038        for (r, row) in blocks.iter().enumerate() {
3039            let mut in_row: Vec<usize> = (0..data.cells.len())
3040                .filter(|&i| data.cells[i].start_row == r)
3041                .collect();
3042            in_row.sort_by_key(|&i| data.cells[i].start_col);
3043            let ragged = t.rows.get(r).map_or(0, Vec::len) != data.num_cols;
3044            for (c, cell) in row.iter().enumerate() {
3045                let target = if ragged {
3046                    in_row.get(c).copied()
3047                } else {
3048                    in_row
3049                        .iter()
3050                        .copied()
3051                        .find(|&i| data.cells[i].start_col == c)
3052                };
3053                // A `rich_cell_group` (#1119, the DOC backend's picture
3054                // cells): the DOCX item tree's `rich_cell_group_<table>_
3055                // <col>_<row>` group under the table, holding the cell's
3056                // items, and the cell's text without its `<!-- image -->`
3057                // paragraphs.
3058                if let [Node::Group {
3059                    name: Some(name),
3060                    children: blocks,
3061                    ..
3062                }] = cell.as_slice()
3063                {
3064                    let Some(target) = target.filter(|_| name == crate::document::RICH_CELL) else {
3065                        continue;
3066                    };
3067                    let name = format!("rich_cell_group_{}_{c}_{r}", self.tables.len() + 1);
3068                    let group = ref_value(self.add_group(
3069                        "unspecified",
3070                        Some(&name),
3071                        None,
3072                        blocks,
3073                        self_ref,
3074                    ));
3075                    children.push(group.clone());
3076                    let cell = &mut data.cells[target];
3077                    cell.text = cell
3078                        .text
3079                        .split("\n\n")
3080                        .filter(|p| p.trim() != "<!-- image -->")
3081                        .collect::<Vec<_>>()
3082                        .join("\n\n")
3083                        .into();
3084                    cell.cell_ref = Some(Box::new(group));
3085                    continue;
3086                }
3087                let [node @ Node::Prov { inner, .. }] = cell.as_slice() else {
3088                    continue;
3089                };
3090                if !matches!(**inner, Node::Picture { .. }) {
3091                    continue;
3092                }
3093                let Some(target) = target else {
3094                    continue;
3095                };
3096                let Some(pic) = self.add_node(node, self_ref) else {
3097                    continue;
3098                };
3099                let pic = ref_value(pic);
3100                children.push(pic.clone());
3101                let cell = &mut data.cells[target];
3102                cell.text = "".into();
3103                cell.cell_ref = Some(Box::new(pic));
3104            }
3105        }
3106    }
3107
3108    /// Add a picture's or table's caption text item where `choice` says it
3109    /// hangs (#390), returning the `captions` entry for the item and the
3110    /// item's own `children` (the caption, when it is the item's child).
3111    /// The caption never consumes the item's pending provenance — the item
3112    /// takes its box first. Its own box, when the backend kept one (the PDF
3113    /// pipeline's caption region, #609), becomes the caption's `prov` on the
3114    /// item's page, as docling's reading-order model gives every caption the
3115    /// cluster it came from; without one the caption has no `prov`.
3116    fn add_caption(
3117        &mut self,
3118        text: &str,
3119        extra: Value,
3120        self_ref: &str,
3121        parent: &str,
3122        (choice, location): (CaptionParent, Option<[u16; 4]>),
3123    ) -> (Vec<Value>, Vec<Value>) {
3124        // docling's PDF pipeline parents the caption to the item; every
3125        // declarative backend leaves `add_text`'s default — the body — even
3126        // for an item inside a group; the office backends and HTML's
3127        // `<figure>` hang it off the item's container.
3128        let cap_parent = match choice {
3129            CaptionParent::Item => self_ref,
3130            CaptionParent::Container | CaptionParent::ContainerAfter => parent,
3131            CaptionParent::Body => "#/body",
3132        };
3133        if self.cur_page > 0 && location.is_some() {
3134            self.pending_loc = location;
3135        }
3136        let cap_ref = ref_value(self.add_text("caption", text, cap_parent, extra));
3137        match choice {
3138            CaptionParent::Item => return (vec![cap_ref.clone()], vec![cap_ref]),
3139            // Created ahead of the item, so it precedes the item in the
3140            // container's children — and, on the body, in the body's.
3141            CaptionParent::Container => self.pending_siblings.push(cap_ref.clone()),
3142            CaptionParent::Body if parent == "#/body" => {
3143                self.pending_siblings.push(cap_ref.clone())
3144            }
3145            CaptionParent::ContainerAfter => self.pending_after.push(cap_ref.clone()),
3146            // The item sits deeper: the body's children get the caption after
3147            // the top-level item under walk, where docling appended it.
3148            CaptionParent::Body => self.pending_body.push(cap_ref.clone()),
3149        }
3150        (vec![cap_ref], Vec::new())
3151    }
3152
3153    /// `meta` is the picture's docling `PictureMeta` (a classifier's
3154    /// predictions, a chart's kind and data), `None` for a plain picture.
3155    fn add_picture(
3156        &mut self,
3157        caption: Option<&str>,
3158        caption_href: Option<&str>,
3159        image: Option<&crate::PictureImage>,
3160        meta: Option<Value>,
3161        parent: &str,
3162        caption_at: (CaptionParent, Option<[u16; 4]>),
3163    ) -> String {
3164        let self_ref = format!("#/pictures/{}", self.pictures.len());
3165        // Take the picture's own provenance before the caption text is added —
3166        // the caption is a separate item and must not inherit the crop's box.
3167        let prov = self.take_prov(0);
3168        let (captions, children) = match caption.filter(|c| !c.is_empty()) {
3169            Some(cap) => {
3170                // Emit the caption as a text item that the picture references. A
3171                // wrapping `<a href>`'s link rides as docling's `hyperlink` field
3172                // on the caption item (#328).
3173                let extra = match caption_href {
3174                    Some(href) => json!({ "hyperlink": href }),
3175                    None => json!({}),
3176                };
3177                self.add_caption(cap, extra, &self_ref, parent, caption_at)
3178            }
3179            None => (Vec::new(), Vec::new()),
3180        };
3181        self.push_picture(prov, captions, children, image, meta, parent)
3182    }
3183
3184    /// Append the picture item itself — `prov`, `captions` and `children`
3185    /// (a PDF caption is the picture's child) already settled.
3186    fn push_picture(
3187        &mut self,
3188        prov: Value,
3189        captions: Vec<Value>,
3190        children: Vec<Value>,
3191        image: Option<&crate::PictureImage>,
3192        meta: Option<Value>,
3193        parent: &str,
3194    ) -> String {
3195        let self_ref = format!("#/pictures/{}", self.pictures.len());
3196        // The legacy `classification` annotation rides along with a
3197        // classifier's `meta` (see `classification_meta`); a chart's meta has
3198        // none, like docling's.
3199        let annotations = meta
3200            .as_ref()
3201            .and_then(|m| m.get("annotations").cloned())
3202            .unwrap_or_else(|| json!([]));
3203        let meta = meta.map(|mut m| {
3204            if let Some(obj) = m.as_object_mut() {
3205                obj.remove("annotations");
3206            }
3207            m
3208        });
3209        // `meta` sits between `content_layer` and `label` in docling's field
3210        // order (and `preserve_order` keeps ours byte-compatible), so the item
3211        // is built in one shot per shape rather than patched afterwards.
3212        let mut item = match meta {
3213            Some(meta) => json!({
3214                "self_ref": self_ref,
3215                "parent": { "$ref": parent },
3216                "children": children,
3217                "content_layer": "body",
3218                "meta": meta,
3219                "label": "picture",
3220                "prov": prov,
3221                "captions": captions,
3222                "references": [],
3223                "footnotes": [],
3224                "annotations": annotations,
3225            }),
3226            None => json!({
3227                "self_ref": self_ref,
3228                "parent": { "$ref": parent },
3229                "children": children,
3230                "content_layer": "body",
3231                "label": "picture",
3232                "prov": prov,
3233                "captions": captions,
3234                "references": [],
3235                "footnotes": [],
3236                "annotations": annotations,
3237            }),
3238        };
3239        // docling stores the extracted image as an `ImageRef` (data URI + size,
3240        // the size as floats) between `footnotes` and `annotations` — pydantic
3241        // field order, which `preserve_order` lets us reproduce by rebuilding
3242        // the tail.
3243        if let Some(img) = image {
3244            let mut image = image_ref_json(img);
3245            // The displayed size, for the Pandoc writer only (#834):
3246            // docling's `ImageRef` has no field for it.
3247            if self.note_keys {
3248                if let Some([w, h]) = img.display_size {
3249                    image["_display"] = json!([w, h]);
3250                }
3251            }
3252            if let Some(obj) = item.as_object_mut() {
3253                let annotations = obj.remove("annotations").unwrap_or_else(|| json!([]));
3254                obj.insert("image".into(), image);
3255                obj.insert("annotations".into(), annotations);
3256            }
3257        }
3258        self.pictures.push(item);
3259        self_ref
3260    }
3261
3262    fn add_group(
3263        &mut self,
3264        label: &str,
3265        name: Option<&str>,
3266        layer: Option<ContentLayer>,
3267        nodes: &[Node],
3268        parent: &str,
3269    ) -> String {
3270        let self_ref = format!("#/groups/{}", self.groups.len());
3271        self.groups.push(Value::Null);
3272        // Everything the walk creates belongs to this group, so a non-body
3273        // layer (a hidden sheet) is stamped on the whole subtree afterwards —
3274        // docling puts the layer on the group *and* on every item under it.
3275        let mark = (
3276            self.texts.len(),
3277            self.tables.len(),
3278            self.pictures.len(),
3279            self.groups.len(),
3280        );
3281        let children: Vec<Value> = self
3282            .walk_into(nodes, &self_ref)
3283            .into_iter()
3284            .map(Child::into_value)
3285            .collect();
3286        let name = name.unwrap_or(if label == "inline" { "group" } else { label });
3287        let content_layer = layer.map_or("body", |l| l.value());
3288        self.groups[group_index(&self_ref)] = json!({
3289            "self_ref": self_ref,
3290            "parent": { "$ref": parent },
3291            "children": children,
3292            "content_layer": content_layer,
3293            "name": name,
3294            "label": label,
3295        });
3296        if layer.is_some() {
3297            let (t, tb, p, g) = mark;
3298            for item in self.texts[t..]
3299                .iter_mut()
3300                .enumerate()
3301                .map(|(k, item)| item.value_mut(t + k))
3302                .chain(self.tables[tb..].iter_mut().map(|t| &mut t.item))
3303                .chain(self.pictures[p..].iter_mut())
3304                .chain(self.groups[g..].iter_mut())
3305            {
3306                if let Some(obj) = item.as_object_mut() {
3307                    obj.insert("content_layer".into(), json!(content_layer));
3308                }
3309            }
3310        }
3311        self_ref
3312    }
3313
3314    /// Walk a slice of sibling nodes, returning each child's `$ref`; runs of
3315    /// list items are folded into list groups (one per sibling list).
3316    fn walk_into(&mut self, nodes: &[Node], parent: &str) -> Vec<Child> {
3317        // Siblings that all carry a creation rank (an XLSX sheet's items) are
3318        // *added* in that order — so `#/tables/N` and friends are numbered as
3319        // docling numbers them — while their refs keep the node order, which
3320        // is docling's position-sorted `children`.
3321        let seqs: Option<Vec<usize>> = nodes
3322            .iter()
3323            .map(|n| match n {
3324                Node::Prov { seq: Some(s), .. } => Some(*s),
3325                _ => None,
3326            })
3327            .collect();
3328        if let Some(seqs) = seqs.filter(|s| !s.is_empty()) {
3329            let mut order: Vec<usize> = (0..nodes.len()).collect();
3330            order.sort_by_key(|&i| seqs[i]);
3331            let mut slots: Vec<Vec<Child>> = (0..nodes.len()).map(|_| Vec::new()).collect();
3332            for i in order {
3333                if let Some(r) = self.add_node(&nodes[i], parent) {
3334                    slots[i].extend(self.pending_siblings.drain(..).map(Child::json));
3335                    slots[i].push(Child::Ref(r.into()));
3336                    slots[i].extend(self.pending_after.drain(..).map(Child::json));
3337                }
3338                if parent == "#/body" {
3339                    slots[i].extend(self.pending_body.drain(..).map(Child::json));
3340                }
3341            }
3342            return slots.into_iter().flatten().collect();
3343        }
3344        let mut children = Vec::new();
3345        let mut i = 0;
3346        while i < nodes.len() {
3347            if matches!(nodes[i], Node::ListItem { .. }) {
3348                let start = i;
3349                i += 1;
3350                loop {
3351                    match nodes.get(i) {
3352                        Some(Node::ListItem { .. }) => i += 1,
3353                        // Absorb an empty paragraph sitting between two list
3354                        // items (docling keeps the ListGroup contiguous).
3355                        Some(Node::Paragraph { text })
3356                            if text.is_empty()
3357                                && matches!(nodes.get(i + 1), Some(Node::ListItem { .. })) =>
3358                        {
3359                            i += 1
3360                        }
3361                        _ => break,
3362                    }
3363                }
3364                let mut lists = Vec::new();
3365                self.add_sibling_lists(&nodes[start..i], parent, &mut lists);
3366                children.extend(lists.into_iter().map(Child::json));
3367            } else {
3368                if let Some(r) = self.add_node(&nodes[i], parent) {
3369                    children.extend(self.pending_siblings.drain(..).map(Child::json));
3370                    children.push(Child::Ref(r.into()));
3371                    children.extend(self.pending_after.drain(..).map(Child::json));
3372                }
3373                i += 1;
3374            }
3375            // Body-parented captions of items deeper in the tree follow the
3376            // top-level item they were created under (#390).
3377            if parent == "#/body" {
3378                children.extend(self.pending_body.drain(..).map(Child::json));
3379            }
3380        }
3381        children
3382    }
3383
3384    /// A run of list items may hold several *sibling* lists; emit one list group
3385    /// per sibling. The boundary is the backend's `first_in_list` flag on a
3386    /// base-level item — the same rule as the Markdown serializer's blank line
3387    /// (#385; the kind-flip and number-gap guesses are gone).
3388    fn add_sibling_lists(&mut self, run: &[Node], parent: &str, out: &mut Vec<Value>) {
3389        let base = level_of(&run[0]);
3390        let mut seg = 0;
3391        for k in 0..run.len() {
3392            let Node::ListItem {
3393                first_in_list,
3394                level,
3395                ..
3396            } = &run[k]
3397            else {
3398                continue;
3399            };
3400            if *level != base {
3401                continue; // nested item — handled inside add_list
3402            }
3403            if k > seg && *first_in_list {
3404                out.push(ref_value(self.add_list(&run[seg..k], parent)));
3405                seg = k;
3406            }
3407        }
3408        out.push(ref_value(self.add_list(&run[seg..], parent)));
3409    }
3410}
3411
3412fn level_of(node: &Node) -> u8 {
3413    match node {
3414        Node::ListItem { level, .. } => *level,
3415        _ => 0,
3416    }
3417}
3418
3419fn group_index(self_ref: &str) -> usize {
3420    self_ref.rsplit('/').next().unwrap().parse().unwrap()
3421}
3422
3423fn ref_index(self_ref: &str) -> Option<usize> {
3424    self_ref.rsplit('/').next()?.parse().ok()
3425}
3426
3427/// Merge the key/values of `extra` (an object) into `target` (an object).
3428fn merge(target: &mut Value, extra: Value) {
3429    if let (Some(t), Value::Object(e)) = (target.as_object_mut(), extra) {
3430        t.extend(e);
3431    }
3432}
3433
3434/// A JSON object of exactly these entries, in this order. The hot per-item
3435/// constructors use this instead of `json!`: the macro grows its map by
3436/// doubling (an 8-key item kept 14 slots) and deep-copies every interpolated
3437/// `Value` through `to_value`. On a long text-heavy PDF those item objects
3438/// *are* the export's footprint (the same reasoning as [`cell_value`]).
3439fn object<const N: usize>(entries: [(&str, Value); N]) -> Value {
3440    let mut m = serde_json::Map::with_capacity(N);
3441    for (k, v) in entries {
3442        m.insert(k.to_owned(), v);
3443    }
3444    Value::Object(m)
3445}
3446
3447/// A `{"$ref": r}` reference object.
3448fn ref_value(r: impl Into<String>) -> Value {
3449    object([("$ref", Value::String(r.into()))])
3450}
3451
3452/// Reverse [`crate`]'s Markdown text escaping (HTML entities + `\_`).
3453fn unescape_text(s: &str) -> String {
3454    s.replace("&lt;", "<")
3455        .replace("&gt;", ">")
3456        .replace("&amp;", "&")
3457        .replace("\\_", "_")
3458}
3459
3460/// 64-bit FNV-1a, a stand-in for docling's `binary_hash` (we lack the source bytes
3461/// at export time; the value only needs to be a stable u64).
3462fn fnv1a(s: &str) -> u64 {
3463    let mut h: u64 = 0xcbf29ce484222325;
3464    for b in s.bytes() {
3465        h ^= b as u64;
3466        h = h.wrapping_mul(0x100000001b3);
3467    }
3468    h
3469}
3470
3471#[cfg(test)]
3472mod tests {
3473    #[cfg(feature = "preserve-order")]
3474    use crate::ImageMode;
3475    #[cfg(feature = "preserve-order")]
3476    use crate::PictureImage;
3477    use crate::{CaptionParent, ContentLayer, DoclingDocument, Node, Table};
3478    use serde_json::Value;
3479
3480    fn cell_at(text: &str, row: usize, col: usize, col_span: usize) -> crate::TableCell {
3481        crate::TableCell {
3482            text: text.into(),
3483            bbox: None,
3484            start_row: row,
3485            start_col: col,
3486            row_span: 1,
3487            col_span,
3488            column_header: row == 0,
3489            row_header: false,
3490            row_section: false,
3491        }
3492    }
3493
3494    /// First-class cells past the rows: rectangular rows are the grid and
3495    /// clip them (docling's `TableData.grid` on USPTO's overrun replicas);
3496    /// ragged rows — an xlsx table compacted by `skip_empty_cells` (#271) —
3497    /// are no grid, so the cells' extent sizes it and the omitted positions
3498    /// come back as empty filler cells in `grid` only.
3499    #[test]
3500    fn ragged_rows_take_their_grid_from_first_class_cells() {
3501        let cells = vec![
3502            cell_at("h0", 0, 0, 1),
3503            cell_at("h2", 0, 2, 1),
3504            cell_at("wide", 1, 0, 3),
3505        ];
3506        let export = |rows: Vec<Vec<String>>| -> Value {
3507            let mut doc = DoclingDocument::new("t");
3508            doc.push(Node::Table(Table {
3509                rows,
3510                cells: Some(cells.clone()),
3511                ..Table::default()
3512            }));
3513            let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
3514            v["tables"][0]["data"].clone()
3515        };
3516        // Compacted rows: 2 and 3 wide, the cells say the grid is 3 wide.
3517        let data = export(vec![
3518            vec!["h0".into(), "h2".into()],
3519            vec!["wide".into(), "wide".into(), "wide".into()],
3520        ]);
3521        assert_eq!(data["num_rows"], 2);
3522        assert_eq!(data["num_cols"], 3);
3523        assert_eq!(data["table_cells"].as_array().unwrap().len(), 3);
3524        let row0: Vec<&str> = data["grid"][0]
3525            .as_array()
3526            .unwrap()
3527            .iter()
3528            .map(|c| c["text"].as_str().unwrap())
3529            .collect();
3530        assert_eq!(row0, ["h0", "", "h2"]);
3531        assert_eq!(data["table_cells"][2]["col_span"], 3);
3532        // Rectangular rows narrower than the cells: the rows win, the cells
3533        // are clipped to them exactly as before.
3534        let data = export(vec![
3535            vec!["h0".into(), "h2".into()],
3536            vec!["wide".into(), "wide".into()],
3537        ]);
3538        assert_eq!(data["num_cols"], 2);
3539        assert_eq!(data["grid"][0].as_array().unwrap().len(), 2);
3540    }
3541
3542    #[cfg(feature = "preserve-order")]
3543    fn doc_with_image() -> DoclingDocument {
3544        let mut doc = DoclingDocument::new("t");
3545        doc.push(Node::Picture {
3546            caption: Some("Fig 1".into()),
3547            caption_href: None,
3548            image: Some(PictureImage {
3549                dpi: crate::PictureImage::DEFAULT_DPI,
3550                mimetype: "image/png".into(),
3551                width: 4,
3552                height: 2,
3553                data: b"foobar".to_vec(),
3554                display_size: None,
3555            }),
3556            classification: None,
3557            description: None,
3558            caption_parent: Default::default(),
3559            caption_location: None,
3560        });
3561        doc
3562    }
3563
3564    /// #402: a deck's speaker notes are content, and docling puts them in the
3565    /// JSON on the `notes` layer so a consumer reading only JSON can pick them
3566    /// out. Markdown still serializes the body layer alone, and page furniture
3567    /// stays out of the JSON, where docling does keep it.
3568    #[test]
3569    fn notes_layer_items_reach_the_json_but_furniture_does_not() {
3570        let mut doc = DoclingDocument::new("t");
3571        doc.push(Node::Heading {
3572            level: 1,
3573            text: "Slide One".into(),
3574        });
3575        doc.push(Node::Furniture {
3576            layer: ContentLayer::Notes,
3577            inner: Box::new(Node::Located {
3578                location: [0, 0, 0, 0],
3579                inner: Box::new(Node::Paragraph {
3580                    text: "Speaker note for slide 1.".into(),
3581                }),
3582            }),
3583        });
3584        doc.push(Node::Furniture {
3585            layer: ContentLayer::Furniture,
3586            inner: Box::new(Node::Paragraph {
3587                text: "page header".into(),
3588            }),
3589        });
3590
3591        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
3592        let texts = v["texts"].as_array().unwrap();
3593        assert_eq!(
3594            texts
3595                .iter()
3596                .map(|t| (
3597                    t["label"].as_str().unwrap(),
3598                    t["content_layer"].as_str().unwrap(),
3599                    t["text"].as_str().unwrap()
3600                ))
3601                .collect::<Vec<_>>(),
3602            vec![
3603                ("title", "body", "Slide One"),
3604                ("text", "notes", "Speaker note for slide 1."),
3605            ],
3606            "the note is carried on its own layer; the furniture is not carried"
3607        );
3608        // The body layer is what Markdown serializes, so it does not change.
3609        assert_eq!(doc.export_to_markdown(), "# Slide One\n");
3610    }
3611
3612    /// #410: a backend that describes merged ranges only as continuation
3613    /// flags (xlsx `<mergeCell>`, docx `gridSpan`/`vMerge`) gets docling's
3614    /// one-`TableCell`-per-range JSON: the anchor's offsets and spans, the
3615    /// entry repeated across the grid positions it covers — not a 1×1 cell
3616    /// per position with the text copied into each.
3617    #[test]
3618    fn continuation_flags_become_spanning_cells() {
3619        let mut doc = DoclingDocument::new("t");
3620        // A1:C2 merged ("merged"), then a plain row underneath.
3621        let rows = vec![
3622            vec!["merged".to_string(), "merged".into(), "merged".into()],
3623            vec!["merged".to_string(), "merged".into(), "merged".into()],
3624            vec!["a".to_string(), "b".into(), "c".into()],
3625        ];
3626        doc.push(Node::Table(crate::Table {
3627            footnotes: Vec::new(),
3628            footnotes_as_runs: false,
3629            rows,
3630            location: None,
3631            structure: Some(crate::TableStructure {
3632                header_row: vec![true, false, false],
3633                col_continuation: vec![
3634                    vec![false, true, true],
3635                    vec![false, true, true],
3636                    vec![false, false, false],
3637                ],
3638                row_continuation: vec![
3639                    vec![false, false, false],
3640                    vec![true, true, true],
3641                    vec![false, false, false],
3642                ],
3643                row_header: Vec::new(),
3644                col_header: Vec::new(),
3645            }),
3646            cell_blocks: None,
3647            cells: None,
3648            caption: None,
3649            caption_parent: Default::default(),
3650            caption_location: None,
3651            document_index: false,
3652        }));
3653        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
3654        let data = &v["tables"][0]["data"];
3655        assert_eq!(data["num_rows"], 3);
3656        assert_eq!(data["num_cols"], 3);
3657        let cells = data["table_cells"].as_array().unwrap();
3658        assert_eq!(
3659            cells.len(),
3660            4,
3661            "one cell for the range, three for the plain row"
3662        );
3663        assert_eq!(
3664            cells[0],
3665            serde_json::json!({
3666                "row_span": 2, "col_span": 3,
3667                "start_row_offset_idx": 0, "end_row_offset_idx": 2,
3668                "start_col_offset_idx": 0, "end_col_offset_idx": 3,
3669                "text": "merged", "column_header": true, "row_header": false,
3670                "row_section": false, "fillable": false,
3671            })
3672        );
3673        assert_eq!(cells[1]["text"], "a");
3674        assert_eq!(cells[1]["row_span"], 1);
3675        assert_eq!(cells[1]["column_header"], false);
3676        // The grid repeats the range's entry at every position it covers.
3677        let grid = data["grid"].as_array().unwrap();
3678        assert_eq!(grid.len(), 3);
3679        for (r, row) in grid.iter().take(2).enumerate() {
3680            for (c, cell) in row.as_array().unwrap().iter().enumerate() {
3681                assert_eq!(*cell, cells[0], "grid[{r}][{c}]");
3682            }
3683        }
3684        assert_eq!(grid[2][2]["text"], "c");
3685    }
3686
3687    /// A [`Node::Prov`] wrapper is docling's provenance verbatim — the exact
3688    /// box in a top-left origin, the backend's charspan — and the page marker
3689    /// before it sizes the page; a chart's caption becomes a sibling of the
3690    /// picture in the container, listed first, sharing the chart's box with
3691    /// a charspan over its text. That is the JSON shape of an XLSX sheet.
3692    #[test]
3693    fn exact_provenance_pages_and_chart_captions_follow_docling() {
3694        let mut doc = DoclingDocument::new("t");
3695        doc.push(Node::PageInfo {
3696            page_no: 1,
3697            width: 3.0,
3698            height: 4.0,
3699        });
3700        let table = crate::Table {
3701            rows: vec![vec!["a".to_string(), "b".into()]],
3702            ..Default::default()
3703        };
3704        doc.push(Node::Group {
3705            label: "sheet".into(),
3706            name: Some("Data".into()),
3707            layer: None,
3708            children: vec![
3709                // Node order is the position-sorted one; creation order (the
3710                // `seq`) had the chart first — so the chart is `#/pictures/0`
3711                // *and* its caption `#/texts/0`, while the table stays the
3712                // group's first child.
3713                Node::Prov {
3714                    page_no: 1,
3715                    bbox: [0.0, 0.0, 3.0, 4.0],
3716                    charspan: [0, 0],
3717                    bottom_left: false,
3718                    seq: Some(1),
3719                    inner: Box::new(Node::Table(table.clone())),
3720                },
3721                Node::Prov {
3722                    page_no: 1,
3723                    bbox: [0.0, 1.0, 1.0, 1.0],
3724                    charspan: [0, 0],
3725                    bottom_left: false,
3726                    seq: Some(0),
3727                    inner: Box::new(Node::Chart {
3728                        kind: "bar_chart".into(),
3729                        table,
3730                        caption: Some("Sales".into()),
3731                        location: Some([0, 128, 170, 128]),
3732                    }),
3733                },
3734            ],
3735        });
3736        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
3737        assert_eq!(
3738            v["pages"],
3739            serde_json::json!({"1": {"size": {"width": 3.0, "height": 4.0}, "page_no": 1}})
3740        );
3741        assert_eq!(
3742            v["tables"][0]["prov"],
3743            serde_json::json!([{
3744                "page_no": 1,
3745                "bbox": {"l": 0.0, "t": 0.0, "r": 3.0, "b": 4.0, "coord_origin": "TOPLEFT"},
3746                "charspan": [0, 0],
3747            }])
3748        );
3749        assert_eq!(v["tables"][0]["data"]["orientation"], "rot_0");
3750        // The caption is the group's child *before* the picture, parented to
3751        // the group, and referenced by the picture.
3752        let sheet = &v["groups"][0];
3753        assert_eq!(
3754            sheet["children"],
3755            serde_json::json!([
3756                {"$ref": "#/tables/0"}, {"$ref": "#/texts/0"}, {"$ref": "#/pictures/0"}
3757            ])
3758        );
3759        let cap = &v["texts"][0];
3760        assert_eq!(cap["label"], "caption");
3761        assert_eq!(cap["parent"], serde_json::json!({"$ref": "#/groups/0"}));
3762        assert_eq!(cap["prov"][0]["charspan"], serde_json::json!([0, 5]));
3763        assert_eq!(cap["prov"][0]["bbox"]["b"], 1.0);
3764        let pic = &v["pictures"][0];
3765        assert_eq!(pic["captions"], serde_json::json!([{"$ref": "#/texts/0"}]));
3766        assert_eq!(pic["prov"][0]["charspan"], serde_json::json!([0, 0]));
3767        assert_eq!(pic["prov"][0]["bbox"]["coord_origin"], "TOPLEFT");
3768        assert_eq!(
3769            pic["meta"]["classification"]["predictions"][0]["class_name"],
3770            "bar_chart"
3771        );
3772        assert_eq!(pic["meta"]["tabular_chart"]["chart_data"]["num_cols"], 2);
3773    }
3774
3775    /// An all-zero location is the "no geometry" sentinel — a slide's speaker
3776    /// notes carry one — and docling writes it as a zero bbox, not as a box
3777    /// spanning the whole page, which is what denormalizing the grid gives.
3778    #[test]
3779    fn a_zero_location_is_a_zero_bbox_not_the_whole_page() {
3780        let mut doc = DoclingDocument::new("t");
3781        doc.push(Node::PageInfo {
3782            page_no: 1,
3783            width: 12192000.0,
3784            height: 6858000.0,
3785        });
3786        doc.push(Node::Furniture {
3787            layer: ContentLayer::Notes,
3788            inner: Box::new(Node::Located {
3789                location: [0, 0, 0, 0],
3790                inner: Box::new(Node::Paragraph {
3791                    text: "a note".into(),
3792                }),
3793            }),
3794        });
3795        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
3796        let prov = &v["texts"][0]["prov"][0];
3797        assert_eq!(prov["page_no"], 1);
3798        assert_eq!(prov["charspan"], serde_json::json!([0, 6]));
3799        assert_eq!(
3800            prov["bbox"],
3801            serde_json::json!({"l": 0.0, "t": 0.0, "r": 0.0, "b": 0.0, "coord_origin": "BOTTOMLEFT"})
3802        );
3803        // The page itself is recorded at its true size.
3804        assert_eq!(
3805            v["pages"]["1"]["size"],
3806            serde_json::json!({"width": 12192000.0, "height": 6858000.0})
3807        );
3808    }
3809
3810    /// #171: PageInfo markers become the `pages` map, and `Located` wrappers /
3811    /// node-level locations become per-item `prov` — the 0–511 grid
3812    /// denormalized against the page into BOTTOMLEFT points. Without markers
3813    /// (every declarative backend) the JSON stays exactly as before: empty
3814    /// `pages`, `prov: []` even for located nodes.
3815    /// #609: a PDF caption and a checkbox item carry their own page and box.
3816    /// docling's reading-order model gives every caption the cluster it came
3817    /// from (`_add_caption_or_footnote`), not its picture's or table's, and
3818    /// a checkbox is a text item like any other.
3819    #[test]
3820    fn captions_and_checkboxes_carry_their_own_prov() {
3821        let mut doc = DoclingDocument::new("t");
3822        doc.push(Node::PageInfo {
3823            page_no: 1,
3824            width: 512.0,
3825            height: 512.0,
3826        });
3827        doc.push(Node::Located {
3828            location: [64, 64, 448, 256],
3829            inner: Box::new(Node::Picture {
3830                caption: Some("Figure 1".into()),
3831                caption_href: None,
3832                image: None,
3833                classification: None,
3834                description: None,
3835                caption_parent: CaptionParent::Item,
3836                caption_location: Some([64, 264, 448, 280]),
3837            }),
3838        });
3839        doc.push(Node::PageInfo {
3840            page_no: 2,
3841            width: 512.0,
3842            height: 512.0,
3843        });
3844        doc.push(Node::Located {
3845            location: [64, 120, 448, 300],
3846            inner: Box::new(Node::Table(Table {
3847                rows: vec![vec!["a".into()]],
3848                caption: Some("Table 1".into()),
3849                caption_parent: CaptionParent::Item,
3850                caption_location: Some([64, 100, 300, 112]),
3851                ..Table::default()
3852            })),
3853        });
3854        doc.push(Node::Located {
3855            location: [64, 320, 200, 332],
3856            inner: Box::new(Node::CheckboxItem {
3857                checked: false,
3858                text: "First option".into(),
3859            }),
3860        });
3861        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
3862        let texts = v["texts"].as_array().unwrap();
3863        let by_text = |t: &str| texts.iter().find(|x| x["text"] == t).expect(t).clone();
3864        let bbox = |p: &Value| {
3865            let b = &p["prov"][0]["bbox"];
3866            [&b["l"], &b["t"], &b["r"], &b["b"]].map(|x| x.as_f64().unwrap())
3867        };
3868        // Figure 1: its own box (grid == points on a 512 page, flipped to
3869        // BOTTOMLEFT), not the picture's.
3870        let fig = by_text("Figure 1");
3871        assert_eq!(fig["prov"][0]["page_no"], 1);
3872        assert_eq!(bbox(&fig), [64.0, 248.0, 448.0, 232.0]);
3873        assert_eq!(fig["prov"][0]["charspan"], serde_json::json!([0, 8]));
3874        assert_eq!(fig["parent"]["$ref"], "#/pictures/0");
3875        assert_eq!(v["pictures"][0]["prov"][0]["bbox"]["t"], 448.0);
3876        // Table 1 on page 2, its own box; the table keeps its own.
3877        let tab = by_text("Table 1");
3878        assert_eq!(tab["prov"][0]["page_no"], 2);
3879        assert_eq!(bbox(&tab), [64.0, 412.0, 300.0, 400.0]);
3880        assert_eq!(v["tables"][0]["prov"][0]["bbox"]["t"], 392.0);
3881        // The checkbox item.
3882        let cb = by_text("First option");
3883        assert_eq!(cb["label"], "checkbox_unselected");
3884        assert_eq!(cb["prov"][0]["page_no"], 2);
3885        assert_eq!(bbox(&cb), [64.0, 192.0, 200.0, 180.0]);
3886        assert!(texts
3887            .iter()
3888            .all(|t| !t["prov"].as_array().unwrap().is_empty()));
3889
3890        // Without a caption box (every declarative backend) the caption
3891        // still has no prov, and nothing else moves.
3892        let mut plain = DoclingDocument::new("t");
3893        plain.push(Node::PageInfo {
3894            page_no: 1,
3895            width: 512.0,
3896            height: 512.0,
3897        });
3898        plain.push(Node::Located {
3899            location: [64, 64, 448, 256],
3900            inner: Box::new(Node::Picture {
3901                caption: Some("Figure 1".into()),
3902                caption_href: None,
3903                image: None,
3904                classification: None,
3905                description: None,
3906                caption_parent: CaptionParent::Item,
3907                caption_location: None,
3908            }),
3909        });
3910        let v: Value = serde_json::from_str(&plain.export_to_json()).unwrap();
3911        assert_eq!(v["texts"][0]["prov"], serde_json::json!([]));
3912        assert_eq!(v["pictures"][0]["prov"][0]["bbox"]["t"], 448.0);
3913    }
3914
3915    #[test]
3916    fn page_markers_produce_pages_and_prov() {
3917        let mut doc = DoclingDocument::new("t");
3918        doc.push(Node::PageInfo {
3919            page_no: 1,
3920            width: 512.0,
3921            height: 1024.0,
3922        });
3923        doc.push(Node::Located {
3924            location: [128, 64, 256, 128], // quarter/eighth points of the grid
3925            inner: Box::new(Node::Paragraph {
3926                text: "hello".into(),
3927            }),
3928        });
3929        doc.push(Node::Table(Table {
3930            rows: vec![vec!["a".into()]],
3931            location: Some([0, 0, 512, 512]),
3932            ..Table::default()
3933        }));
3934        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
3935        assert_eq!(v["pages"]["1"]["page_no"], 1);
3936        assert_eq!(v["pages"]["1"]["size"]["width"], 512.0);
3937        assert_eq!(v["pages"]["1"]["size"]["height"], 1024.0);
3938        // 512-wide page: grid x scales 1:1; 1024-high: grid y doubles, then
3939        // flips to the BOTTOMLEFT origin (t from grid-top 64 → 1024-128=896).
3940        let prov = &v["texts"][0]["prov"][0];
3941        assert_eq!(prov["page_no"], 1);
3942        assert_eq!(prov["bbox"]["l"], 128.0);
3943        assert_eq!(prov["bbox"]["t"], 896.0);
3944        assert_eq!(prov["bbox"]["r"], 256.0);
3945        assert_eq!(prov["bbox"]["b"], 768.0);
3946        assert_eq!(prov["bbox"]["coord_origin"], "BOTTOMLEFT");
3947        assert_eq!(prov["charspan"][1], 5);
3948        // The table adopts its own location field; charspan is [0, 0].
3949        let tprov = &v["tables"][0]["prov"][0];
3950        assert_eq!(tprov["bbox"]["t"], 1024.0);
3951        assert_eq!(tprov["bbox"]["b"], 0.0);
3952        assert_eq!(tprov["charspan"][1], 0);
3953
3954        // No markers → the pre-#171 shape, byte for byte.
3955        let mut plain = DoclingDocument::new("t");
3956        plain.push(Node::Located {
3957            location: [1, 2, 3, 4],
3958            inner: Box::new(Node::Paragraph { text: "x".into() }),
3959        });
3960        let v: Value = serde_json::from_str(&plain.export_to_json()).unwrap();
3961        assert_eq!(v["pages"], serde_json::json!({}));
3962        assert_eq!(v["texts"][0]["prov"], serde_json::json!([]));
3963    }
3964
3965    /// PDF page headers/footers reach the JSON as docling writes them:
3966    /// body-parented text items on the furniture layer, with their box.
3967    #[test]
3968    fn page_furniture_becomes_furniture_layer_text() {
3969        let mut doc = DoclingDocument::new("t");
3970        doc.push(Node::PageInfo {
3971            page_no: 1,
3972            width: 512.0,
3973            height: 512.0,
3974        });
3975        doc.push(Node::PageFurniture {
3976            footer: false,
3977            location: [10, 0, 100, 20],
3978            text: "Chapter 1".into(),
3979        });
3980        doc.push(Node::Paragraph {
3981            text: "body".into(),
3982        });
3983        doc.push(Node::PageFurniture {
3984            footer: true,
3985            location: [400, 490, 500, 512],
3986            text: "1.10.2".into(),
3987        });
3988        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
3989        let texts = v["texts"].as_array().unwrap();
3990        assert_eq!(texts.len(), 3);
3991        assert_eq!(texts[0]["label"], "page_header");
3992        assert_eq!(texts[0]["content_layer"], "furniture");
3993        assert_eq!(texts[0]["parent"]["$ref"], "#/body");
3994        assert_eq!(texts[0]["prov"][0]["bbox"]["l"], 10.0);
3995        assert_eq!(texts[1]["content_layer"], "body");
3996        assert_eq!(texts[1]["prov"], serde_json::json!([]));
3997        assert_eq!(texts[2]["label"], "page_footer");
3998        assert_eq!(texts[2]["text"], "1.10.2");
3999        assert_eq!(texts[2]["content_layer"], "furniture");
4000    }
4001
4002    #[test]
4003    #[cfg(feature = "preserve-order")] // field-order assertions (#970)
4004    fn picture_image_in_markdown_modes_and_json() {
4005        let doc = doc_with_image();
4006        // placeholder (default) ignores the image
4007        assert!(doc.export_to_markdown().contains("<!-- image -->"));
4008        // embedded → base64 data URI (b"foobar" → "Zm9vYmFy")
4009        let (md, files) = doc.export_to_markdown_with_images(ImageMode::Embedded, "artifacts");
4010        assert!(
4011            md.contains("![Image](data:image/png;base64,Zm9vYmFy)"),
4012            "got:\n{md}"
4013        );
4014        assert!(files.is_empty());
4015        // referenced → file link + collected bytes
4016        let (md, files) = doc.export_to_markdown_with_images(ImageMode::Referenced, "artifacts");
4017        assert!(
4018            md.contains("![Image](artifacts/image_000000.png)"),
4019            "got:\n{md}"
4020        );
4021        assert_eq!(
4022            files,
4023            vec![("artifacts/image_000000.png".to_string(), b"foobar".to_vec())]
4024        );
4025        // JSON carries the ImageRef (data URI + size — floats, as docling's
4026        // `Size` is — placed before `annotations`).
4027        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
4028        assert_eq!(v["pictures"][0]["image"]["mimetype"], "image/png");
4029        assert_eq!(v["pictures"][0]["image"]["size"]["width"], 4.0);
4030        let keys: Vec<&str> = v["pictures"][0]
4031            .as_object()
4032            .unwrap()
4033            .keys()
4034            .map(String::as_str)
4035            .collect();
4036        assert_eq!(&keys[keys.len() - 2..], ["image", "annotations"]);
4037        assert_eq!(
4038            v["pictures"][0]["image"]["uri"],
4039            "data:image/png;base64,Zm9vYmFy"
4040        );
4041    }
4042
4043    #[test]
4044    fn exports_docling_schema() {
4045        let mut doc = DoclingDocument::new("t");
4046        doc.push(Node::Heading {
4047            level: 1,
4048            text: "Title".into(),
4049        });
4050        doc.push(Node::Heading {
4051            level: 2,
4052            text: "Sec".into(),
4053        });
4054        doc.push(Node::Paragraph {
4055            text: "Body &amp; more".into(),
4056        }); // markdown-escaped
4057        doc.push(Node::ListItem {
4058            ordered: false,
4059            number: 0,
4060            first_in_list: true,
4061            text: "one".into(),
4062            level: 0,
4063            marker: None,
4064            location: None,
4065            split: None,
4066            dclx: None,
4067            href: None,
4068            layer: None,
4069        });
4070        doc.push(Node::ListItem {
4071            ordered: false,
4072            number: 0,
4073            first_in_list: false,
4074            text: "two".into(),
4075            level: 0,
4076            marker: None,
4077            location: None,
4078            split: None,
4079            dclx: None,
4080            href: None,
4081            layer: None,
4082        });
4083        doc.push(Node::Table(Table {
4084            footnotes: Vec::new(),
4085            footnotes_as_runs: false,
4086            rows: vec![vec!["A".into(), "B".into()]],
4087            location: None,
4088            structure: None,
4089            cell_blocks: None,
4090            cells: None,
4091            caption: None,
4092            caption_parent: Default::default(),
4093            caption_location: None,
4094            document_index: false,
4095        }));
4096
4097        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
4098        assert_eq!(v["schema_name"], "DoclingDocument");
4099        assert_eq!(v["version"], "1.11.0");
4100        assert_eq!(v["texts"][0]["label"], "title");
4101        assert_eq!(v["texts"][1]["label"], "section_header");
4102        assert_eq!(v["texts"][1]["level"], 1); // heading level 2 → docling level 1
4103        assert_eq!(v["texts"][2]["text"], "Body & more"); // un-escaped for the wire format
4104                                                          // consecutive list items fold into one list group, parented to it
4105        assert_eq!(v["groups"][0]["label"], "list");
4106        assert_eq!(v["groups"][0]["children"].as_array().unwrap().len(), 2);
4107        assert_eq!(v["texts"][3]["parent"]["$ref"], "#/groups/0");
4108        assert_eq!(v["texts"][3]["marker"], "-");
4109        // table grid + header flag
4110        assert_eq!(v["tables"][0]["data"]["num_cols"], 2);
4111        assert_eq!(v["tables"][0]["data"]["grid"][0][0]["column_header"], true);
4112    }
4113    /// A named group on a non-body layer — docling's hidden spreadsheet sheet:
4114    /// the group carries the sheet's name and the `invisible` layer, and every
4115    /// item inside it carries the layer too.
4116    #[test]
4117    fn a_layered_group_stamps_its_whole_subtree() {
4118        let doc = DoclingDocument {
4119            name: "s".into(),
4120            nodes: vec![
4121                Node::Group {
4122                    label: "sheet".into(),
4123                    name: Some("Sheet1".into()),
4124                    layer: None,
4125                    children: vec![Node::Paragraph {
4126                        text: "visible".into(),
4127                    }],
4128                },
4129                Node::Group {
4130                    label: "sheet".into(),
4131                    name: Some("Sheet2".into()),
4132                    layer: Some(ContentLayer::Invisible),
4133                    children: vec![Node::Paragraph {
4134                        text: "hidden".into(),
4135                    }],
4136                },
4137            ],
4138            ..DoclingDocument::new("s")
4139        };
4140        let v = crate::json::to_json(&doc);
4141        assert_eq!(v["groups"][0]["label"], "sheet");
4142        assert_eq!(v["groups"][0]["name"], "Sheet1");
4143        assert_eq!(v["groups"][0]["content_layer"], "body");
4144        assert_eq!(v["texts"][0]["content_layer"], "body");
4145        assert_eq!(v["groups"][1]["name"], "Sheet2");
4146        assert_eq!(v["groups"][1]["content_layer"], "invisible");
4147        assert_eq!(v["texts"][1]["content_layer"], "invisible");
4148        // The group's children are the items, and the body holds the groups.
4149        assert_eq!(v["groups"][1]["children"][0]["$ref"], "#/texts/1");
4150        assert_eq!(v["body"]["children"][1]["$ref"], "#/groups/1");
4151    }
4152
4153    /// A backend-built item tree is serialized as it is: items numbered in
4154    /// creation order per bucket (a field region's part texts included), the
4155    /// tree's parents / children / layers, docling's field order for
4156    /// `formatting`, `hyperlink`, `level`, `enumerated`/`marker`, a rich
4157    /// cell's `ref` on `table_cells` only, raw cell text.
4158    /// The DOCX tree's extras: an item `delete`d (docling's `delete_items`,
4159    /// the spacer between two items of a resumed list) is neither written nor
4160    /// numbered, `comments` back-refs sit between `prov` and `orig`, and a
4161    /// chart picture carries `classification` plus `tabular_chart`.
4162    #[test]
4163    #[cfg(feature = "preserve-order")] // field-order assertions (#970)
4164    fn deleted_items_comment_refs_and_chart_meta_in_the_tree() {
4165        use crate::tree::{ItemTree, TreeKind};
4166        let mut t = ItemTree::default();
4167        let text = |txt: &str| TreeKind::Text {
4168            label: "text".into(),
4169            text: txt.into(),
4170            orig: None,
4171            formatting: None,
4172            hyperlink: None,
4173            level: None,
4174            list: None,
4175        };
4176        let a = t.add(None, None, text("a"));
4177        let blank = t.add(None, None, text(""));
4178        let b = t.add(None, None, text("b"));
4179        t.delete(blank);
4180        let group = t.add(
4181            None,
4182            Some(ContentLayer::Notes),
4183            TreeKind::Group {
4184                label: "comment_section".into(),
4185                name: "comment-0".into(),
4186            },
4187        );
4188        t.add(Some(group), Some(ContentLayer::Notes), text("note"));
4189        t.items[a].comments.push(group);
4190        t.add(
4191            None,
4192            None,
4193            TreeKind::Picture {
4194                captions: Vec::new(),
4195                image: None,
4196                extra_classes: Vec::new(),
4197                classification: Some("bar_chart".into()),
4198                description: None,
4199                confidence: None,
4200                chart: Some(Table {
4201                    rows: vec![vec!["".into(), "s".into()], vec!["c".into(), "1".into()]],
4202                    ..Table::default()
4203                }),
4204                dpi: None,
4205            },
4206        );
4207        assert_eq!(t.last_text(), Some(4), "the note; the blank is skipped");
4208        assert_eq!(t.bucket_index(b), 1, "numbered past the deleted item");
4209        let mut doc = DoclingDocument::new("t");
4210        doc.tree = Some(t);
4211        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
4212        let texts = v["texts"].as_array().unwrap();
4213        assert_eq!(texts.len(), 3);
4214        assert_eq!(texts[1]["text"], "b");
4215        assert_eq!(texts[1]["self_ref"], "#/texts/1");
4216        assert_eq!(
4217            v["body"]["children"],
4218            serde_json::json!([{"$ref": "#/texts/0"}, {"$ref": "#/texts/1"}, {"$ref": "#/groups/0"}, {"$ref": "#/pictures/0"}])
4219        );
4220        let keys: Vec<&str> = texts[0]
4221            .as_object()
4222            .unwrap()
4223            .keys()
4224            .map(String::as_str)
4225            .collect();
4226        assert_eq!(
4227            keys,
4228            vec![
4229                "self_ref",
4230                "parent",
4231                "children",
4232                "content_layer",
4233                "label",
4234                "prov",
4235                "comments",
4236                "orig",
4237                "text"
4238            ]
4239        );
4240        assert_eq!(
4241            texts[0]["comments"],
4242            serde_json::json!([{"$ref": "#/groups/0"}])
4243        );
4244        assert!(texts[1].get("comments").is_none());
4245        let meta = &v["pictures"][0]["meta"];
4246        assert_eq!(
4247            meta["classification"]["predictions"][0]["class_name"],
4248            "bar_chart"
4249        );
4250        assert_eq!(meta["tabular_chart"]["chart_data"]["num_rows"], 2);
4251    }
4252
4253    /// A tree item's `TreeProv` is written verbatim — a raw EMU box with
4254    /// whatever origin tag the backend set (`BOTTOMLEFT` here) and a per-item
4255    /// charspan, a note's zero `TOPLEFT` box — a picture's `image.dpi` is the file's when the backend
4256    /// read one, an item without provenance writes `prov: []`, and the page
4257    /// map still comes from the flat stream's markers.
4258    #[test]
4259    fn tree_items_carry_exact_provenance_and_dpi() {
4260        use crate::tree::{ItemTree, TreeKind, TreeProv};
4261        let text = |label: &str, t: &str| TreeKind::Text {
4262            label: label.into(),
4263            text: t.into(),
4264            orig: None,
4265            formatting: None,
4266            hyperlink: None,
4267            level: None,
4268            list: None,
4269        };
4270        let mut t = ItemTree::default();
4271        let slide = t.add(
4272            None,
4273            None,
4274            TreeKind::Group {
4275                label: "chapter".into(),
4276                name: "slide-0".into(),
4277            },
4278        );
4279        t.add_with_prov(
4280            Some(slide),
4281            None,
4282            text("paragraph", "héllo"),
4283            TreeProv {
4284                page_no: 1,
4285                bbox: [914400.0, 1828800.0, 2743200.0, 457200.0],
4286                bottom_left: true,
4287                charspan: [0, 5],
4288            },
4289        );
4290        t.add_with_prov(
4291            Some(slide),
4292            None,
4293            TreeKind::Picture {
4294                captions: Vec::new(),
4295                image: Some(crate::PictureImage {
4296                    dpi: crate::PictureImage::DEFAULT_DPI,
4297                    mimetype: "image/png".into(),
4298                    width: 2,
4299                    height: 2,
4300                    data: vec![0],
4301                    display_size: None,
4302                }),
4303                extra_classes: Vec::new(),
4304                classification: None,
4305                description: None,
4306                confidence: None,
4307                chart: None,
4308                dpi: Some(300),
4309            },
4310            TreeProv {
4311                page_no: 1,
4312                bbox: [0.0; 4],
4313                bottom_left: false,
4314                charspan: [0, 0],
4315            },
4316        );
4317        t.add(
4318            Some(slide),
4319            Some(ContentLayer::Notes),
4320            text("text", "no geometry"),
4321        );
4322        let mut doc = DoclingDocument::new("t");
4323        doc.push(Node::PageInfo {
4324            page_no: 1,
4325            width: 9144000.0,
4326            height: 6858000.0,
4327        });
4328        doc.tree = Some(t);
4329        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
4330        assert_eq!(
4331            v["texts"][0]["prov"],
4332            serde_json::json!([{
4333                "page_no": 1,
4334                "bbox": { "l": 914400.0, "t": 1828800.0, "r": 2743200.0, "b": 457200.0, "coord_origin": "BOTTOMLEFT" },
4335                "charspan": [0, 5],
4336            }])
4337        );
4338        assert_eq!(v["texts"][0]["label"], "paragraph");
4339        assert_eq!(
4340            v["pictures"][0]["prov"][0]["bbox"]["coord_origin"],
4341            "TOPLEFT"
4342        );
4343        assert_eq!(v["pictures"][0]["image"]["dpi"], 300);
4344        assert_eq!(v["texts"][1]["prov"], serde_json::json!([]));
4345        assert_eq!(v["texts"][1]["content_layer"], "notes");
4346        assert_eq!(v["pages"]["1"]["size"]["width"], 9144000.0);
4347        assert_eq!(v["pages"]["1"]["page_no"], 1);
4348    }
4349
4350    /// docling-core's `validate_document` clamps every provenance box (and a
4351    /// one-page table's cell boxes) into its page — the state every
4352    /// `ConversionResult` leaves a document in, so the state docling's JSON
4353    /// shows. A box on a page the document does not describe is left alone.
4354    #[test]
4355    fn provenance_boxes_are_clamped_to_their_page() {
4356        let mut doc = DoclingDocument::new("t");
4357        doc.push(Node::PageInfo {
4358            page_no: 1,
4359            width: 10.0,
4360            height: 8.0,
4361        });
4362        doc.push(Node::Prov {
4363            page_no: 1,
4364            bbox: [-1.0, 2.0, 12.0, 9.5],
4365            charspan: [0, 1],
4366            bottom_left: false,
4367            seq: None,
4368            inner: Box::new(Node::Paragraph { text: "x".into() }),
4369        });
4370        let mut table = Table {
4371            rows: vec![vec!["a".into()]],
4372            ..Table::default()
4373        };
4374        table.cells = Some(vec![crate::TableCell {
4375            text: "a".into(),
4376            bbox: Some([1.0, 1.0, 11.0, 9.0]),
4377            start_row: 0,
4378            start_col: 0,
4379            row_span: 1,
4380            col_span: 1,
4381            column_header: false,
4382            row_header: false,
4383            row_section: false,
4384        }]);
4385        doc.push(Node::Prov {
4386            page_no: 1,
4387            bbox: [0.0, 0.0, 10.0, 8.0],
4388            charspan: [0, 0],
4389            bottom_left: false,
4390            seq: None,
4391            inner: Box::new(Node::Table(table)),
4392        });
4393        doc.push(Node::Prov {
4394            page_no: 7,
4395            bbox: [-5.0, 0.0, 50.0, 50.0],
4396            charspan: [0, 1],
4397            bottom_left: false,
4398            seq: None,
4399            inner: Box::new(Node::Paragraph { text: "y".into() }),
4400        });
4401        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
4402        assert_eq!(
4403            v["texts"][0]["prov"][0]["bbox"],
4404            serde_json::json!({ "l": 0.0, "t": 2.0, "r": 10.0, "b": 8.0, "coord_origin": "TOPLEFT" })
4405        );
4406        let cell = &v["tables"][0]["data"]["table_cells"][0]["bbox"];
4407        assert_eq!(
4408            (cell["l"].as_f64(), cell["r"].as_f64(), cell["b"].as_f64()),
4409            (Some(1.0), Some(10.0), Some(8.0))
4410        );
4411        assert_eq!(v["tables"][0]["data"]["grid"][0][0]["bbox"]["r"], 10.0);
4412        assert_eq!(
4413            v["texts"][1]["prov"][0]["bbox"]["r"], 50.0,
4414            "page 7 is not described"
4415        );
4416    }
4417
4418    /// docling-core's `validate_misplaced_list_items`, as it re-homes list
4419    /// items outside a `list` group (#527) — the refs below are what
4420    /// docling-core 2.99 writes for the same document: the two consecutive
4421    /// items on the body share a group, each item in another group gets its
4422    /// own, the runs are handled last-first (new groups and re-added texts
4423    /// numbered in that order), and a well-placed item is left alone.
4424    #[test]
4425    fn misplaced_list_items_are_wrapped_like_docling_core() {
4426        use crate::tree::{ItemTree, ListMeta, TreeKind};
4427        let mut t = ItemTree::default();
4428        let li = |txt: &str| TreeKind::Text {
4429            label: "list_item".into(),
4430            text: txt.into(),
4431            orig: None,
4432            formatting: None,
4433            hyperlink: None,
4434            level: None,
4435            list: Some(ListMeta {
4436                enumerated: false,
4437                marker: "-".into(),
4438            }),
4439        };
4440        let group = |label: &str, name: &str| TreeKind::Group {
4441            label: label.into(),
4442            name: name.into(),
4443        };
4444        t.add(None, None, li("A"));
4445        t.add(None, None, li("B"));
4446        t.add(
4447            None,
4448            None,
4449            TreeKind::Text {
4450                label: "text".into(),
4451                text: "plain".into(),
4452                orig: None,
4453                formatting: None,
4454                hyperlink: None,
4455                level: None,
4456                list: None,
4457            },
4458        );
4459        let cell = t.add(None, None, group("unspecified", "cell"));
4460        t.add(Some(cell), None, li("C"));
4461        t.add(Some(cell), None, li("D"));
4462        let list = t.add(None, None, group("list", "list"));
4463        t.add(Some(list), None, li("E"));
4464        let doc = DoclingDocument {
4465            tree: Some(t),
4466            ..DoclingDocument::new("t")
4467        };
4468        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
4469        let refs = |x: &Value| -> Vec<String> {
4470            x.as_array()
4471                .unwrap()
4472                .iter()
4473                .map(|r| r["$ref"].as_str().unwrap().to_string())
4474                .collect()
4475        };
4476        assert_eq!(
4477            refs(&v["body"]["children"]),
4478            ["#/groups/4", "#/texts/0", "#/groups/0", "#/groups/1"]
4479        );
4480        assert_eq!(
4481            refs(&v["groups"][0]["children"]),
4482            ["#/groups/3", "#/groups/2"]
4483        );
4484        for (g, name, kids) in [
4485            (2, "group", vec!["#/texts/2"]),
4486            (3, "group", vec!["#/texts/3"]),
4487            (4, "group", vec!["#/texts/4", "#/texts/5"]),
4488            (1, "list", vec!["#/texts/1"]),
4489        ] {
4490            assert_eq!(v["groups"][g]["label"], "list");
4491            assert_eq!(v["groups"][g]["name"], name);
4492            assert_eq!(refs(&v["groups"][g]["children"]), kids);
4493        }
4494        let texts: Vec<&str> = v["texts"]
4495            .as_array()
4496            .unwrap()
4497            .iter()
4498            .map(|t| t["text"].as_str().unwrap())
4499            .collect();
4500        assert_eq!(texts, ["plain", "E", "D", "C", "A", "B"]);
4501        assert_eq!(v["texts"][2]["parent"]["$ref"], "#/groups/2");
4502    }
4503
4504    /// A child the tree still lists after deleting it is left out instead
4505    /// of written as `"$ref": ""`, which docling-core rejects (#527).
4506    #[test]
4507    fn a_deleted_child_is_not_written_as_an_empty_ref() {
4508        use crate::tree::{ItemTree, TreeKind};
4509        let mut t = ItemTree::default();
4510        let text = |txt: &str| TreeKind::Text {
4511            label: "text".into(),
4512            text: txt.into(),
4513            orig: None,
4514            formatting: None,
4515            hyperlink: None,
4516            level: None,
4517            list: None,
4518        };
4519        let g = t.add(
4520            None,
4521            None,
4522            TreeKind::Group {
4523                label: "unspecified".into(),
4524                name: "g".into(),
4525            },
4526        );
4527        let gone = t.add(Some(g), None, text(""));
4528        t.add(Some(g), None, text("kept"));
4529        t.items[gone].deleted = true; // still in `g`'s children
4530        let doc = DoclingDocument {
4531            tree: Some(t),
4532            ..DoclingDocument::new("t")
4533        };
4534        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
4535        assert_eq!(
4536            v["groups"][0]["children"],
4537            serde_json::json!([{"$ref": "#/texts/0"}])
4538        );
4539    }
4540
4541    #[test]
4542    fn a_trimmed_run_tree_gets_the_legacy_join_in_its_runs() {
4543        use crate::tree::{ItemTree, TreeKind, TreeProv};
4544        let text = |label: &str, txt: &str| TreeKind::Text {
4545            label: label.into(),
4546            text: txt.into(),
4547            orig: None,
4548            formatting: None,
4549            hyperlink: None,
4550            level: None,
4551            list: None,
4552        };
4553        let mut t = ItemTree::default();
4554        let g = t.add(
4555            None,
4556            None,
4557            TreeKind::Group {
4558                label: "inline".into(),
4559                name: "group".into(),
4560            },
4561        );
4562        t.add(Some(g), None, text("text", "left"));
4563        let prov = TreeProv {
4564            page_no: 1,
4565            bbox: [0.0, 0.0, 1.0, 1.0],
4566            bottom_left: false,
4567            charspan: [0, 1],
4568        };
4569        t.add_with_prov(Some(g), None, text("formula", "a"), prov.clone());
4570        t.add_with_prov(Some(g), None, text("formula", "b"), prov);
4571        t.add(Some(g), None, text("text", "right"));
4572        let doc = DoclingDocument {
4573            tree: Some(t),
4574            ..DoclingDocument::new("t")
4575        };
4576        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
4577        let texts: Vec<&str> = v["texts"]
4578            .as_array()
4579            .unwrap()
4580            .iter()
4581            .map(|t| t["text"].as_str().unwrap())
4582            .collect();
4583        // `left ` · `a` · ` ` (standalone, appended) · `b` · ` right`.
4584        assert_eq!(texts, ["left ", "a", "b", " right", " "]);
4585        assert_eq!(v["texts"][0]["orig"], "left");
4586        assert_eq!(v["groups"][0]["children"][2]["$ref"], "#/texts/4");
4587        assert_eq!(
4588            v["texts"][4]["prov"][0]["charspan"],
4589            serde_json::json!([0, 1])
4590        );
4591    }
4592
4593    #[test]
4594    #[cfg(feature = "preserve-order")] // field-order assertions (#970)
4595    fn a_backend_item_tree_is_written_verbatim() {
4596        use crate::tree::{Formatting, ItemTree, ListMeta, TreeKind};
4597        let mut t = ItemTree {
4598            // Runs as written: no legacy separator injection (#997).
4599            inline_whitespace: true,
4600            ..ItemTree::default()
4601        };
4602        let text = |label: &str, txt: &str| TreeKind::Text {
4603            label: label.into(),
4604            text: txt.into(),
4605            orig: None,
4606            formatting: None,
4607            hyperlink: None,
4608            level: None,
4609            list: None,
4610        };
4611        let title = t.add(None, Some(ContentLayer::Furniture), text("title", "Page"));
4612        let h = t.add(None, None, text("title", "Heading"));
4613        let group = t.add(
4614            Some(h),
4615            None,
4616            TreeKind::Group {
4617                label: "inline".into(),
4618                name: "group".into(),
4619            },
4620        );
4621        t.add(
4622            Some(group),
4623            None,
4624            TreeKind::Text {
4625                label: "text".into(),
4626                text: "bold".into(),
4627                orig: None,
4628                formatting: Some(Formatting {
4629                    bold: true,
4630                    ..Formatting::default()
4631                }),
4632                hyperlink: Some("https://example.com/".into()),
4633                level: None,
4634                list: None,
4635            },
4636        );
4637        t.add(
4638            Some(group),
4639            None,
4640            TreeKind::Code {
4641                text: "x = 1".into(),
4642                orig: None,
4643                language: Some("python".into()),
4644                formatting: None,
4645                hyperlink: None,
4646                captions: Vec::new(),
4647            },
4648        );
4649        let sub = t.add(
4650            Some(h),
4651            None,
4652            TreeKind::Text {
4653                label: "section_header".into(),
4654                text: "Sub".into(),
4655                orig: Some("Sub\u{2019}".into()),
4656                formatting: None,
4657                hyperlink: None,
4658                level: Some(1),
4659                list: None,
4660            },
4661        );
4662        let item = t.add(
4663            Some(sub),
4664            None,
4665            TreeKind::Text {
4666                label: "list_item".into(),
4667                text: "item".into(),
4668                orig: None,
4669                formatting: None,
4670                hyperlink: None,
4671                level: None,
4672                list: Some(ListMeta {
4673                    enumerated: true,
4674                    marker: "3.".into(),
4675                }),
4676            },
4677        );
4678        let _region = t.add(
4679            Some(sub),
4680            None,
4681            TreeKind::FieldRegion {
4682                items: vec![crate::FieldItem {
4683                    marker: None,
4684                    key: Some("Name".into()),
4685                    value: Some("Duck".into()),
4686                    value_kind: Some("read_only".into()),
4687                }],
4688            },
4689        );
4690        let table = t.add(
4691            Some(sub),
4692            None,
4693            TreeKind::Table {
4694                footnotes: Vec::new(),
4695                table: Table {
4696                    rows: vec![vec!["a  \n&lt;".into(), "b".into()]],
4697                    cells: Some(vec![
4698                        crate::TableCell {
4699                            text: "a  \n&lt;".into(),
4700                            bbox: None,
4701                            start_row: 0,
4702                            start_col: 0,
4703                            row_span: 3,
4704                            col_span: 1,
4705                            column_header: false,
4706                            row_header: true,
4707                            row_section: false,
4708                        },
4709                        crate::TableCell {
4710                            text: "b".into(),
4711                            bbox: None,
4712                            start_row: 0,
4713                            start_col: 1,
4714                            row_span: 1,
4715                            col_span: 1,
4716                            column_header: false,
4717                            row_header: false,
4718                            row_section: false,
4719                        },
4720                    ]),
4721                    ..Table::default()
4722                },
4723                rich_cells: vec![(0, 1, 0)], // patched below
4724                captions: Vec::new(),
4725            },
4726        );
4727        let cell_group = t.add(
4728            Some(table),
4729            None,
4730            TreeKind::Group {
4731                label: "unspecified".into(),
4732                name: "rich_cell_group_1_0_0".into(),
4733            },
4734        );
4735        if let TreeKind::Table { rich_cells, .. } = &mut t.items[table].kind {
4736            *rich_cells = vec![(0, 1, cell_group)];
4737        }
4738        let after = t.add(Some(sub), None, text("text", "after the region"));
4739        let _ = (title, after);
4740        // A list item belongs in a `list` group — one outside it would be
4741        // re-homed by `wrap_misplaced_list_items` (created last, so the
4742        // other groups keep their numbers).
4743        let list = t.add(
4744            Some(sub),
4745            None,
4746            TreeKind::Group {
4747                label: "list".into(),
4748                name: "list".into(),
4749            },
4750        );
4751        t.reparent(item, Some(list));
4752
4753        let doc = DoclingDocument {
4754            tree: Some(t),
4755            ..DoclingDocument::new("t")
4756        };
4757        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
4758        // Creation order: Page, Heading, bold, x = 1, Sub, item, [Name, Duck], after.
4759        let texts: Vec<&str> = v["texts"]
4760            .as_array()
4761            .unwrap()
4762            .iter()
4763            .map(|t| t["text"].as_str().unwrap())
4764            .collect();
4765        assert_eq!(
4766            texts,
4767            [
4768                "Page",
4769                "Heading",
4770                "bold",
4771                "x = 1",
4772                "Sub",
4773                "item",
4774                "Name",
4775                "Duck",
4776                "after the region"
4777            ]
4778        );
4779        assert_eq!(
4780            v["body"]["children"],
4781            serde_json::json!([{"$ref": "#/texts/0"}, {"$ref": "#/texts/1"}])
4782        );
4783        assert_eq!(v["texts"][0]["content_layer"], "furniture");
4784        assert_eq!(
4785            v["texts"][1]["children"],
4786            serde_json::json!([{"$ref": "#/groups/0"}, {"$ref": "#/texts/4"}])
4787        );
4788        let bold = &v["texts"][2];
4789        assert_eq!(bold["parent"]["$ref"], "#/groups/0");
4790        let keys: Vec<&str> = bold
4791            .as_object()
4792            .unwrap()
4793            .keys()
4794            .map(String::as_str)
4795            .collect();
4796        assert_eq!(
4797            keys,
4798            [
4799                "self_ref",
4800                "parent",
4801                "children",
4802                "content_layer",
4803                "label",
4804                "prov",
4805                "orig",
4806                "text",
4807                "formatting",
4808                "hyperlink"
4809            ]
4810        );
4811        assert_eq!(
4812            bold["formatting"],
4813            serde_json::json!({"bold": true, "italic": false, "underline": false, "strikethrough": false, "script": "baseline"})
4814        );
4815        let code = &v["texts"][3];
4816        assert_eq!(code["label"], "code");
4817        assert_eq!(code["code_language"], "Python");
4818        let sub = &v["texts"][4];
4819        assert_eq!(sub["orig"], "Sub\u{2019}");
4820        assert_eq!(sub["level"], 1);
4821        let item = &v["texts"][5];
4822        let keys: Vec<&str> = item
4823            .as_object()
4824            .unwrap()
4825            .keys()
4826            .map(String::as_str)
4827            .collect();
4828        assert_eq!(
4829            keys,
4830            [
4831                "self_ref",
4832                "parent",
4833                "children",
4834                "content_layer",
4835                "label",
4836                "prov",
4837                "orig",
4838                "text",
4839                "enumerated",
4840                "marker"
4841            ]
4842        );
4843        assert_eq!(item["marker"], "3.");
4844        assert_eq!(v["texts"][7]["kind"], "read_only");
4845        assert_eq!(v["field_regions"][0]["parent"]["$ref"], "#/texts/4");
4846        let table = &v["tables"][0];
4847        assert_eq!(
4848            table["children"],
4849            serde_json::json!([{"$ref": "#/groups/1"}])
4850        );
4851        let cells = table["data"]["table_cells"].as_array().unwrap();
4852        assert_eq!(
4853            cells[0]["text"], "a  \n&lt;",
4854            "raw cell text is written verbatim"
4855        );
4856        assert_eq!(
4857            cells[0]["end_row_offset_idx"], 3,
4858            "declared spans are not clamped"
4859        );
4860        assert_eq!(cells[1]["ref"], serde_json::json!({"$ref": "#/groups/1"}));
4861        assert!(cells[0].get("ref").is_none());
4862        assert!(
4863            table["data"]["grid"][0][1].get("ref").is_none(),
4864            "the grid shows plain cells"
4865        );
4866        assert_eq!(v["groups"][1]["name"], "rich_cell_group_1_0_0");
4867    }
4868
4869    /// A comment section that links its note text rather than its group — the
4870    /// spreadsheet shape, where docling-core's `add_comment` appends the text
4871    /// item's ref to each target.
4872    #[test]
4873    fn a_comment_section_can_be_referenced_by_its_note_text() {
4874        let doc = DoclingDocument {
4875            name: "c".into(),
4876            nodes: vec![
4877                Node::Commented {
4878                    comments: vec![0],
4879                    inner: Box::new(Node::Paragraph {
4880                        text: "annotated".into(),
4881                    }),
4882                },
4883                Node::CommentSection {
4884                    name: "comment-Sheet1-A1".into(),
4885                    text: "[author: A]: note".into(),
4886                    refs_note_text: true,
4887                    grouped: true,
4888                },
4889            ],
4890            ..DoclingDocument::new("c")
4891        };
4892        let v = crate::json::to_json(&doc);
4893        assert_eq!(v["groups"][0]["name"], "comment-Sheet1-A1");
4894        assert_eq!(v["texts"][0]["comments"][0]["$ref"], "#/texts/1");
4895    }
4896
4897    /// A thread's messages are notes of one `comment_section` group, which is
4898    /// listed once among its parent's children however many notes it holds.
4899    #[test]
4900    fn a_comment_thread_is_one_child_of_its_parent() {
4901        let note = |text: &str| Node::CommentSection {
4902            name: "comment-Sheet1-F7".into(),
4903            text: text.into(),
4904            refs_note_text: true,
4905            grouped: true,
4906        };
4907        let doc = DoclingDocument {
4908            name: "c".into(),
4909            nodes: vec![note("[author: A]: first"), note("[author: B]: reply")],
4910            ..DoclingDocument::new("c")
4911        };
4912        let v = crate::json::to_json(&doc);
4913        assert_eq!(v["body"]["children"].as_array().unwrap().len(), 1);
4914        assert_eq!(v["groups"][0]["children"].as_array().unwrap().len(), 2);
4915    }
4916
4917    /// docx reviewer comments: a `comment_section` group on the notes layer
4918    /// holding the note text, and a `comments` back-ref on the annotated item —
4919    /// keyed between `prov` and `orig`, the slot docling emits it in.
4920    #[test]
4921    #[cfg(feature = "preserve-order")] // field-order assertions (#970)
4922    fn comment_sections_link_back_to_their_items() {
4923        let doc = DoclingDocument {
4924            name: "c".into(),
4925            nodes: vec![
4926                Node::Commented {
4927                    comments: vec![0],
4928                    inner: Box::new(Node::Paragraph {
4929                        text: "annotated".into(),
4930                    }),
4931                },
4932                Node::Paragraph {
4933                    text: "plain".into(),
4934                },
4935                Node::CommentSection {
4936                    name: "comment-7".into(),
4937                    text: "[time: t]: note".into(),
4938                    refs_note_text: false,
4939                    grouped: true,
4940                },
4941            ],
4942            ..DoclingDocument::new("c")
4943        };
4944        let v = crate::json::to_json(&doc);
4945        // The group is the comment section; its only child is the notes text.
4946        assert_eq!(v["groups"][0]["label"], "comment_section");
4947        assert_eq!(v["groups"][0]["name"], "comment-7");
4948        assert_eq!(v["groups"][0]["content_layer"], "notes");
4949        assert_eq!(v["groups"][0]["children"][0]["$ref"], "#/texts/2");
4950        assert_eq!(v["texts"][2]["content_layer"], "notes");
4951        // The annotated item points back at the group; the plain one has no key.
4952        assert_eq!(v["texts"][0]["comments"][0]["$ref"], "#/groups/0");
4953        assert!(v["texts"][1].get("comments").is_none());
4954        // docling's key order: … prov, comments, orig, text.
4955        let keys: Vec<&str> = v["texts"][0]
4956            .as_object()
4957            .unwrap()
4958            .keys()
4959            .map(String::as_str)
4960            .collect();
4961        assert_eq!(
4962            &keys[keys.len() - 4..],
4963            &["prov", "comments", "orig", "text"]
4964        );
4965    }
4966
4967    fn picture(caption: &str, caption_parent: CaptionParent) -> Node {
4968        Node::Picture {
4969            caption: Some(caption.into()),
4970            caption_href: None,
4971            image: None,
4972            classification: None,
4973            description: None,
4974            caption_parent,
4975            caption_location: None,
4976        }
4977    }
4978
4979    fn group(children: Vec<Node>) -> Node {
4980        Node::Group {
4981            label: "section".into(),
4982            name: None,
4983            layer: None,
4984            children,
4985        }
4986    }
4987
4988    fn refs(v: &Value) -> Vec<&str> {
4989        v.as_array()
4990            .unwrap()
4991            .iter()
4992            .map(|r| r["$ref"].as_str().unwrap())
4993            .collect()
4994    }
4995
4996    /// #390: a declarative backend's caption is docling's `add_text` default —
4997    /// a body child, appended as it is created — wherever the picture sits:
4998    /// ahead of a top-level picture, behind the top-level item enclosing a
4999    /// nested one. The picture references it either way and has no children.
5000    #[test]
5001    fn a_body_caption_follows_the_enclosing_top_level_item() {
5002        let mut doc = DoclingDocument::new("t");
5003        doc.push(picture("top", CaptionParent::Body));
5004        doc.push(group(vec![
5005            Node::Paragraph { text: "p".into() },
5006            picture("nested", CaptionParent::Body),
5007        ]));
5008        doc.push(Node::Paragraph {
5009            text: "after".into(),
5010        });
5011        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
5012        assert_eq!(
5013            refs(&v["body"]["children"]),
5014            [
5015                "#/texts/0",
5016                "#/pictures/0",
5017                "#/groups/0",
5018                "#/texts/2",
5019                "#/texts/3"
5020            ]
5021        );
5022        assert_eq!(
5023            refs(&v["groups"][0]["children"]),
5024            ["#/texts/1", "#/pictures/1"]
5025        );
5026        for (cap, pic) in [(0, 0), (2, 1)] {
5027            assert_eq!(v["texts"][cap]["label"], "caption");
5028            assert_eq!(v["texts"][cap]["parent"]["$ref"], "#/body");
5029            assert_eq!(
5030                refs(&v["pictures"][pic]["captions"]),
5031                [format!("#/texts/{cap}")]
5032            );
5033            assert_eq!(v["pictures"][pic]["children"], serde_json::json!([]));
5034        }
5035    }
5036
5037    /// The PDF pipeline's caption is the picture's (or table's) own child,
5038    /// as docling attaches a layout caption.
5039    #[test]
5040    fn an_item_caption_is_the_items_first_child() {
5041        let mut doc = DoclingDocument::new("t");
5042        doc.push(picture("fig", CaptionParent::Item));
5043        doc.push(Node::Table(Table {
5044            rows: vec![vec!["a".into()]],
5045            caption: Some("tab".into()),
5046            caption_parent: CaptionParent::Item,
5047            ..Table::default()
5048        }));
5049        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
5050        assert_eq!(refs(&v["body"]["children"]), ["#/pictures/0", "#/tables/0"]);
5051        assert_eq!(v["texts"][0]["parent"]["$ref"], "#/pictures/0");
5052        assert_eq!(refs(&v["pictures"][0]["children"]), ["#/texts/0"]);
5053        assert_eq!(refs(&v["pictures"][0]["captions"]), ["#/texts/0"]);
5054        assert_eq!(v["texts"][1]["parent"]["$ref"], "#/tables/0");
5055        assert_eq!(refs(&v["tables"][0]["children"]), ["#/texts/1"]);
5056        assert_eq!(refs(&v["tables"][0]["captions"]), ["#/texts/1"]);
5057    }
5058
5059    /// A PDF picture's contained text (`Node::PictureChildren`) is written as
5060    /// docling's `_add_child_elements` writes it: items parented to the
5061    /// picture, after its caption in the picture's `children`, never in the
5062    /// body; a list item opens its own list group under the picture. The
5063    /// Markdown and the chunker's refs are unaffected.
5064    #[test]
5065    fn picture_children_hang_off_the_picture_after_its_caption() {
5066        let mut doc = DoclingDocument::new("t");
5067        doc.push(picture("fig", CaptionParent::Item));
5068        doc.push(Node::PictureChildren(vec![
5069            Node::Heading {
5070                level: 2,
5071                text: "in-figure title".into(),
5072            },
5073            Node::Paragraph {
5074                text: "axis label".into(),
5075            },
5076            Node::ListItem {
5077                ordered: false,
5078                number: 0,
5079                first_in_list: true,
5080                text: "callout".into(),
5081                level: 0,
5082                marker: None,
5083                location: None,
5084                split: None,
5085                dclx: None,
5086                href: None,
5087                layer: None,
5088            },
5089        ]));
5090        doc.push(Node::Paragraph {
5091            text: "after".into(),
5092        });
5093        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
5094        assert_eq!(refs(&v["body"]["children"]), ["#/pictures/0", "#/texts/4"]);
5095        assert_eq!(
5096            refs(&v["pictures"][0]["children"]),
5097            ["#/texts/0", "#/texts/1", "#/texts/2", "#/groups/0"]
5098        );
5099        assert_eq!(refs(&v["pictures"][0]["captions"]), ["#/texts/0"]);
5100        assert_eq!(v["texts"][1]["label"], "section_header");
5101        assert_eq!(v["texts"][2]["label"], "text");
5102        for t in 1..=2 {
5103            assert_eq!(v["texts"][t]["parent"]["$ref"], "#/pictures/0");
5104            assert_eq!(v["texts"][t]["content_layer"], "body");
5105        }
5106        assert_eq!(v["groups"][0]["parent"]["$ref"], "#/pictures/0");
5107        assert_eq!(v["texts"][3]["parent"]["$ref"], "#/groups/0");
5108        let md = doc.export_to_markdown();
5109        assert!(
5110            !md.contains("axis label") && !md.contains("callout"),
5111            "{md}"
5112        );
5113        assert!(md.contains("after"), "{md}");
5114    }
5115
5116    /// A container caption sits beside its item under the item's parent —
5117    /// ahead of it (an office chart's title) or behind it (an HTML
5118    /// `<figure>`'s table, whose figcaption docling adds after the table).
5119    #[test]
5120    fn a_container_caption_is_the_items_sibling() {
5121        let mut doc = DoclingDocument::new("t");
5122        doc.push(group(vec![
5123            picture("chart", CaptionParent::Container),
5124            Node::Table(Table {
5125                rows: vec![vec!["a".into()]],
5126                caption: Some("figcaption".into()),
5127                caption_parent: CaptionParent::ContainerAfter,
5128                ..Table::default()
5129            }),
5130        ]));
5131        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
5132        assert_eq!(refs(&v["body"]["children"]), ["#/groups/0"]);
5133        assert_eq!(
5134            refs(&v["groups"][0]["children"]),
5135            ["#/texts/0", "#/pictures/0", "#/tables/0", "#/texts/1"]
5136        );
5137        assert_eq!(v["texts"][0]["parent"]["$ref"], "#/groups/0");
5138        assert_eq!(v["texts"][1]["parent"]["$ref"], "#/groups/0");
5139        assert_eq!(v["pictures"][0]["children"], serde_json::json!([]));
5140        assert_eq!(v["tables"][0]["children"], serde_json::json!([]));
5141    }
5142
5143    /// A PDF footnote (#620 follow-up): the JSON keeps docling's
5144    /// `footnote` label, the raw text and the link as `hyperlink`; the
5145    /// Markdown still wraps the whole item as `[text](uri)`, and the plain
5146    /// text drops the link like docling-core's `export_to_text`.
5147    #[test]
5148    fn a_labeled_text_keeps_its_label_and_hyperlink_out_of_the_text() {
5149        let mut doc = DoclingDocument::new("t");
5150        doc.push(Node::LabeledText {
5151            label: "footnote".into(),
5152            text: "1 https://example.com/a\\_b".into(),
5153            href: Some("https://example.com/a_b".into()),
5154        });
5155        doc.push(Node::LabeledText {
5156            label: "footnote".into(),
5157            text: "© 2022 the authors".into(),
5158            href: None,
5159        });
5160        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
5161        let t = &v["texts"][0];
5162        assert_eq!(t["label"], "footnote");
5163        assert_eq!(t["text"], "1 https://example.com/a_b");
5164        assert_eq!(t["orig"], "1 https://example.com/a_b");
5165        assert_eq!(t["hyperlink"], "https://example.com/a_b");
5166        assert_eq!(v["texts"][1]["label"], "footnote");
5167        assert!(v["texts"][1].get("hyperlink").is_none());
5168        assert_eq!(
5169            doc.export_to_markdown(),
5170            "[1 https://example.com/a\\_b](https://example.com/a_b)\n\n© 2022 the authors\n"
5171        );
5172        assert_eq!(
5173            doc.export_to_text(),
5174            "1 https://example.com/a_b\n\n© 2022 the authors"
5175        );
5176    }
5177
5178    /// A marked PDF item (#1005, docling's `ScriptPositionModel._apply`):
5179    /// the item keeps its place with an empty text and holds an inline group
5180    /// of its runs, added after every other item; two such paragraphs stay
5181    /// separate HTML blocks; a linked footnote's link rides on its baseline
5182    /// runs only, so the marker stays out of it.
5183    #[test]
5184    fn script_runs_follow_docling() {
5185        use crate::{Script, ScriptRun, ScriptRunProv};
5186        let run = |text: &str, script, hyperlink: Option<&str>| ScriptRun {
5187            text: text.into(),
5188            script,
5189            prov: vec![ScriptRunProv {
5190                page_no: 1,
5191                bbox: [10.0, 700.0, 20.0, 690.0],
5192                charspan: [0, text.chars().count()],
5193            }],
5194            hyperlink: hyperlink.map(String::from),
5195        };
5196        let mut doc = DoclingDocument::new("t");
5197        doc.push(Node::PageInfo {
5198            page_no: 1,
5199            width: 612.0,
5200            height: 792.0,
5201        });
5202        let located = |inner: Node| Node::Located {
5203            location: [40, 80, 200, 90],
5204            inner: Box::new(inner),
5205        };
5206        doc.push(located(Node::ScriptText {
5207            inner: Box::new(Node::Paragraph {
5208                text: "E = mc2".into(),
5209            }),
5210            runs: vec![
5211                run("E = mc", Script::Baseline, None),
5212                run("2", Script::Super, None),
5213            ],
5214        }));
5215        doc.push(located(Node::ScriptText {
5216            inner: Box::new(Node::Paragraph { text: "H2O".into() }),
5217            runs: vec![
5218                run("H", Script::Baseline, None),
5219                run("2", Script::Sub, None),
5220                run("O", Script::Baseline, None),
5221            ],
5222        }));
5223        let url = "https://example.com/x";
5224        doc.push(located(Node::ScriptText {
5225            inner: Box::new(Node::LabeledText {
5226                label: "footnote".into(),
5227                text: format!("1[Note text]({url})"),
5228                href: None,
5229            }),
5230            runs: vec![
5231                run("1", Script::Super, None),
5232                run("Note text", Script::Baseline, Some(url)),
5233            ],
5234        }));
5235        doc.push(located(Node::Paragraph {
5236            text: "Plain line".into(),
5237        }));
5238
5239        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
5240        let texts = v["texts"].as_array().unwrap();
5241        // The items first, in place; the runs after them.
5242        assert_eq!(texts[0]["text"], "");
5243        assert_eq!(
5244            texts[0]["children"],
5245            serde_json::json!([{"$ref": "#/groups/0"}])
5246        );
5247        assert_eq!(texts[2]["label"], "footnote");
5248        assert_eq!(texts[2]["hyperlink"], url);
5249        assert_eq!(texts[3]["text"], "Plain line");
5250        assert_eq!(texts[4]["text"], "E = mc");
5251        assert_eq!(texts[5]["formatting"]["script"], "super");
5252        assert_eq!(texts[5]["prov"][0]["bbox"]["coord_origin"], "BOTTOMLEFT");
5253        assert_eq!(texts[7]["formatting"]["script"], "sub");
5254        assert_eq!(texts[9]["label"], "footnote");
5255        assert!(texts[9].get("hyperlink").is_none());
5256        assert_eq!(texts[10]["hyperlink"], url);
5257        assert_eq!(v["groups"][0]["label"], "inline");
5258        assert_eq!(v["groups"][0]["parent"]["$ref"], "#/texts/0");
5259
5260        assert_eq!(
5261            doc.export_to_markdown(),
5262            format!("E = mc2\n\nH2O\n\n1[Note text]({url})\n\nPlain line\n")
5263        );
5264        let html = doc.export_to_html();
5265        // Each marked item is a block of its own (the footnote too, as
5266        // docling-core renders it).
5267        assert_eq!(
5268            html.matches("<p><span class='inline-group'>").count(),
5269            3,
5270            "{html}"
5271        );
5272        assert!(html.contains("E = mc<sup>2</sup>"), "{html}");
5273        assert!(html.contains("H<sub>2</sub>O"), "{html}");
5274        assert!(
5275            html.contains(&format!("<sup>1</sup><a href=\"{url}\">Note text</a>")),
5276            "{html}"
5277        );
5278        let dclx = doc.export_to_doclang();
5279        assert!(
5280            dclx.contains("E = mc<superscript>2</superscript>"),
5281            "{dclx}"
5282        );
5283    }
5284}