Skip to main content

text_typeset/layout/
table.rs

1use crate::font::registry::FontRegistry;
2use crate::layout::block::{BlockLayout, BlockLayoutParams, layout_block};
3use crate::types::{DecorationKind, DecorationRect};
4
5/// Parameters for a table, extracted from text-document's TableSnapshot.
6pub struct TableLayoutParams {
7    pub table_id: usize,
8    pub rows: usize,
9    pub columns: usize,
10    /// Relative column widths (0.0-1.0). If empty, columns are distributed evenly.
11    pub column_widths: Vec<f32>,
12    pub border_width: f32,
13    pub cell_spacing: f32,
14    pub cell_padding: f32,
15    /// One entry per cell, in row-major order (row 0 col 0, row 0 col 1, ...).
16    pub cells: Vec<CellLayoutParams>,
17}
18
19/// Parameters for a single table cell.
20pub struct CellLayoutParams {
21    pub row: usize,
22    pub column: usize,
23    pub blocks: Vec<BlockLayoutParams>,
24    pub background_color: Option<[f32; 4]>,
25}
26
27/// Computed layout for an entire table.
28#[non_exhaustive]
29pub struct TableLayout {
30    pub table_id: usize,
31    /// Y position relative to document start (set by flow).
32    pub y: f32,
33    /// Total height of the table including borders.
34    pub total_height: f32,
35    /// Total width of the table.
36    pub total_width: f32,
37    /// Computed column x positions (left edge of each column's content area).
38    pub column_xs: Vec<f32>,
39    /// Computed column widths (content area, excluding padding).
40    pub column_content_widths: Vec<f32>,
41    /// Computed row y positions (top edge of each row's content area, relative to table top).
42    pub row_ys: Vec<f32>,
43    /// Computed row heights (content area).
44    pub row_heights: Vec<f32>,
45    /// Laid out cells. Each cell contains its block layouts.
46    pub cell_layouts: Vec<CellLayout>,
47    pub border_width: f32,
48    pub cell_padding: f32,
49}
50
51#[non_exhaustive]
52pub struct CellLayout {
53    pub row: usize,
54    pub column: usize,
55    pub blocks: Vec<BlockLayout>,
56    pub background_color: Option<[f32; 4]>,
57}
58
59/// Lay out a table: distribute column widths, lay out cell contents, compute row heights.
60pub fn layout_table(
61    registry: &FontRegistry,
62    params: &TableLayoutParams,
63    available_width: f32,
64    scale_factor: f32,
65    font_scale: f32,
66) -> TableLayout {
67    let cols = params.columns.max(1);
68    let rows = params.rows.max(1);
69    let border = params.border_width;
70    let padding = params.cell_padding;
71    let spacing = params.cell_spacing;
72
73    // Total overhead: borders + spacing + padding for all columns
74    let total_overhead =
75        border * 2.0 + spacing * (cols as f32 - 1.0).max(0.0) + padding * 2.0 * cols as f32;
76    let content_area = (available_width - total_overhead).max(0.0);
77
78    // Compute column widths
79    let column_content_widths =
80        compute_column_widths(&params.column_widths, cols, content_area, padding);
81
82    // Compute column x positions
83    let mut column_xs = Vec::with_capacity(cols);
84    let mut x = border;
85    for (c, &col_w) in column_content_widths.iter().enumerate() {
86        column_xs.push(x + padding);
87        x += padding * 2.0 + col_w;
88        if c < cols - 1 {
89            x += spacing;
90        }
91    }
92    let total_width = x + border;
93
94    // Lay out each cell's blocks
95    let mut cell_layouts = Vec::new();
96    // Track row heights (max cell content height per row)
97    let mut row_heights = vec![0.0f32; rows];
98
99    for cell_params in &params.cells {
100        let r = cell_params.row;
101        let c = cell_params.column;
102        if c >= cols || r >= rows {
103            continue;
104        }
105
106        let cell_width = column_content_widths[c];
107        let mut cell_blocks = Vec::new();
108        let mut cell_height = 0.0f32;
109
110        for block_params in &cell_params.blocks {
111            let block = layout_block(registry, block_params, cell_width, scale_factor, font_scale);
112            cell_height += block.height;
113            cell_blocks.push(block);
114        }
115
116        // Position blocks within the cell vertically
117        let mut block_y = 0.0f32;
118        for block in &mut cell_blocks {
119            block.y = block_y;
120            block_y += block.height;
121        }
122
123        row_heights[r] = row_heights[r].max(cell_height);
124
125        cell_layouts.push(CellLayout {
126            row: r,
127            column: c,
128            blocks: cell_blocks,
129            background_color: cell_params.background_color,
130        });
131    }
132
133    // Compute row y positions
134    let mut row_ys = Vec::with_capacity(rows);
135    let mut y = border;
136    for (r, &row_h) in row_heights.iter().enumerate() {
137        row_ys.push(y + padding);
138        y += padding * 2.0 + row_h;
139        if r < rows - 1 {
140            y += spacing;
141        }
142    }
143    let total_height = y + border;
144
145    TableLayout {
146        table_id: params.table_id,
147        y: 0.0, // set by flow
148        total_height,
149        total_width,
150        column_xs,
151        column_content_widths,
152        row_ys,
153        row_heights,
154        cell_layouts,
155        border_width: border,
156        cell_padding: padding,
157    }
158}
159
160fn compute_column_widths(
161    specified: &[f32],
162    cols: usize,
163    content_area: f32,
164    _padding: f32,
165) -> Vec<f32> {
166    // When no explicit widths, distribute content_area evenly.
167    // Clamp to a reasonable range: at least 1px (zero-width guard) and
168    // at most a sensible default when the viewport is unbounded.
169    let default_col_width = if content_area.is_finite() {
170        (content_area / cols as f32).max(1.0)
171    } else {
172        200.0
173    };
174
175    if specified.is_empty() || specified.len() != cols {
176        return vec![default_col_width; cols];
177    }
178
179    // Use specified proportions
180    let total: f32 = specified.iter().sum();
181    if total <= 0.0 {
182        return vec![default_col_width; cols];
183    }
184
185    specified
186        .iter()
187        .map(|&s| (s / total) * content_area)
188        .collect()
189}
190
191/// Generate border and background decoration rects for a top-level table.
192pub fn generate_table_decorations(table: &TableLayout, scroll_offset: f32) -> Vec<DecorationRect> {
193    generate_table_decorations_at(table, 0.0, 0.0, scroll_offset)
194}
195
196/// Generate border and background decoration rects for a table whose
197/// origin is shifted by `(offset_x, offset_y)` — a table nested inside a
198/// frame (e.g. a blockquote), where the offsets are the frame's content
199/// origin.
200pub fn generate_table_decorations_at(
201    table: &TableLayout,
202    offset_x: f32,
203    offset_y: f32,
204    scroll_offset: f32,
205) -> Vec<DecorationRect> {
206    let mut decorations = Vec::new();
207    let table_y = offset_y + table.y - scroll_offset;
208
209    // Outer table border
210    if table.border_width > 0.0 {
211        let bw = table.border_width;
212        let color = [0.6, 0.6, 0.6, 1.0]; // gray border
213        // Top
214        decorations.push(DecorationRect {
215            rect: [offset_x, table_y, table.total_width, bw],
216            color,
217            kind: DecorationKind::TableBorder,
218        });
219        // Bottom
220        decorations.push(DecorationRect {
221            rect: [
222                offset_x,
223                table_y + table.total_height - bw,
224                table.total_width,
225                bw,
226            ],
227            color,
228            kind: DecorationKind::TableBorder,
229        });
230        // Left
231        decorations.push(DecorationRect {
232            rect: [offset_x, table_y, bw, table.total_height],
233            color,
234            kind: DecorationKind::TableBorder,
235        });
236        // Right
237        decorations.push(DecorationRect {
238            rect: [
239                offset_x + table.total_width - bw,
240                table_y,
241                bw,
242                table.total_height,
243            ],
244            color,
245            kind: DecorationKind::TableBorder,
246        });
247
248        // Row borders
249        for r in 1..table.row_ys.len() {
250            let row_y = table.row_ys[r] - table.cell_padding;
251            decorations.push(DecorationRect {
252                rect: [offset_x, table_y + row_y - bw / 2.0, table.total_width, bw],
253                color,
254                kind: DecorationKind::TableBorder,
255            });
256        }
257
258        // Column borders
259        for c in 1..table.column_xs.len() {
260            let col_x = table.column_xs[c] - table.cell_padding;
261            decorations.push(DecorationRect {
262                rect: [offset_x + col_x - bw / 2.0, table_y, bw, table.total_height],
263                color,
264                kind: DecorationKind::TableBorder,
265            });
266        }
267    }
268
269    // Cell backgrounds
270    for cell in &table.cell_layouts {
271        if let Some(bg_color) = cell.background_color
272            && cell.row < table.row_ys.len()
273            && cell.column < table.column_xs.len()
274        {
275            let cx = table.column_xs[cell.column] - table.cell_padding;
276            let cy = table.row_ys[cell.row] - table.cell_padding;
277            let cw = table.column_content_widths[cell.column] + table.cell_padding * 2.0;
278            let ch = table.row_heights[cell.row] + table.cell_padding * 2.0;
279            decorations.push(DecorationRect {
280                rect: [offset_x + cx, table_y + cy, cw, ch],
281                color: bg_color,
282                kind: DecorationKind::TableCellBackground,
283            });
284        }
285    }
286
287    decorations
288}