Skip to main content

jubarte_doc/inspect/
tables.rs

1// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
2//
3// SPDX-License-Identifier: Apache-2.0
4
5//! Body tables as grids of cells, each cell with the ids of the paragraphs
6//! it holds.
7
8use std::collections::HashMap;
9
10use serde::Serialize;
11
12use super::{body_paragraph_nodes, project_paragraph};
13use crate::namespaces::{MC, W};
14use crate::xmllinq::{Dom, NodeId, XName};
15
16/// A top-level body table, numbered as the view's `tN`.
17#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
18pub struct Table {
19    /// Position among top-level body tables in document order.
20    pub index: usize,
21    /// Cells row by row, as they appear in the XML: a merged cell is one
22    /// cell, so rows can differ in length.
23    pub rows: Vec<Vec<TableCell>>,
24    /// Leading rows marked to repeat as a header (`w:tblHeader`).
25    pub header_rows: usize,
26    /// Grid column widths (`w:gridCol`) in twentieths of a point; 0 when a
27    /// width is missing or unreadable.
28    pub widths_dxa: Vec<u32>,
29    /// Tables nested directly in this table's cells, in document order.
30    pub nested: Vec<NestedTable>,
31}
32
33/// A table nested in a cell. It has a parent cell path, rather than a `tN`
34/// index in the body. Its own nested tables carry the full cell path.
35#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
36pub struct NestedTable {
37    /// Containing cell, for example `t0.row2.cell0` or
38    /// `t0.row2.cell0.t0.row0.cell1`.
39    pub parent: String,
40    /// The cell grid, with the same own-paragraph rule as [`Table::rows`].
41    pub rows: Vec<Vec<TableCell>>,
42    /// Leading rows marked to repeat as a header.
43    pub header_rows: usize,
44    /// Grid column widths in twentieths of a point.
45    pub widths_dxa: Vec<u32>,
46    /// Tables nested directly in this table's cells, in document order.
47    pub nested: Vec<NestedTable>,
48}
49
50/// A table cell.
51#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
52pub struct TableCell {
53    /// Ids (`body:p:N`) of the cell's own paragraphs; a nested table's
54    /// paragraphs belong to that table's cells.
55    pub paragraph_ids: Vec<String>,
56    /// Those paragraphs' text, joined with `\n`.
57    pub text: String,
58}
59
60/// The nearest ancestor named `name`.
61fn nearest(dom: &Dom, node: NodeId, name: &XName) -> Option<NodeId> {
62    dom.ancestors(node, Some(name)).first().copied()
63}
64
65/// Whether a table is hidden from tN addressing by an opaque wrapper.
66pub(crate) fn opaque_table(dom: &Dom, table: NodeId) -> bool {
67    super::in_text_box(dom, table) || nearest(dom, table, &MC::name("AlternateContent")).is_some()
68}
69
70/// The tables numbered by the view: outside cells, text boxes and AC.
71#[doc(hidden)]
72pub fn top_level_table_nodes(dom: &Dom, body: NodeId) -> Vec<NodeId> {
73    dom.descendants(body, Some(&W::tbl()))
74        .into_iter()
75        .filter(|&table| nearest(dom, table, &W::tc()).is_none() && !opaque_table(dom, table))
76        .collect()
77}
78
79/// Top-level body tables, with their nested tables under their cells.
80pub(super) fn body_tables(dom: &Dom, body: NodeId) -> Vec<Table> {
81    let tc = W::tc();
82    // Each addressable paragraph, grouped under the cell that holds it.
83    let mut by_cell: HashMap<NodeId, Vec<(usize, NodeId)>> = HashMap::new();
84    for (index, p) in body_paragraph_nodes(dom, body).into_iter().enumerate() {
85        if let Some(cell) = nearest(dom, p, &tc) {
86            by_cell.entry(cell).or_default().push((index, p));
87        }
88    }
89    top_level_table_nodes(dom, body)
90        .into_iter()
91        .enumerate()
92        .map(|(index, table)| {
93            let grid = table_grid(dom, table, &format!("t{index}"), &by_cell);
94            Table {
95                index,
96                rows: grid.rows,
97                header_rows: grid.header_rows,
98                widths_dxa: grid.widths_dxa,
99                nested: grid.nested,
100            }
101        })
102        .collect()
103}
104
105struct Grid {
106    rows: Vec<Vec<TableCell>>,
107    header_rows: usize,
108    widths_dxa: Vec<u32>,
109    nested: Vec<NestedTable>,
110}
111
112fn table_grid(
113    dom: &Dom,
114    table: NodeId,
115    path: &str,
116    by_cell: &HashMap<NodeId, Vec<(usize, NodeId)>>,
117) -> Grid {
118    let tc = W::tc();
119    let tr = W::tr();
120    let tbl = W::tbl();
121    let rows: Vec<NodeId> = dom
122        .descendants(table, Some(&tr))
123        .into_iter()
124        .filter(|&row| nearest(dom, row, &tbl) == Some(table))
125        .collect();
126    let header_rows = rows
127        .iter()
128        .take_while(|&&row| {
129            dom.element(row, &W::tr_pr())
130                .and_then(|pr| dom.element(pr, &W::name("tblHeader")))
131                .is_some_and(|h| {
132                    !matches!(dom.attribute(h, &W::val()), Some("0" | "false" | "off"))
133                })
134        })
135        .count();
136    let widths_dxa = dom
137        .element(table, &W::name("tblGrid"))
138        .map(|grid| {
139            dom.elements(grid, Some(&W::grid_col()))
140                .into_iter()
141                .map(|col| {
142                    dom.attribute(col, &W::w())
143                        .and_then(|w| w.parse::<u32>().ok())
144                        .unwrap_or(0)
145                })
146                .collect()
147        })
148        .unwrap_or_default();
149    let mut nested = Vec::new();
150    let rows = rows
151        .into_iter()
152        .enumerate()
153        .map(|(r, row)| {
154            dom.descendants(row, Some(&tc))
155                .into_iter()
156                .filter(|&cell| nearest(dom, cell, &tr) == Some(row))
157                .enumerate()
158                .map(|(c, cell)| {
159                    let parent = format!("{path}.row{r}.cell{c}");
160                    for (index, child) in dom
161                        .descendants(cell, Some(&tbl))
162                        .into_iter()
163                        .filter(|&child| {
164                            nearest(dom, child, &tc) == Some(cell) && !opaque_table(dom, child)
165                        })
166                        .enumerate()
167                    {
168                        let grid = table_grid(dom, child, &format!("{parent}.t{index}"), by_cell);
169                        nested.push(NestedTable {
170                            parent: parent.clone(),
171                            rows: grid.rows,
172                            header_rows: grid.header_rows,
173                            widths_dxa: grid.widths_dxa,
174                            nested: grid.nested,
175                        });
176                    }
177                    let own = by_cell.get(&cell).map(Vec::as_slice).unwrap_or_default();
178                    TableCell {
179                        paragraph_ids: own
180                            .iter()
181                            .map(|&(i, _)| crate::ids::paragraph_id("body", i))
182                            .collect(),
183                        text: own
184                            .iter()
185                            .map(|&(_, p)| project_paragraph(dom, p).text)
186                            .collect::<Vec<_>>()
187                            .join("\n"),
188                    }
189                })
190                .collect()
191        })
192        .collect();
193    Grid {
194        rows,
195        header_rows,
196        widths_dxa,
197        nested,
198    }
199}