Skip to main content

strata_layout/
table.rs

1//! W3C CSS 2.1 Chapter 17 Table Layout Engine.
2//!
3//! Implements W3C CSS 2.1 §17.5 (Table Layout), §17.5.1 (Fixed & Auto Sizing),
4//! §17.5.2 (Auto Table Sizing Algorithm), §17.5.3 (Cell Vertical Alignment),
5//! §17.4 (Table Captions & Wrapper Box), and §17.6 (Borders: Separated vs Collapsed).
6
7#![allow(clippy::needless_range_loop)]
8
9use crate::box_model::{clamp_dimension, resolve_dimension};
10use crate::geometry::{LayoutGeometry, Rect};
11use crate::intrinsic::compute_min_max_sizes;
12use crate::tree::LayoutNode;
13use strata_style::types::{
14    BorderCollapse, BorderStyle, CaptionSide, Color, Display, Position, TableLayout, VerticalAlign,
15};
16
17/// Origin element type of a border edge in the collapsing border model.
18/// Priority order per CSS 2.1 §17.6.2.1:
19/// cell > row > row group > column > colgroup > table.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
21pub enum ElementSource {
22    Table = 0,
23    ColGroup = 1,
24    Col = 2,
25    RowGroup = 3,
26    Row = 4,
27    Cell = 5,
28}
29
30/// A resolved or candidate border edge in the collapsing border model (CSS 2.1 §17.6.2).
31#[derive(Debug, Clone, Copy, PartialEq)]
32pub struct CollapsedBorderEdge {
33    pub width: f32,
34    pub style: BorderStyle,
35    pub color: Option<Color>,
36    pub source: ElementSource,
37}
38
39impl Default for CollapsedBorderEdge {
40    fn default() -> Self {
41        Self {
42            width: 0.0,
43            style: BorderStyle::None,
44            color: None,
45            source: ElementSource::Table,
46        }
47    }
48}
49
50/// Computes the priority ranking of a border style per CSS 2.1 §17.6.2.1:
51/// 'double' > 'solid' > 'dashed' > 'dotted' > 'none'/'hidden'.
52#[inline]
53pub fn border_style_priority(style: BorderStyle) -> u8 {
54    match style {
55        BorderStyle::Double => 4,
56        BorderStyle::Solid => 3,
57        BorderStyle::Dashed => 2,
58        BorderStyle::Dotted => 1,
59        BorderStyle::None | BorderStyle::Hidden => 0,
60    }
61}
62
63/// Resolves the winning border between two conflicting edges meeting at a grid boundary (CSS 2.1 §17.6.2.1).
64///
65/// `first` is the edge from the top or left element.
66/// `second` is the edge from the bottom or right element.
67pub fn resolve_collapsed_border(
68    first: CollapsedBorderEdge,
69    second: CollapsedBorderEdge,
70) -> CollapsedBorderEdge {
71    // 1. 'border-style: hidden' takes precedence over all other conflicting borders
72    // and suppresses border rendering entirely (width = 0).
73    if first.style == BorderStyle::Hidden || second.style == BorderStyle::Hidden {
74        return CollapsedBorderEdge {
75            width: 0.0,
76            style: BorderStyle::Hidden,
77            color: None,
78            source: if first.style == BorderStyle::Hidden {
79                first.source
80            } else {
81                second.source
82            },
83        };
84    }
85
86    // 2. 'border-style: none' has the lowest priority: any specified border wins over 'none'.
87    let first_is_none = first.style == BorderStyle::None || first.width <= 0.0;
88    let second_is_none = second.style == BorderStyle::None || second.width <= 0.0;
89
90    if first_is_none && !second_is_none {
91        return second;
92    }
93    if !first_is_none && second_is_none {
94        return first;
95    }
96    if first_is_none && second_is_none {
97        return CollapsedBorderEdge::default();
98    }
99
100    // 3. Wider border wins over narrower.
101    const EPSILON: f32 = 0.001;
102    if (first.width - second.width).abs() > EPSILON {
103        return if first.width > second.width {
104            first
105        } else {
106            second
107        };
108    }
109
110    // 4. If widths are identical, style priority: double > solid > dashed > dotted
111    let prio_first = border_style_priority(first.style);
112    let prio_second = border_style_priority(second.style);
113    if prio_first != prio_second {
114        return if prio_first > prio_second {
115            first
116        } else {
117            second
118        };
119    }
120
121    // 5. If styles and widths are identical, element origin priority:
122    // cell > row > row group > column > colgroup > table.
123    if first.source != second.source {
124        return if first.source > second.source {
125            first
126        } else {
127            second
128        };
129    }
130
131    // 6. When two elements of the same type have conflicting borders of the same
132    // width and style, the border from the cell to the left / top wins.
133    first
134}
135
136/// 2D grid matrix storing resolved collapsed borders and boundary coordinates (CSS 2.1 §17.6.2).
137#[derive(Debug, Clone, PartialEq)]
138pub struct TableBorderGrid {
139    pub num_rows: usize,
140    pub num_cols: usize,
141    /// Horizontal boundary edges: `(num_rows + 1)` rows by `num_cols` columns.
142    pub horizontal_edges: Vec<Vec<CollapsedBorderEdge>>,
143    /// Vertical boundary edges: `num_rows` rows by `(num_cols + 1)` columns.
144    pub vertical_edges: Vec<Vec<CollapsedBorderEdge>>,
145    /// Y coordinates of the `num_rows + 1` horizontal grid lines.
146    pub row_positions: Vec<f32>,
147    /// X coordinates of the `num_cols + 1` vertical grid lines.
148    pub col_positions: Vec<f32>,
149}
150
151impl TableBorderGrid {
152    pub fn new(num_rows: usize, num_cols: usize) -> Self {
153        Self {
154            num_rows,
155            num_cols,
156            horizontal_edges: vec![vec![CollapsedBorderEdge::default(); num_cols]; num_rows + 1],
157            vertical_edges: vec![vec![CollapsedBorderEdge::default(); num_cols + 1]; num_rows],
158            row_positions: vec![0.0; num_rows + 1],
159            col_positions: vec![0.0; num_cols + 1],
160        }
161    }
162
163    pub fn translate(&mut self, dx: f32, dy: f32) {
164        for y in &mut self.row_positions {
165            *y += dy;
166        }
167        for x in &mut self.col_positions {
168            *x += dx;
169        }
170    }
171}
172
173/// Location of a table cell within the container's hierarchy.
174#[derive(Debug, Clone, Copy, PartialEq, Eq)]
175pub struct CellLocation {
176    pub group_idx: Option<usize>,
177    pub row_idx: usize,
178    pub cell_idx: usize,
179}
180
181/// A cell placed within the 2D table grid matrix.
182#[derive(Debug, Clone)]
183struct PlacedCell {
184    loc: CellLocation,
185    row_start: usize,
186    col_start: usize,
187    col_span: usize,
188    row_span: usize,
189    min_w: f32,
190    max_w: f32,
191    baseline: f32,
192}
193
194/// Reference to a row within the table hierarchy.
195#[derive(Debug, Clone, Copy, PartialEq, Eq)]
196struct RowLocation {
197    group_idx: Option<usize>,
198    row_idx: usize,
199}
200
201/// Solves W3C CSS Table Layout for a table container and its rows/cells.
202pub fn solve_table(container: &mut LayoutNode, available_width: f32, available_height: f32) {
203    solve_table_guarded(
204        container,
205        available_width,
206        available_height,
207        crate::tree::LayoutDepthGuard::root(),
208    );
209}
210
211/// Solves W3C CSS Table Layout with an active depth guard to prevent stack overflow.
212pub fn solve_table_guarded(
213    container: &mut LayoutNode,
214    available_width: f32,
215    available_height: f32,
216    guard: crate::tree::LayoutDepthGuard,
217) {
218    let _prof = crate::prof::Scope::new(crate::prof::Slot::Table);
219    let padding = container.style.padding;
220    let border = container.style.border_width;
221    let margin = container.style.margin;
222
223    let (h_spacing, v_spacing) = match container.style.border_collapse {
224        BorderCollapse::Collapse => (0.0, 0.0),
225        BorderCollapse::Separate => container.style.border_spacing,
226    };
227
228    // 1. Discover Table Captions and Rows
229    let mut top_captions: Vec<usize> = Vec::new();
230    let mut bottom_captions: Vec<usize> = Vec::new();
231    let mut rows: Vec<RowLocation> = Vec::new();
232
233    for (i, child) in container.children.iter().enumerate() {
234        match child.style.display {
235            Display::TableCaption => {
236                if child.style.caption_side == CaptionSide::Bottom {
237                    bottom_captions.push(i);
238                } else {
239                    top_captions.push(i);
240                }
241            }
242            Display::TableRowGroup | Display::TableHeaderGroup | Display::TableFooterGroup => {
243                for (r, row) in child.children.iter().enumerate() {
244                    if row.style.display == Display::TableRow {
245                        rows.push(RowLocation {
246                            group_idx: Some(i),
247                            row_idx: r,
248                        });
249                    }
250                }
251            }
252            Display::TableRow => {
253                rows.push(RowLocation {
254                    group_idx: None,
255                    row_idx: i,
256                });
257            }
258            _ => {}
259        }
260    }
261
262    let child_guard = guard.enter();
263
264    if rows.is_empty() {
265        let mut total_h = padding.top + padding.bottom + border.top + border.bottom;
266        let w = resolve_dimension(container.style.width, available_width).unwrap_or(0.0);
267        let table_origin_x = container.geometry.border_box.x;
268        let table_origin_y = container.geometry.border_box.y;
269
270        let cg = child_guard.unwrap_or(guard);
271        for &cap_idx in top_captions.iter().chain(bottom_captions.iter()) {
272            let cap = &mut container.children[cap_idx];
273            cap.compute_layout_guarded(w, available_height, None, 0.0, cg);
274            let cap_h = cap.geometry.border_box.height;
275            let cap_m = cap.style.margin;
276            cap.geometry = LayoutGeometry::from_border_box(
277                Rect::new(
278                    table_origin_x + border.left + padding.left + cap_m.left,
279                    table_origin_y + total_h + cap_m.top,
280                    w,
281                    cap_h,
282                ),
283                cap.style.padding,
284                cap.style.border_width,
285                cap_m,
286            );
287            total_h += cap_m.top + cap_h + cap_m.bottom;
288        }
289
290        container.geometry = LayoutGeometry::from_border_box(
291            Rect::new(table_origin_x, table_origin_y, w, total_h),
292            padding,
293            border,
294            margin,
295        );
296        return;
297    }
298
299    // 2. Build 2D Grid Matrix and place cells considering colspans and rowspans
300    let mut occupied: Vec<Vec<bool>> = Vec::new();
301    let mut placed_cells: Vec<PlacedCell> = Vec::new();
302
303    for (r_idx, row_loc) in rows.iter().enumerate() {
304        if occupied.len() <= r_idx {
305            occupied.resize(r_idx + 1, Vec::new());
306        }
307
308        let cell_count = get_row(container, *row_loc).children.len();
309        let mut col_cursor = 0;
310
311        for c_idx in 0..cell_count {
312            let (col_span, row_span) = {
313                let cell = get_cell(
314                    container,
315                    CellLocation {
316                        group_idx: row_loc.group_idx,
317                        row_idx: row_loc.row_idx,
318                        cell_idx: c_idx,
319                    },
320                );
321                if cell.style.display == Display::None
322                    || cell.style.position == Position::Absolute
323                    || cell.style.position == Position::Fixed
324                {
325                    continue;
326                }
327                (
328                    cell.style.colspan.max(1) as usize,
329                    cell.style.rowspan.max(1) as usize,
330                )
331            };
332
333            // Advance cursor past occupied cells
334            while col_cursor < occupied[r_idx].len() && occupied[r_idx][col_cursor] {
335                col_cursor += 1;
336            }
337
338            let start_col = col_cursor;
339            let end_col = start_col + col_span;
340            let end_row = r_idx + row_span;
341
342            // Expand occupancy matrix
343            if occupied.len() < end_row {
344                occupied.resize(end_row, Vec::new());
345            }
346            for r in r_idx..end_row {
347                if occupied[r].len() < end_col {
348                    occupied[r].resize(end_col, false);
349                }
350                for c in start_col..end_col {
351                    occupied[r][c] = true;
352                }
353            }
354
355            placed_cells.push(PlacedCell {
356                loc: CellLocation {
357                    group_idx: row_loc.group_idx,
358                    row_idx: row_loc.row_idx,
359                    cell_idx: c_idx,
360                },
361                row_start: r_idx,
362                col_start: start_col,
363                col_span,
364                row_span,
365                min_w: 0.0,
366                max_w: 0.0,
367                baseline: 0.0,
368            });
369
370            col_cursor = end_col;
371        }
372    }
373
374    let num_cols = occupied.iter().map(|r| r.len()).max().unwrap_or(0);
375    let num_rows = occupied.len();
376
377    if num_cols == 0 || num_rows == 0 {
378        return;
379    }
380
381    // Resolve shared horizontal and vertical borders (CSS 2.1 §17.6.2).
382    let collapsed = container.style.border_collapse == BorderCollapse::Collapse;
383    let mut table_grid = if collapsed {
384        Some(TableBorderGrid::new(num_rows, num_cols))
385    } else {
386        None
387    };
388
389    if collapsed {
390        // Propagate border_collapse = Collapse to cells and rows
391        for row_loc in &rows {
392            let row = get_row_mut(container, *row_loc);
393            row.style.border_collapse = BorderCollapse::Collapse;
394            for cell in &mut row.children {
395                if cell.style.display == Display::TableCell {
396                    cell.style.border_collapse = BorderCollapse::Collapse;
397                }
398            }
399        }
400
401        // Build 2D occupancy mapping for O(1) cell lookup at boundaries
402        let mut cell_at = vec![vec![None; num_cols]; num_rows];
403        for (i, pc) in placed_cells.iter().enumerate() {
404            let end_r = (pc.row_start + pc.row_span).min(num_rows);
405            let end_c = (pc.col_start + pc.col_span).min(num_cols);
406            for r in pc.row_start..end_r {
407                for c in pc.col_start..end_c {
408                    cell_at[r][c] = Some(i);
409                }
410            }
411        }
412
413        if let Some(ref mut grid) = table_grid {
414            // Resolve horizontal edges (num_rows + 1 boundaries, num_cols columns)
415            for r in 0..=num_rows {
416                for c in 0..num_cols {
417                    // 1. Top candidate (from elements above boundary r)
418                    let top_candidate = if r == 0 {
419                        // Table top border
420                        if container.style.border_width.top > 0.0
421                            || container.style.border_style == BorderStyle::Hidden
422                        {
423                            CollapsedBorderEdge {
424                                width: container.style.border_width.top,
425                                style: container.style.border_style,
426                                color: container.style.border_color,
427                                source: ElementSource::Table,
428                            }
429                        } else {
430                            CollapsedBorderEdge::default()
431                        }
432                    } else {
433                        // Check cell above: cell ending at row r
434                        let cell_edge = if let Some(cell_idx) = cell_at[r - 1][c] {
435                            let pc = &placed_cells[cell_idx];
436                            if pc.row_start + pc.row_span == r {
437                                let cell = get_cell(container, pc.loc);
438                                CollapsedBorderEdge {
439                                    width: cell.style.border_width.bottom,
440                                    style: cell.style.border_style,
441                                    color: cell.style.border_color,
442                                    source: ElementSource::Cell,
443                                }
444                            } else {
445                                CollapsedBorderEdge::default()
446                            }
447                        } else {
448                            CollapsedBorderEdge::default()
449                        };
450
451                        // Check row above: row r - 1 bottom border
452                        let row = get_row(container, rows[r - 1]);
453                        let row_edge = if row.style.border_width.bottom > 0.0
454                            || row.style.border_style == BorderStyle::Hidden
455                        {
456                            CollapsedBorderEdge {
457                                width: row.style.border_width.bottom,
458                                style: row.style.border_style,
459                                color: row.style.border_color,
460                                source: ElementSource::Row,
461                            }
462                        } else {
463                            CollapsedBorderEdge::default()
464                        };
465
466                        resolve_collapsed_border(row_edge, cell_edge)
467                    };
468
469                    // 2. Bottom candidate (from elements below boundary r)
470                    let bottom_candidate = if r == num_rows {
471                        // Table bottom border
472                        if container.style.border_width.bottom > 0.0
473                            || container.style.border_style == BorderStyle::Hidden
474                        {
475                            CollapsedBorderEdge {
476                                width: container.style.border_width.bottom,
477                                style: container.style.border_style,
478                                color: container.style.border_color,
479                                source: ElementSource::Table,
480                            }
481                        } else {
482                            CollapsedBorderEdge::default()
483                        }
484                    } else {
485                        // Check cell below: cell starting at row r
486                        let cell_edge = if let Some(cell_idx) = cell_at[r][c] {
487                            let pc = &placed_cells[cell_idx];
488                            if pc.row_start == r {
489                                let cell = get_cell(container, pc.loc);
490                                CollapsedBorderEdge {
491                                    width: cell.style.border_width.top,
492                                    style: cell.style.border_style,
493                                    color: cell.style.border_color,
494                                    source: ElementSource::Cell,
495                                }
496                            } else {
497                                CollapsedBorderEdge::default()
498                            }
499                        } else {
500                            CollapsedBorderEdge::default()
501                        };
502
503                        // Check row below: row r top border
504                        let row = get_row(container, rows[r]);
505                        let row_edge = if row.style.border_width.top > 0.0
506                            || row.style.border_style == BorderStyle::Hidden
507                        {
508                            CollapsedBorderEdge {
509                                width: row.style.border_width.top,
510                                style: row.style.border_style,
511                                color: row.style.border_color,
512                                source: ElementSource::Row,
513                            }
514                        } else {
515                            CollapsedBorderEdge::default()
516                        };
517
518                        resolve_collapsed_border(row_edge, cell_edge)
519                    };
520
521                    grid.horizontal_edges[r][c] =
522                        resolve_collapsed_border(top_candidate, bottom_candidate);
523                }
524            }
525
526            // Resolve vertical edges (num_rows rows, num_cols + 1 boundaries)
527            for r in 0..num_rows {
528                for c in 0..=num_cols {
529                    // 1. Left candidate (from elements left of boundary c)
530                    let left_candidate = if c == 0 {
531                        // Table left border
532                        if container.style.border_width.left > 0.0
533                            || container.style.border_style == BorderStyle::Hidden
534                        {
535                            CollapsedBorderEdge {
536                                width: container.style.border_width.left,
537                                style: container.style.border_style,
538                                color: container.style.border_color,
539                                source: ElementSource::Table,
540                            }
541                        } else {
542                            CollapsedBorderEdge::default()
543                        }
544                    } else {
545                        // Check cell left: cell ending at column c
546                        if let Some(cell_idx) = cell_at[r][c - 1] {
547                            let pc = &placed_cells[cell_idx];
548                            if pc.col_start + pc.col_span == c {
549                                let cell = get_cell(container, pc.loc);
550                                CollapsedBorderEdge {
551                                    width: cell.style.border_width.right,
552                                    style: cell.style.border_style,
553                                    color: cell.style.border_color,
554                                    source: ElementSource::Cell,
555                                }
556                            } else {
557                                CollapsedBorderEdge::default()
558                            }
559                        } else {
560                            CollapsedBorderEdge::default()
561                        }
562                    };
563
564                    // 2. Right candidate (from elements right of boundary c)
565                    let right_candidate = if c == num_cols {
566                        // Table right border
567                        if container.style.border_width.right > 0.0
568                            || container.style.border_style == BorderStyle::Hidden
569                        {
570                            CollapsedBorderEdge {
571                                width: container.style.border_width.right,
572                                style: container.style.border_style,
573                                color: container.style.border_color,
574                                source: ElementSource::Table,
575                            }
576                        } else {
577                            CollapsedBorderEdge::default()
578                        }
579                    } else {
580                        // Check cell right: cell starting at column c
581                        if let Some(cell_idx) = cell_at[r][c] {
582                            let pc = &placed_cells[cell_idx];
583                            if pc.col_start == c {
584                                let cell = get_cell(container, pc.loc);
585                                CollapsedBorderEdge {
586                                    width: cell.style.border_width.left,
587                                    style: cell.style.border_style,
588                                    color: cell.style.border_color,
589                                    source: ElementSource::Cell,
590                                }
591                            } else {
592                                CollapsedBorderEdge::default()
593                            }
594                        } else {
595                            CollapsedBorderEdge::default()
596                        }
597                    };
598
599                    grid.vertical_edges[r][c] =
600                        resolve_collapsed_border(left_candidate, right_candidate);
601                }
602            }
603        }
604    }
605
606    let mut row_boundary = vec![0.0f32; num_rows + 1];
607    if collapsed {
608        if let Some(ref grid) = table_grid {
609            for r in 0..=num_rows {
610                let max_w = grid.horizontal_edges[r]
611                    .iter()
612                    .map(|edge| edge.width)
613                    .fold(0.0f32, f32::max);
614                row_boundary[r] = max_w;
615            }
616        }
617    }
618
619    // 3. Resolve Target Inner Width
620    let total_h_spacing = (num_cols.saturating_sub(1)) as f32 * h_spacing;
621    let table_h_extras =
622        padding.left + padding.right + border.left + border.right + total_h_spacing;
623
624    let is_fixed = container.style.table_layout == TableLayout::Fixed;
625
626    let col_w = if is_fixed {
627        // W3C CSS 2.1 §17.5.1 Fixed Table Layout
628        let target_inner_w = match resolve_dimension(container.style.width, available_width) {
629            Some(w) => {
630                let clamped = clamp_dimension(
631                    w,
632                    container.style.min_width,
633                    container.style.max_width,
634                    available_width,
635                );
636                (clamped - table_h_extras).max(0.0)
637            }
638            None => (available_width - margin.left - margin.right - table_h_extras).max(0.0),
639        };
640
641        let mut fixed_col_w = vec![0.0f32; num_cols];
642        let mut assigned = vec![false; num_cols];
643        let mut assigned_sum = 0.0f32;
644        let mut unassigned_count = 0;
645
646        // Inspect cells in row 0 for explicit column widths
647        for pc in &placed_cells {
648            if pc.row_start == 0 && pc.col_span == 1 {
649                let cell = get_cell(container, pc.loc);
650                let col = pc.col_start;
651                if let Some(explicit_w) = resolve_dimension(cell.style.width, target_inner_w) {
652                    fixed_col_w[col] = explicit_w;
653                    assigned[col] = true;
654                    assigned_sum += explicit_w;
655                }
656            }
657        }
658
659        for c in 0..num_cols {
660            if !assigned[c] {
661                unassigned_count += 1;
662            }
663        }
664
665        if unassigned_count > 0 {
666            let remaining_w = (target_inner_w - assigned_sum).max(0.0);
667            let per_col = remaining_w / unassigned_count as f32;
668            for c in 0..num_cols {
669                if !assigned[c] {
670                    fixed_col_w[c] = per_col;
671                }
672            }
673        } else if assigned_sum > 0.0 && assigned_sum < target_inner_w {
674            let extra = target_inner_w - assigned_sum;
675            for c in 0..num_cols {
676                fixed_col_w[c] += extra * (fixed_col_w[c] / assigned_sum);
677            }
678        } else if target_inner_w > 0.0 && assigned_sum == 0.0 {
679            let equal_w = target_inner_w / num_cols as f32;
680            for c in 0..num_cols {
681                fixed_col_w[c] = equal_w;
682            }
683        }
684
685        fixed_col_w
686    } else {
687        // W3C CSS 2.1 §17.5.2 Auto Table Layout Pass
688        let mut col_min = vec![0.0f32; num_cols];
689        let mut col_max = vec![0.0f32; num_cols];
690
691        for pc in &mut placed_cells {
692            let cell = get_cell_mut(container, pc.loc);
693            let min_max = compute_min_max_sizes(cell, None);
694            let cell_padding = cell.style.padding;
695            let cell_border = cell.style.border_width;
696            let h_extra =
697                cell_padding.left + cell_padding.right + cell_border.left + cell_border.right;
698
699            let mut min_w = min_max.min_content + h_extra;
700            let mut max_w = min_max.max_content + h_extra;
701
702            if let Some(explicit_w) = resolve_dimension(cell.style.width, available_width) {
703                min_w = min_w.max(explicit_w);
704                max_w = max_w.max(explicit_w);
705            }
706
707            pc.min_w = min_w;
708            pc.max_w = max_w;
709        }
710
711        // Step 3a: Non-spanning cells (colspan == 1)
712        for pc in &placed_cells {
713            if pc.col_span == 1 {
714                let col = pc.col_start;
715                col_min[col] = col_min[col].max(pc.min_w);
716                col_max[col] = col_max[col].max(pc.max_w);
717            }
718        }
719
720        // Step 3b: Spanning cells (colspan > 1) - distribute excess
721        for pc in &placed_cells {
722            if pc.col_span > 1 {
723                let span_cols = pc.col_start..pc.col_start + pc.col_span;
724                let current_span_min: f32 = span_cols.clone().map(|c| col_min[c]).sum();
725                if pc.min_w > current_span_min {
726                    let excess = pc.min_w - current_span_min;
727                    let per_col = excess / pc.col_span as f32;
728                    for c in span_cols.clone() {
729                        col_min[c] += per_col;
730                    }
731                }
732
733                let current_span_max: f32 = span_cols.clone().map(|c| col_max[c]).sum();
734                if pc.max_w > current_span_max {
735                    let excess = pc.max_w - current_span_max;
736                    let per_col = excess / pc.col_span as f32;
737                    for c in span_cols {
738                        col_max[c] += per_col;
739                    }
740                }
741            }
742        }
743
744        for c in 0..num_cols {
745            col_max[c] = col_max[c].max(col_min[c]);
746        }
747
748        let target_inner_w = match resolve_dimension(container.style.width, available_width) {
749            Some(w) => {
750                let clamped = clamp_dimension(
751                    w,
752                    container.style.min_width,
753                    container.style.max_width,
754                    available_width,
755                );
756                (clamped - table_h_extras).max(0.0)
757            }
758            None => {
759                let avail_inner =
760                    (available_width - margin.left - margin.right - table_h_extras).max(0.0);
761                let sum_max: f32 = col_max.iter().sum();
762                if sum_max <= avail_inner {
763                    sum_max
764                } else {
765                    avail_inner
766                }
767            }
768        };
769
770        let sum_col_min: f32 = col_min.iter().sum();
771        let sum_col_max: f32 = col_max.iter().sum();
772        let mut auto_col_w = vec![0.0f32; num_cols];
773
774        if target_inner_w <= sum_col_min || sum_col_min == 0.0 {
775            if sum_col_min > 0.0 {
776                for c in 0..num_cols {
777                    auto_col_w[c] = col_min[c] * (target_inner_w / sum_col_min);
778                }
779            } else {
780                let equal_w = target_inner_w / num_cols as f32;
781                for c in 0..num_cols {
782                    auto_col_w[c] = equal_w;
783                }
784            }
785        } else if target_inner_w >= sum_col_max {
786            let extra = target_inner_w - sum_col_max;
787            if sum_col_max > 0.0 {
788                for c in 0..num_cols {
789                    auto_col_w[c] = col_max[c] + extra * (col_max[c] / sum_col_max);
790                }
791            } else {
792                let equal_w = target_inner_w / num_cols as f32;
793                for c in 0..num_cols {
794                    auto_col_w[c] = equal_w;
795                }
796            }
797        } else {
798            let factor = (target_inner_w - sum_col_min) / (sum_col_max - sum_col_min);
799            for c in 0..num_cols {
800                auto_col_w[c] = col_min[c] + factor * (col_max[c] - col_min[c]);
801            }
802        }
803
804        auto_col_w
805    };
806
807    // 4. Measure Row Heights with Computed Column Widths
808    let mut col_x = vec![0.0f32; num_cols];
809    let mut current_col_x = border.left + padding.left;
810    for c in 0..num_cols {
811        col_x[c] = current_col_x;
812        current_col_x += col_w[c] + h_spacing;
813    }
814
815    let mut row_h = vec![0.0f32; num_rows];
816    let mut row_content_h = vec![0.0f32; num_rows];
817
818    // Measure unspanned cells first
819    for pc in &mut placed_cells {
820        if pc.row_span == 1 {
821            let span_cols = pc.col_start..pc.col_start + pc.col_span;
822            let cell_width: f32 =
823                span_cols.map(|c| col_w[c]).sum::<f32>() + (pc.col_span - 1) as f32 * h_spacing;
824
825            let cell = get_cell_mut(container, pc.loc);
826            let cg = child_guard.unwrap_or(guard);
827            cell.compute_layout_guarded(cell_width, available_height, None, 0.0, cg);
828            let measured_h = cell.geometry.border_box.height;
829            if collapsed {
830                let border = cell.style.border_width;
831                let content_h = (measured_h - border.top - border.bottom).max(0.0);
832                row_content_h[pc.row_start] = row_content_h[pc.row_start].max(content_h);
833            } else {
834                row_h[pc.row_start] = row_h[pc.row_start].max(measured_h);
835            }
836
837            // Compute baseline per W3C CSS 2.1 §17.5.3
838            pc.baseline = if !cell.line_boxes.is_empty() {
839                (cell.line_boxes[0].bounds.y - cell.geometry.border_box.y)
840                    + cell.line_boxes[0].baseline
841            } else {
842                measured_h - cell.style.padding.bottom - cell.style.border_width.bottom
843            };
844        }
845    }
846
847    if collapsed {
848        // Split each resolved boundary evenly between the two rows it joins, so
849        // the shared border contributes its width once to the row pitch.
850        for r in 0..num_rows {
851            row_h[r] = row_content_h[r] + 0.5 * (row_boundary[r] + row_boundary[r + 1]);
852        }
853    }
854
855    // Measure spanned cells and distribute excess height
856    for pc in &mut placed_cells {
857        if pc.row_span > 1 {
858            let span_cols = pc.col_start..pc.col_start + pc.col_span;
859            let cell_width: f32 =
860                span_cols.map(|c| col_w[c]).sum::<f32>() + (pc.col_span - 1) as f32 * h_spacing;
861
862            let cell = get_cell_mut(container, pc.loc);
863            let cg = child_guard.unwrap_or(guard);
864            cell.compute_layout_guarded(cell_width, available_height, None, 0.0, cg);
865            let measured_h = cell.geometry.border_box.height;
866
867            pc.baseline = if !cell.line_boxes.is_empty() {
868                (cell.line_boxes[0].bounds.y - cell.geometry.border_box.y)
869                    + cell.line_boxes[0].baseline
870            } else {
871                measured_h - cell.style.padding.bottom - cell.style.border_width.bottom
872            };
873
874            let required_h = if collapsed {
875                let border = cell.style.border_width;
876                let end_row = pc.row_start + pc.row_span;
877                (measured_h - border.top - border.bottom).max(0.0)
878                    + 0.5 * (row_boundary[pc.row_start] + row_boundary[end_row])
879            } else {
880                measured_h
881            };
882
883            let span_rows = pc.row_start..pc.row_start + pc.row_span;
884            let current_span_h: f32 = span_rows.clone().map(|r| row_h[r]).sum::<f32>()
885                + (pc.row_span - 1) as f32 * v_spacing;
886            if required_h > current_span_h {
887                let excess = required_h - current_span_h;
888                let per_row = excess / pc.row_span as f32;
889                for r in span_rows {
890                    row_h[r] += per_row;
891                }
892            }
893        }
894    }
895
896    // Baseline alignment pass (§17.5.3): calculate row maximum baseline distance
897    let mut row_max_baseline = vec![0.0f32; num_rows];
898    for pc in &placed_cells {
899        let cell = get_cell(container, pc.loc);
900        if matches!(cell.style.vertical_align, VerticalAlign::Baseline) {
901            row_max_baseline[pc.row_start] = row_max_baseline[pc.row_start].max(pc.baseline);
902        }
903    }
904
905    // Expand row heights if baseline shifting increases the required height
906    for pc in &placed_cells {
907        let cell = get_cell(container, pc.loc);
908        if matches!(cell.style.vertical_align, VerticalAlign::Baseline) && pc.row_span == 1 {
909            let shift = row_max_baseline[pc.row_start] - pc.baseline;
910            let required_h = if collapsed {
911                let border = cell.style.border_width;
912                (cell.geometry.border_box.height - border.top - border.bottom).max(0.0)
913                    + 0.5 * (row_boundary[pc.row_start] + row_boundary[pc.row_start + 1])
914            } else {
915                cell.geometry.border_box.height
916            };
917            row_h[pc.row_start] = row_h[pc.row_start].max(shift + required_h);
918        }
919    }
920
921    // 5. Position Rows, Captions, and Cells
922    let mut row_y = vec![0.0f32; num_rows];
923    let mut current_rel_y = 0.0f32;
924    for r in 0..num_rows {
925        row_y[r] = current_rel_y;
926        current_rel_y += row_h[r] + v_spacing;
927    }
928
929    let table_origin_x = container.geometry.border_box.x;
930    let table_origin_y = container.geometry.border_box.y;
931    let table_inner_w = col_w.iter().sum::<f32>() + total_h_spacing;
932    let final_table_w = table_inner_w + padding.left + padding.right + border.left + border.right;
933
934    let mut current_offset_y = border.top + padding.top;
935
936    // Layout top captions (§17.4)
937    for &cap_idx in &top_captions {
938        let cap = &mut container.children[cap_idx];
939        let cg = child_guard.unwrap_or(guard);
940        cap.compute_layout_guarded(final_table_w, available_height, None, 0.0, cg);
941        let cap_h = cap.geometry.border_box.height;
942        let cap_m = cap.style.margin;
943        let cap_x = table_origin_x + border.left + padding.left + cap_m.left;
944        let cap_y = table_origin_y + current_offset_y + cap_m.top;
945        let dx = cap_x - cap.geometry.border_box.x;
946        let dy = cap_y - cap.geometry.border_box.y;
947        cap.translate(dx, dy);
948        cap.geometry.border_box.x = cap_x;
949        cap.geometry.border_box.y = cap_y;
950        current_offset_y += cap_m.top + cap_h + cap_m.bottom;
951    }
952
953    let grid_origin_y = current_offset_y;
954
955    // Position each cell
956    for pc in &placed_cells {
957        let span_cols = pc.col_start..pc.col_start + pc.col_span;
958        let cell_w: f32 =
959            span_cols.map(|c| col_w[c]).sum::<f32>() + (pc.col_span - 1) as f32 * h_spacing;
960
961        let span_rows = pc.row_start..pc.row_start + pc.row_span;
962        let cell_h: f32 =
963            span_rows.map(|r| row_h[r]).sum::<f32>() + (pc.row_span - 1) as f32 * v_spacing;
964
965        let target_x = table_origin_x + col_x[pc.col_start];
966        let target_y = table_origin_y + grid_origin_y + row_y[pc.row_start];
967
968        let cell = get_cell_mut(container, pc.loc);
969        let old_x = cell.geometry.border_box.x;
970        let old_y = cell.geometry.border_box.y;
971        let dx = target_x - old_x;
972        let dy = target_y - old_y;
973        cell.translate(dx, dy);
974
975        let cell_padding = cell.style.padding;
976        let cell_border = cell.style.border_width;
977        let cell_margin = cell.style.margin;
978
979        let measured_content_h = cell.geometry.content_box.height;
980        cell.geometry = LayoutGeometry::from_border_box(
981            Rect::new(target_x, target_y, cell_w, cell_h),
982            cell_padding,
983            cell_border,
984            cell_margin,
985        );
986
987        // Apply cell vertical alignment (§17.5.3)
988        let inner_avail_h = cell.geometry.content_box.height;
989        let shift_y = match cell.style.vertical_align {
990            VerticalAlign::Baseline => (row_max_baseline[pc.row_start] - pc.baseline).max(0.0),
991            VerticalAlign::Middle => ((inner_avail_h - measured_content_h) / 2.0).max(0.0),
992            VerticalAlign::Bottom => (inner_avail_h - measured_content_h).max(0.0),
993            _ => 0.0,
994        };
995
996        if shift_y > 0.0 {
997            for line in &mut cell.line_boxes {
998                line.bounds.y += shift_y;
999                for frag in &mut line.text_fragments {
1000                    frag.bounds.y += shift_y;
1001                    frag.baseline_y += shift_y;
1002                }
1003                for atomic in &mut line.atomic_fragments {
1004                    atomic.bounds.y += shift_y;
1005                }
1006            }
1007            for child in &mut cell.children {
1008                child.translate(0.0, shift_y);
1009            }
1010        }
1011    }
1012
1013    // Set row container geometries
1014    for (r_idx, row_loc) in rows.iter().enumerate() {
1015        let r_y = table_origin_y + grid_origin_y + row_y[r_idx];
1016        let r_h = row_h[r_idx];
1017        let row = get_row_mut(container, *row_loc);
1018        row.geometry = LayoutGeometry::from_border_box(
1019            Rect::new(
1020                table_origin_x + border.left + padding.left,
1021                r_y,
1022                table_inner_w,
1023                r_h,
1024            ),
1025            row.style.padding,
1026            row.style.border_width,
1027            row.style.margin,
1028        );
1029    }
1030
1031    // Set row group geometries
1032    for child in &mut container.children {
1033        if matches!(
1034            child.style.display,
1035            Display::TableRowGroup | Display::TableHeaderGroup | Display::TableFooterGroup
1036        ) {
1037            let mut min_y = f32::MAX;
1038            let mut max_y = f32::MIN;
1039            for row in &child.children {
1040                if row.geometry.border_box.height > 0.0 {
1041                    min_y = min_y.min(row.geometry.border_box.y);
1042                    max_y = max_y.max(row.geometry.border_box.y + row.geometry.border_box.height);
1043                }
1044            }
1045            let group_y = if min_y < f32::MAX {
1046                min_y
1047            } else {
1048                table_origin_y + grid_origin_y
1049            };
1050            let group_h = if max_y > f32::MIN {
1051                (max_y - min_y).max(0.0)
1052            } else {
1053                0.0
1054            };
1055            child.geometry = LayoutGeometry::from_border_box(
1056                Rect::new(
1057                    table_origin_x + border.left + padding.left,
1058                    group_y,
1059                    table_inner_w,
1060                    group_h,
1061                ),
1062                child.style.padding,
1063                child.style.border_width,
1064                child.style.margin,
1065            );
1066        }
1067    }
1068
1069    let total_v_spacing = (num_rows.saturating_sub(1)) as f32 * v_spacing;
1070    let grid_h = row_h.iter().sum::<f32>() + total_v_spacing;
1071    current_offset_y = grid_origin_y + grid_h;
1072
1073    // Layout bottom captions (§17.4)
1074    for &cap_idx in &bottom_captions {
1075        let cap = &mut container.children[cap_idx];
1076        let cg = child_guard.unwrap_or(guard);
1077        cap.compute_layout_guarded(final_table_w, available_height, None, 0.0, cg);
1078        let cap_h = cap.geometry.border_box.height;
1079        let cap_m = cap.style.margin;
1080        let cap_x = table_origin_x + border.left + padding.left + cap_m.left;
1081        let cap_y = table_origin_y + current_offset_y + cap_m.top;
1082        let dx = cap_x - cap.geometry.border_box.x;
1083        let dy = cap_y - cap.geometry.border_box.y;
1084        cap.translate(dx, dy);
1085        cap.geometry.border_box.x = cap_x;
1086        cap.geometry.border_box.y = cap_y;
1087        current_offset_y += cap_m.top + cap_h + cap_m.bottom;
1088    }
1089
1090    let final_table_h = current_offset_y + padding.bottom + border.bottom;
1091
1092    if collapsed {
1093        if let Some(mut grid) = table_grid {
1094            grid.row_positions = vec![0.0f32; num_rows + 1];
1095            for r in 0..num_rows {
1096                grid.row_positions[r] = table_origin_y + grid_origin_y + row_y[r];
1097            }
1098            grid.row_positions[num_rows] =
1099                table_origin_y + grid_origin_y + row_y[num_rows - 1] + row_h[num_rows - 1];
1100
1101            grid.col_positions = vec![0.0f32; num_cols + 1];
1102            for c in 0..num_cols {
1103                grid.col_positions[c] = table_origin_x + col_x[c];
1104            }
1105            grid.col_positions[num_cols] =
1106                table_origin_x + col_x[num_cols - 1] + col_w[num_cols - 1];
1107
1108            container.table_grid = Some(grid);
1109        }
1110    } else {
1111        container.table_grid = None;
1112    }
1113
1114    container.geometry = LayoutGeometry::from_border_box(
1115        Rect::new(table_origin_x, table_origin_y, final_table_w, final_table_h),
1116        padding,
1117        border,
1118        margin,
1119    );
1120}
1121
1122#[inline(always)]
1123fn get_row(container: &LayoutNode, loc: RowLocation) -> &LayoutNode {
1124    match loc.group_idx {
1125        Some(g) => &container.children[g].children[loc.row_idx],
1126        None => &container.children[loc.row_idx],
1127    }
1128}
1129
1130#[inline(always)]
1131fn get_row_mut(container: &mut LayoutNode, loc: RowLocation) -> &mut LayoutNode {
1132    match loc.group_idx {
1133        Some(g) => &mut container.children[g].children[loc.row_idx],
1134        None => &mut container.children[loc.row_idx],
1135    }
1136}
1137
1138#[inline(always)]
1139fn get_cell(container: &LayoutNode, loc: CellLocation) -> &LayoutNode {
1140    match loc.group_idx {
1141        Some(g) => &container.children[g].children[loc.row_idx].children[loc.cell_idx],
1142        None => &container.children[loc.row_idx].children[loc.cell_idx],
1143    }
1144}
1145
1146#[inline(always)]
1147fn get_cell_mut(container: &mut LayoutNode, loc: CellLocation) -> &mut LayoutNode {
1148    match loc.group_idx {
1149        Some(g) => &mut container.children[g].children[loc.row_idx].children[loc.cell_idx],
1150        None => &mut container.children[loc.row_idx].children[loc.cell_idx],
1151    }
1152}