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    if guard.is_exhausted() {
220        crate::tree::record_layout_overflow(guard.current_depth(), guard.max_depth());
221        return;
222    }
223    let padding = container.style.padding;
224    let border = container.style.border_width;
225    let margin = container.style.margin;
226
227    let (h_spacing, v_spacing) = match container.style.border_collapse {
228        BorderCollapse::Collapse => (0.0, 0.0),
229        BorderCollapse::Separate => container.style.border_spacing,
230    };
231
232    // 1. Discover Table Captions and Rows
233    let mut top_captions: Vec<usize> = Vec::new();
234    let mut bottom_captions: Vec<usize> = Vec::new();
235    let mut rows: Vec<RowLocation> = Vec::new();
236
237    for (i, child) in container.children.iter().enumerate() {
238        match child.style.display {
239            Display::TableCaption => {
240                if child.style.caption_side == CaptionSide::Bottom {
241                    bottom_captions.push(i);
242                } else {
243                    top_captions.push(i);
244                }
245            }
246            Display::TableRowGroup | Display::TableHeaderGroup | Display::TableFooterGroup => {
247                for (r, row) in child.children.iter().enumerate() {
248                    if row.style.display == Display::TableRow {
249                        rows.push(RowLocation {
250                            group_idx: Some(i),
251                            row_idx: r,
252                        });
253                    }
254                }
255            }
256            Display::TableRow => {
257                rows.push(RowLocation {
258                    group_idx: None,
259                    row_idx: i,
260                });
261            }
262            _ => {}
263        }
264    }
265
266    let child_guard = guard.enter();
267
268    if rows.is_empty() {
269        let mut total_h = padding.top + padding.bottom + border.top + border.bottom;
270        let w = resolve_dimension(container.style.width, available_width).unwrap_or(0.0);
271        let table_origin_x = container.geometry.border_box.x;
272        let table_origin_y = container.geometry.border_box.y;
273
274        let cg = child_guard.unwrap_or(guard);
275        for &cap_idx in top_captions.iter().chain(bottom_captions.iter()) {
276            let cap = &mut container.children[cap_idx];
277            cap.compute_layout_guarded(w, available_height, None, 0.0, cg);
278            let cap_h = cap.geometry.border_box.height;
279            let cap_m = cap.style.margin;
280            cap.geometry = LayoutGeometry::from_border_box(
281                Rect::new(
282                    table_origin_x + border.left + padding.left + cap_m.left,
283                    table_origin_y + total_h + cap_m.top,
284                    w,
285                    cap_h,
286                ),
287                cap.style.padding,
288                cap.style.border_width,
289                cap_m,
290            );
291            total_h += cap_m.top + cap_h + cap_m.bottom;
292        }
293
294        container.geometry = LayoutGeometry::from_border_box(
295            Rect::new(table_origin_x, table_origin_y, w, total_h),
296            padding,
297            border,
298            margin,
299        );
300        return;
301    }
302
303    // 2. Build 2D Grid Matrix and place cells considering colspans and rowspans
304    let mut occupied: Vec<Vec<bool>> = Vec::new();
305    let mut placed_cells: Vec<PlacedCell> = Vec::new();
306
307    for (r_idx, row_loc) in rows.iter().enumerate() {
308        if occupied.len() <= r_idx {
309            occupied.resize(r_idx + 1, Vec::new());
310        }
311
312        let cell_count = get_row(container, *row_loc).children.len();
313        let mut col_cursor = 0;
314
315        for c_idx in 0..cell_count {
316            let (col_span, row_span) = {
317                let cell = get_cell(
318                    container,
319                    CellLocation {
320                        group_idx: row_loc.group_idx,
321                        row_idx: row_loc.row_idx,
322                        cell_idx: c_idx,
323                    },
324                );
325                if cell.style.display == Display::None
326                    || cell.style.position == Position::Absolute
327                    || cell.style.position == Position::Fixed
328                {
329                    continue;
330                }
331                (
332                    cell.style.colspan.max(1) as usize,
333                    cell.style.rowspan.max(1) as usize,
334                )
335            };
336
337            // Advance cursor past occupied cells
338            while col_cursor < occupied[r_idx].len() && occupied[r_idx][col_cursor] {
339                col_cursor += 1;
340            }
341
342            let start_col = col_cursor;
343            let end_col = start_col + col_span;
344            let end_row = r_idx + row_span;
345
346            // Expand occupancy matrix
347            if occupied.len() < end_row {
348                occupied.resize(end_row, Vec::new());
349            }
350            for r in r_idx..end_row {
351                if occupied[r].len() < end_col {
352                    occupied[r].resize(end_col, false);
353                }
354                for c in start_col..end_col {
355                    occupied[r][c] = true;
356                }
357            }
358
359            placed_cells.push(PlacedCell {
360                loc: CellLocation {
361                    group_idx: row_loc.group_idx,
362                    row_idx: row_loc.row_idx,
363                    cell_idx: c_idx,
364                },
365                row_start: r_idx,
366                col_start: start_col,
367                col_span,
368                row_span,
369                min_w: 0.0,
370                max_w: 0.0,
371                baseline: 0.0,
372            });
373
374            col_cursor = end_col;
375        }
376    }
377
378    let num_cols = occupied.iter().map(|r| r.len()).max().unwrap_or(0);
379    let num_rows = occupied.len();
380
381    if num_cols == 0 || num_rows == 0 {
382        return;
383    }
384
385    // Resolve shared horizontal and vertical borders (CSS 2.1 §17.6.2).
386    let collapsed = container.style.border_collapse == BorderCollapse::Collapse;
387    let mut table_grid = if collapsed {
388        Some(TableBorderGrid::new(num_rows, num_cols))
389    } else {
390        None
391    };
392
393    if collapsed {
394        // Propagate border_collapse = Collapse to cells and rows
395        for row_loc in &rows {
396            let row = get_row_mut(container, *row_loc);
397            row.style.border_collapse = BorderCollapse::Collapse;
398            for cell in &mut row.children {
399                if cell.style.display == Display::TableCell {
400                    cell.style.border_collapse = BorderCollapse::Collapse;
401                }
402            }
403        }
404
405        // Build 2D occupancy mapping for O(1) cell lookup at boundaries
406        let mut cell_at = vec![vec![None; num_cols]; num_rows];
407        for (i, pc) in placed_cells.iter().enumerate() {
408            let end_r = (pc.row_start + pc.row_span).min(num_rows);
409            let end_c = (pc.col_start + pc.col_span).min(num_cols);
410            for r in pc.row_start..end_r {
411                for c in pc.col_start..end_c {
412                    cell_at[r][c] = Some(i);
413                }
414            }
415        }
416
417        if let Some(ref mut grid) = table_grid {
418            // Resolve horizontal edges (num_rows + 1 boundaries, num_cols columns)
419            for r in 0..=num_rows {
420                for c in 0..num_cols {
421                    // 1. Top candidate (from elements above boundary r)
422                    let top_candidate = if r == 0 {
423                        // Table top border
424                        if container.style.border_width.top > 0.0
425                            || container.style.border_style == BorderStyle::Hidden
426                        {
427                            CollapsedBorderEdge {
428                                width: container.style.border_width.top,
429                                style: container.style.border_style,
430                                color: container.style.border_color,
431                                source: ElementSource::Table,
432                            }
433                        } else {
434                            CollapsedBorderEdge::default()
435                        }
436                    } else {
437                        // Check cell above: cell ending at row r
438                        let cell_edge = if let Some(cell_idx) = cell_at[r - 1][c] {
439                            let pc = &placed_cells[cell_idx];
440                            if pc.row_start + pc.row_span == r {
441                                let cell = get_cell(container, pc.loc);
442                                CollapsedBorderEdge {
443                                    width: cell.style.border_width.bottom,
444                                    style: cell.style.border_style,
445                                    color: cell.style.border_color,
446                                    source: ElementSource::Cell,
447                                }
448                            } else {
449                                CollapsedBorderEdge::default()
450                            }
451                        } else {
452                            CollapsedBorderEdge::default()
453                        };
454
455                        // Check row above: row r - 1 bottom border
456                        let row = get_row(container, rows[r - 1]);
457                        let row_edge = if row.style.border_width.bottom > 0.0
458                            || row.style.border_style == BorderStyle::Hidden
459                        {
460                            CollapsedBorderEdge {
461                                width: row.style.border_width.bottom,
462                                style: row.style.border_style,
463                                color: row.style.border_color,
464                                source: ElementSource::Row,
465                            }
466                        } else {
467                            CollapsedBorderEdge::default()
468                        };
469
470                        resolve_collapsed_border(row_edge, cell_edge)
471                    };
472
473                    // 2. Bottom candidate (from elements below boundary r)
474                    let bottom_candidate = if r == num_rows {
475                        // Table bottom border
476                        if container.style.border_width.bottom > 0.0
477                            || container.style.border_style == BorderStyle::Hidden
478                        {
479                            CollapsedBorderEdge {
480                                width: container.style.border_width.bottom,
481                                style: container.style.border_style,
482                                color: container.style.border_color,
483                                source: ElementSource::Table,
484                            }
485                        } else {
486                            CollapsedBorderEdge::default()
487                        }
488                    } else {
489                        // Check cell below: cell starting at row r
490                        let cell_edge = if let Some(cell_idx) = cell_at[r][c] {
491                            let pc = &placed_cells[cell_idx];
492                            if pc.row_start == r {
493                                let cell = get_cell(container, pc.loc);
494                                CollapsedBorderEdge {
495                                    width: cell.style.border_width.top,
496                                    style: cell.style.border_style,
497                                    color: cell.style.border_color,
498                                    source: ElementSource::Cell,
499                                }
500                            } else {
501                                CollapsedBorderEdge::default()
502                            }
503                        } else {
504                            CollapsedBorderEdge::default()
505                        };
506
507                        // Check row below: row r top border
508                        let row = get_row(container, rows[r]);
509                        let row_edge = if row.style.border_width.top > 0.0
510                            || row.style.border_style == BorderStyle::Hidden
511                        {
512                            CollapsedBorderEdge {
513                                width: row.style.border_width.top,
514                                style: row.style.border_style,
515                                color: row.style.border_color,
516                                source: ElementSource::Row,
517                            }
518                        } else {
519                            CollapsedBorderEdge::default()
520                        };
521
522                        resolve_collapsed_border(row_edge, cell_edge)
523                    };
524
525                    grid.horizontal_edges[r][c] =
526                        resolve_collapsed_border(top_candidate, bottom_candidate);
527                }
528            }
529
530            // Resolve vertical edges (num_rows rows, num_cols + 1 boundaries)
531            for r in 0..num_rows {
532                for c in 0..=num_cols {
533                    // 1. Left candidate (from elements left of boundary c)
534                    let left_candidate = if c == 0 {
535                        // Table left border
536                        if container.style.border_width.left > 0.0
537                            || container.style.border_style == BorderStyle::Hidden
538                        {
539                            CollapsedBorderEdge {
540                                width: container.style.border_width.left,
541                                style: container.style.border_style,
542                                color: container.style.border_color,
543                                source: ElementSource::Table,
544                            }
545                        } else {
546                            CollapsedBorderEdge::default()
547                        }
548                    } else {
549                        // Check cell left: cell ending at column c
550                        if let Some(cell_idx) = cell_at[r][c - 1] {
551                            let pc = &placed_cells[cell_idx];
552                            if pc.col_start + pc.col_span == c {
553                                let cell = get_cell(container, pc.loc);
554                                CollapsedBorderEdge {
555                                    width: cell.style.border_width.right,
556                                    style: cell.style.border_style,
557                                    color: cell.style.border_color,
558                                    source: ElementSource::Cell,
559                                }
560                            } else {
561                                CollapsedBorderEdge::default()
562                            }
563                        } else {
564                            CollapsedBorderEdge::default()
565                        }
566                    };
567
568                    // 2. Right candidate (from elements right of boundary c)
569                    let right_candidate = if c == num_cols {
570                        // Table right border
571                        if container.style.border_width.right > 0.0
572                            || container.style.border_style == BorderStyle::Hidden
573                        {
574                            CollapsedBorderEdge {
575                                width: container.style.border_width.right,
576                                style: container.style.border_style,
577                                color: container.style.border_color,
578                                source: ElementSource::Table,
579                            }
580                        } else {
581                            CollapsedBorderEdge::default()
582                        }
583                    } else {
584                        // Check cell right: cell starting at column c
585                        if let Some(cell_idx) = cell_at[r][c] {
586                            let pc = &placed_cells[cell_idx];
587                            if pc.col_start == c {
588                                let cell = get_cell(container, pc.loc);
589                                CollapsedBorderEdge {
590                                    width: cell.style.border_width.left,
591                                    style: cell.style.border_style,
592                                    color: cell.style.border_color,
593                                    source: ElementSource::Cell,
594                                }
595                            } else {
596                                CollapsedBorderEdge::default()
597                            }
598                        } else {
599                            CollapsedBorderEdge::default()
600                        }
601                    };
602
603                    grid.vertical_edges[r][c] =
604                        resolve_collapsed_border(left_candidate, right_candidate);
605                }
606            }
607        }
608    }
609
610    let mut row_boundary = vec![0.0f32; num_rows + 1];
611    if collapsed {
612        if let Some(ref grid) = table_grid {
613            for r in 0..=num_rows {
614                let max_w = grid.horizontal_edges[r]
615                    .iter()
616                    .map(|edge| edge.width)
617                    .fold(0.0f32, f32::max);
618                row_boundary[r] = max_w;
619            }
620        }
621    }
622
623    // 3. Resolve Target Inner Width
624    let total_h_spacing = (num_cols.saturating_sub(1)) as f32 * h_spacing;
625    let table_h_extras =
626        padding.left + padding.right + border.left + border.right + total_h_spacing;
627
628    let is_fixed = container.style.table_layout == TableLayout::Fixed;
629
630    let col_w = if is_fixed {
631        // W3C CSS 2.1 §17.5.1 Fixed Table Layout
632        let target_inner_w = match resolve_dimension(container.style.width, available_width) {
633            Some(w) => {
634                let clamped = clamp_dimension(
635                    w,
636                    container.style.min_width,
637                    container.style.max_width,
638                    available_width,
639                );
640                (clamped - table_h_extras).max(0.0)
641            }
642            None => (available_width - margin.left - margin.right - table_h_extras).max(0.0),
643        };
644
645        let mut fixed_col_w = vec![0.0f32; num_cols];
646        let mut assigned = vec![false; num_cols];
647        let mut assigned_sum = 0.0f32;
648        let mut unassigned_count = 0;
649
650        // Inspect cells in row 0 for explicit column widths
651        for pc in &placed_cells {
652            if pc.row_start == 0 && pc.col_span == 1 {
653                let cell = get_cell(container, pc.loc);
654                let col = pc.col_start;
655                if let Some(explicit_w) = resolve_dimension(cell.style.width, target_inner_w) {
656                    fixed_col_w[col] = explicit_w;
657                    assigned[col] = true;
658                    assigned_sum += explicit_w;
659                }
660            }
661        }
662
663        for c in 0..num_cols {
664            if !assigned[c] {
665                unassigned_count += 1;
666            }
667        }
668
669        if unassigned_count > 0 {
670            let remaining_w = (target_inner_w - assigned_sum).max(0.0);
671            let per_col = remaining_w / unassigned_count as f32;
672            for c in 0..num_cols {
673                if !assigned[c] {
674                    fixed_col_w[c] = per_col;
675                }
676            }
677        } else if assigned_sum > 0.0 && assigned_sum < target_inner_w {
678            let extra = target_inner_w - assigned_sum;
679            for c in 0..num_cols {
680                fixed_col_w[c] += extra * (fixed_col_w[c] / assigned_sum);
681            }
682        } else if target_inner_w > 0.0 && assigned_sum == 0.0 {
683            let equal_w = target_inner_w / num_cols as f32;
684            for c in 0..num_cols {
685                fixed_col_w[c] = equal_w;
686            }
687        }
688
689        fixed_col_w
690    } else {
691        // W3C CSS 2.1 §17.5.2 Auto Table Layout Pass
692        let mut col_min = vec![0.0f32; num_cols];
693        let mut col_max = vec![0.0f32; num_cols];
694
695        for pc in &mut placed_cells {
696            let cell = get_cell_mut(container, pc.loc);
697            let min_max = compute_min_max_sizes(cell, None);
698            let cell_padding = cell.style.padding;
699            let cell_border = cell.style.border_width;
700            let h_extra =
701                cell_padding.left + cell_padding.right + cell_border.left + cell_border.right;
702
703            let mut min_w = min_max.min_content + h_extra;
704            let mut max_w = min_max.max_content + h_extra;
705
706            if let Some(explicit_w) = resolve_dimension(cell.style.width, available_width) {
707                min_w = min_w.max(explicit_w);
708                max_w = max_w.max(explicit_w);
709            }
710
711            pc.min_w = min_w;
712            pc.max_w = max_w;
713        }
714
715        // Step 3a: Non-spanning cells (colspan == 1)
716        for pc in &placed_cells {
717            if pc.col_span == 1 {
718                let col = pc.col_start;
719                col_min[col] = col_min[col].max(pc.min_w);
720                col_max[col] = col_max[col].max(pc.max_w);
721            }
722        }
723
724        // Step 3b: Spanning cells (colspan > 1) - distribute excess
725        for pc in &placed_cells {
726            if pc.col_span > 1 {
727                let span_cols = pc.col_start..pc.col_start + pc.col_span;
728                let current_span_min: f32 = span_cols.clone().map(|c| col_min[c]).sum();
729                if pc.min_w > current_span_min {
730                    let excess = pc.min_w - current_span_min;
731                    let per_col = excess / pc.col_span as f32;
732                    for c in span_cols.clone() {
733                        col_min[c] += per_col;
734                    }
735                }
736
737                let current_span_max: f32 = span_cols.clone().map(|c| col_max[c]).sum();
738                if pc.max_w > current_span_max {
739                    let excess = pc.max_w - current_span_max;
740                    let per_col = excess / pc.col_span as f32;
741                    for c in span_cols {
742                        col_max[c] += per_col;
743                    }
744                }
745            }
746        }
747
748        for c in 0..num_cols {
749            col_max[c] = col_max[c].max(col_min[c]);
750        }
751
752        let target_inner_w = match resolve_dimension(container.style.width, available_width) {
753            Some(w) => {
754                let clamped = clamp_dimension(
755                    w,
756                    container.style.min_width,
757                    container.style.max_width,
758                    available_width,
759                );
760                (clamped - table_h_extras).max(0.0)
761            }
762            None => {
763                let avail_inner =
764                    (available_width - margin.left - margin.right - table_h_extras).max(0.0);
765                let sum_max: f32 = col_max.iter().sum();
766                if sum_max <= avail_inner {
767                    sum_max
768                } else {
769                    avail_inner
770                }
771            }
772        };
773
774        let sum_col_min: f32 = col_min.iter().sum();
775        let sum_col_max: f32 = col_max.iter().sum();
776        let mut auto_col_w = vec![0.0f32; num_cols];
777
778        if target_inner_w <= sum_col_min || sum_col_min == 0.0 {
779            if sum_col_min > 0.0 {
780                for c in 0..num_cols {
781                    auto_col_w[c] = col_min[c] * (target_inner_w / sum_col_min);
782                }
783            } else {
784                let equal_w = target_inner_w / num_cols as f32;
785                for c in 0..num_cols {
786                    auto_col_w[c] = equal_w;
787                }
788            }
789        } else if target_inner_w >= sum_col_max {
790            let extra = target_inner_w - sum_col_max;
791            if sum_col_max > 0.0 {
792                for c in 0..num_cols {
793                    auto_col_w[c] = col_max[c] + extra * (col_max[c] / sum_col_max);
794                }
795            } else {
796                let equal_w = target_inner_w / num_cols as f32;
797                for c in 0..num_cols {
798                    auto_col_w[c] = equal_w;
799                }
800            }
801        } else {
802            let factor = (target_inner_w - sum_col_min) / (sum_col_max - sum_col_min);
803            for c in 0..num_cols {
804                auto_col_w[c] = col_min[c] + factor * (col_max[c] - col_min[c]);
805            }
806        }
807
808        auto_col_w
809    };
810
811    // 4. Measure Row Heights with Computed Column Widths
812    let mut col_x = vec![0.0f32; num_cols];
813    let mut current_col_x = border.left + padding.left;
814    for c in 0..num_cols {
815        col_x[c] = current_col_x;
816        current_col_x += col_w[c] + h_spacing;
817    }
818
819    let mut row_h = vec![0.0f32; num_rows];
820    let mut row_content_h = vec![0.0f32; num_rows];
821
822    // Measure unspanned cells first
823    for pc in &mut placed_cells {
824        if pc.row_span == 1 {
825            let span_cols = pc.col_start..pc.col_start + pc.col_span;
826            let cell_width: f32 =
827                span_cols.map(|c| col_w[c]).sum::<f32>() + (pc.col_span - 1) as f32 * h_spacing;
828
829            let cell = get_cell_mut(container, pc.loc);
830            let cg = child_guard.unwrap_or(guard);
831            cell.compute_layout_guarded(cell_width, available_height, None, 0.0, cg);
832            let measured_h = cell.geometry.border_box.height;
833            if collapsed {
834                let border = cell.style.border_width;
835                let content_h = (measured_h - border.top - border.bottom).max(0.0);
836                row_content_h[pc.row_start] = row_content_h[pc.row_start].max(content_h);
837            } else {
838                row_h[pc.row_start] = row_h[pc.row_start].max(measured_h);
839            }
840
841            // Compute baseline per W3C CSS 2.1 §17.5.3
842            pc.baseline = if !cell.line_boxes.is_empty() {
843                (cell.line_boxes[0].bounds.y - cell.geometry.border_box.y)
844                    + cell.line_boxes[0].baseline
845            } else {
846                measured_h - cell.style.padding.bottom - cell.style.border_width.bottom
847            };
848        }
849    }
850
851    if collapsed {
852        // Split each resolved boundary evenly between the two rows it joins, so
853        // the shared border contributes its width once to the row pitch.
854        for r in 0..num_rows {
855            row_h[r] = row_content_h[r] + 0.5 * (row_boundary[r] + row_boundary[r + 1]);
856        }
857    }
858
859    // Measure spanned cells and distribute excess height
860    for pc in &mut placed_cells {
861        if pc.row_span > 1 {
862            let span_cols = pc.col_start..pc.col_start + pc.col_span;
863            let cell_width: f32 =
864                span_cols.map(|c| col_w[c]).sum::<f32>() + (pc.col_span - 1) as f32 * h_spacing;
865
866            let cell = get_cell_mut(container, pc.loc);
867            let cg = child_guard.unwrap_or(guard);
868            cell.compute_layout_guarded(cell_width, available_height, None, 0.0, cg);
869            let measured_h = cell.geometry.border_box.height;
870
871            pc.baseline = if !cell.line_boxes.is_empty() {
872                (cell.line_boxes[0].bounds.y - cell.geometry.border_box.y)
873                    + cell.line_boxes[0].baseline
874            } else {
875                measured_h - cell.style.padding.bottom - cell.style.border_width.bottom
876            };
877
878            let required_h = if collapsed {
879                let border = cell.style.border_width;
880                let end_row = pc.row_start + pc.row_span;
881                (measured_h - border.top - border.bottom).max(0.0)
882                    + 0.5 * (row_boundary[pc.row_start] + row_boundary[end_row])
883            } else {
884                measured_h
885            };
886
887            let span_rows = pc.row_start..pc.row_start + pc.row_span;
888            let current_span_h: f32 = span_rows.clone().map(|r| row_h[r]).sum::<f32>()
889                + (pc.row_span - 1) as f32 * v_spacing;
890            if required_h > current_span_h {
891                let excess = required_h - current_span_h;
892                let per_row = excess / pc.row_span as f32;
893                for r in span_rows {
894                    row_h[r] += per_row;
895                }
896            }
897        }
898    }
899
900    // Baseline alignment pass (§17.5.3): calculate row maximum baseline distance
901    let mut row_max_baseline = vec![0.0f32; num_rows];
902    for pc in &placed_cells {
903        let cell = get_cell(container, pc.loc);
904        if matches!(cell.style.vertical_align, VerticalAlign::Baseline) {
905            row_max_baseline[pc.row_start] = row_max_baseline[pc.row_start].max(pc.baseline);
906        }
907    }
908
909    // Expand row heights if baseline shifting increases the required height
910    for pc in &placed_cells {
911        let cell = get_cell(container, pc.loc);
912        if matches!(cell.style.vertical_align, VerticalAlign::Baseline) && pc.row_span == 1 {
913            let shift = row_max_baseline[pc.row_start] - pc.baseline;
914            let required_h = if collapsed {
915                let border = cell.style.border_width;
916                (cell.geometry.border_box.height - border.top - border.bottom).max(0.0)
917                    + 0.5 * (row_boundary[pc.row_start] + row_boundary[pc.row_start + 1])
918            } else {
919                cell.geometry.border_box.height
920            };
921            row_h[pc.row_start] = row_h[pc.row_start].max(shift + required_h);
922        }
923    }
924
925    // 5. Position Rows, Captions, and Cells
926    let mut row_y = vec![0.0f32; num_rows];
927    let mut current_rel_y = 0.0f32;
928    for r in 0..num_rows {
929        row_y[r] = current_rel_y;
930        current_rel_y += row_h[r] + v_spacing;
931    }
932
933    let table_origin_x = container.geometry.border_box.x;
934    let table_origin_y = container.geometry.border_box.y;
935    let table_inner_w = col_w.iter().sum::<f32>() + total_h_spacing;
936    let final_table_w = table_inner_w + padding.left + padding.right + border.left + border.right;
937
938    let mut current_offset_y = border.top + padding.top;
939
940    // Layout top captions (§17.4)
941    for &cap_idx in &top_captions {
942        let cap = &mut container.children[cap_idx];
943        let cg = child_guard.unwrap_or(guard);
944        cap.compute_layout_guarded(final_table_w, available_height, None, 0.0, cg);
945        let cap_h = cap.geometry.border_box.height;
946        let cap_m = cap.style.margin;
947        let cap_x = table_origin_x + border.left + padding.left + cap_m.left;
948        let cap_y = table_origin_y + current_offset_y + cap_m.top;
949        let dx = cap_x - cap.geometry.border_box.x;
950        let dy = cap_y - cap.geometry.border_box.y;
951        cap.translate(dx, dy);
952        cap.geometry.border_box.x = cap_x;
953        cap.geometry.border_box.y = cap_y;
954        current_offset_y += cap_m.top + cap_h + cap_m.bottom;
955    }
956
957    let grid_origin_y = current_offset_y;
958
959    // Position each cell
960    for pc in &placed_cells {
961        let span_cols = pc.col_start..pc.col_start + pc.col_span;
962        let cell_w: f32 =
963            span_cols.map(|c| col_w[c]).sum::<f32>() + (pc.col_span - 1) as f32 * h_spacing;
964
965        let span_rows = pc.row_start..pc.row_start + pc.row_span;
966        let cell_h: f32 =
967            span_rows.map(|r| row_h[r]).sum::<f32>() + (pc.row_span - 1) as f32 * v_spacing;
968
969        let target_x = table_origin_x + col_x[pc.col_start];
970        let target_y = table_origin_y + grid_origin_y + row_y[pc.row_start];
971
972        let cell = get_cell_mut(container, pc.loc);
973        let old_x = cell.geometry.border_box.x;
974        let old_y = cell.geometry.border_box.y;
975        let dx = target_x - old_x;
976        let dy = target_y - old_y;
977        cell.translate(dx, dy);
978
979        let cell_padding = cell.style.padding;
980        let cell_border = cell.style.border_width;
981        let cell_margin = cell.style.margin;
982
983        let measured_content_h = cell.geometry.content_box.height;
984        cell.geometry = LayoutGeometry::from_border_box(
985            Rect::new(target_x, target_y, cell_w, cell_h),
986            cell_padding,
987            cell_border,
988            cell_margin,
989        );
990
991        // Apply cell vertical alignment (§17.5.3)
992        let inner_avail_h = cell.geometry.content_box.height;
993        let shift_y = match cell.style.vertical_align {
994            VerticalAlign::Baseline => (row_max_baseline[pc.row_start] - pc.baseline).max(0.0),
995            VerticalAlign::Middle => ((inner_avail_h - measured_content_h) / 2.0).max(0.0),
996            VerticalAlign::Bottom => (inner_avail_h - measured_content_h).max(0.0),
997            _ => 0.0,
998        };
999
1000        if shift_y > 0.0 {
1001            for line in &mut cell.line_boxes {
1002                line.bounds.y += shift_y;
1003                for frag in &mut line.text_fragments {
1004                    frag.bounds.y += shift_y;
1005                    frag.baseline_y += shift_y;
1006                }
1007                for atomic in &mut line.atomic_fragments {
1008                    atomic.bounds.y += shift_y;
1009                }
1010            }
1011            for child in &mut cell.children {
1012                child.translate(0.0, shift_y);
1013            }
1014        }
1015    }
1016
1017    // Set row container geometries
1018    for (r_idx, row_loc) in rows.iter().enumerate() {
1019        let r_y = table_origin_y + grid_origin_y + row_y[r_idx];
1020        let r_h = row_h[r_idx];
1021        let row = get_row_mut(container, *row_loc);
1022        row.geometry = LayoutGeometry::from_border_box(
1023            Rect::new(
1024                table_origin_x + border.left + padding.left,
1025                r_y,
1026                table_inner_w,
1027                r_h,
1028            ),
1029            row.style.padding,
1030            row.style.border_width,
1031            row.style.margin,
1032        );
1033    }
1034
1035    // Set row group geometries
1036    for child in &mut container.children {
1037        if matches!(
1038            child.style.display,
1039            Display::TableRowGroup | Display::TableHeaderGroup | Display::TableFooterGroup
1040        ) {
1041            let mut min_y = f32::MAX;
1042            let mut max_y = f32::MIN;
1043            for row in &child.children {
1044                if row.geometry.border_box.height > 0.0 {
1045                    min_y = min_y.min(row.geometry.border_box.y);
1046                    max_y = max_y.max(row.geometry.border_box.y + row.geometry.border_box.height);
1047                }
1048            }
1049            let group_y = if min_y < f32::MAX {
1050                min_y
1051            } else {
1052                table_origin_y + grid_origin_y
1053            };
1054            let group_h = if max_y > f32::MIN {
1055                (max_y - min_y).max(0.0)
1056            } else {
1057                0.0
1058            };
1059            child.geometry = LayoutGeometry::from_border_box(
1060                Rect::new(
1061                    table_origin_x + border.left + padding.left,
1062                    group_y,
1063                    table_inner_w,
1064                    group_h,
1065                ),
1066                child.style.padding,
1067                child.style.border_width,
1068                child.style.margin,
1069            );
1070        }
1071    }
1072
1073    let total_v_spacing = (num_rows.saturating_sub(1)) as f32 * v_spacing;
1074    let grid_h = row_h.iter().sum::<f32>() + total_v_spacing;
1075    current_offset_y = grid_origin_y + grid_h;
1076
1077    // Layout bottom captions (§17.4)
1078    for &cap_idx in &bottom_captions {
1079        let cap = &mut container.children[cap_idx];
1080        let cg = child_guard.unwrap_or(guard);
1081        cap.compute_layout_guarded(final_table_w, available_height, None, 0.0, cg);
1082        let cap_h = cap.geometry.border_box.height;
1083        let cap_m = cap.style.margin;
1084        let cap_x = table_origin_x + border.left + padding.left + cap_m.left;
1085        let cap_y = table_origin_y + current_offset_y + cap_m.top;
1086        let dx = cap_x - cap.geometry.border_box.x;
1087        let dy = cap_y - cap.geometry.border_box.y;
1088        cap.translate(dx, dy);
1089        cap.geometry.border_box.x = cap_x;
1090        cap.geometry.border_box.y = cap_y;
1091        current_offset_y += cap_m.top + cap_h + cap_m.bottom;
1092    }
1093
1094    let final_table_h = current_offset_y + padding.bottom + border.bottom;
1095
1096    if collapsed {
1097        if let Some(mut grid) = table_grid {
1098            grid.row_positions = vec![0.0f32; num_rows + 1];
1099            for r in 0..num_rows {
1100                grid.row_positions[r] = table_origin_y + grid_origin_y + row_y[r];
1101            }
1102            grid.row_positions[num_rows] =
1103                table_origin_y + grid_origin_y + row_y[num_rows - 1] + row_h[num_rows - 1];
1104
1105            grid.col_positions = vec![0.0f32; num_cols + 1];
1106            for c in 0..num_cols {
1107                grid.col_positions[c] = table_origin_x + col_x[c];
1108            }
1109            grid.col_positions[num_cols] =
1110                table_origin_x + col_x[num_cols - 1] + col_w[num_cols - 1];
1111
1112            container.table_grid = Some(grid);
1113        }
1114    } else {
1115        container.table_grid = None;
1116    }
1117
1118    container.geometry = LayoutGeometry::from_border_box(
1119        Rect::new(table_origin_x, table_origin_y, final_table_w, final_table_h),
1120        padding,
1121        border,
1122        margin,
1123    );
1124}
1125
1126#[inline(always)]
1127fn get_row(container: &LayoutNode, loc: RowLocation) -> &LayoutNode {
1128    match loc.group_idx {
1129        Some(g) => &container.children[g].children[loc.row_idx],
1130        None => &container.children[loc.row_idx],
1131    }
1132}
1133
1134#[inline(always)]
1135fn get_row_mut(container: &mut LayoutNode, loc: RowLocation) -> &mut LayoutNode {
1136    match loc.group_idx {
1137        Some(g) => &mut container.children[g].children[loc.row_idx],
1138        None => &mut container.children[loc.row_idx],
1139    }
1140}
1141
1142#[inline(always)]
1143fn get_cell(container: &LayoutNode, loc: CellLocation) -> &LayoutNode {
1144    match loc.group_idx {
1145        Some(g) => &container.children[g].children[loc.row_idx].children[loc.cell_idx],
1146        None => &container.children[loc.row_idx].children[loc.cell_idx],
1147    }
1148}
1149
1150#[inline(always)]
1151fn get_cell_mut(container: &mut LayoutNode, loc: CellLocation) -> &mut LayoutNode {
1152    match loc.group_idx {
1153        Some(g) => &mut container.children[g].children[loc.row_idx].children[loc.cell_idx],
1154        None => &mut container.children[loc.row_idx].children[loc.cell_idx],
1155    }
1156}