sghtmltopdf 0.6.0

HTML to PDF renderer that does not depend on Chromium, WebKit or Gecko
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
//! Layout of `display: table` elements (the content-based automatic column width algorithm).
//!
//! A simplified version of the automatic table layout in CSS2.1 section 17.5.2. Each cell's
//! "natural width" is measured (in practice, the width of its text laid out on one line with
//! no wrapping); the maximum natural width per column is taken; and the columns are scaled
//! proportionally to fit the containing width (scaling up when the containing width is
//! larger, so the table always fills it, matching the ordinary CSS behaviour of a
//! `width: auto` table filling its containing block).
//!
//! - `rowspan="0"` (HTML5's "extend to the end of the section" special value) is not supported and is treated as 1
//! - `border-collapse: collapse` only unifies how the borders are drawn; the layout
//!   calculation is identical to the separate model
//! - The natural width of a table, flex or grid nested inside a cell is approximated
//!   according to the meaning of its own axes (broken down in [`measure_natural_content_width`])
//! - Cell content that cannot provide a baseline for `vertical-align: baseline`
//!   (a nested table, a replaced element) falls back to the equivalent of `bottom`

use std::collections::HashMap;
use std::rc::Rc;

use crate::fonts::FontCollection;
use crate::html::NodeId;
use crate::style::{
    BoxSizing, CaptionSide, ComputedStyle, FlexDirection, LengthPercentage, LengthPercentageOrAuto,
    MaxSize, RepeatCount, TableLayout, TrackComponent, TrackList, VerticalAlign,
};

use super::block::resolve_lpa_or_zero;
use super::block::{
    apply_replaced_element_auto_size, box_style, clamp_used_width, layout_box,
    layout_box_with_forced_width, resolve_border, resolve_lp, resolve_padding, shift_box_y,
    shift_box_y_in_place, shift_content_vertical, LaidOutBox, LaidOutContent, LaidOutTable,
    LaidOutTableRow, PosCtx,
};
use super::box_tree::{BoxContent, ImageBoxContent, LayoutBox, TableBox, TableCell, TableRow};
use super::float_ctx::FloatContext;
use super::inline::{clear_word_width_cache, layout_inline_content, plain_text_min_content_width};

/// A width that can be treated as effectively infinite, used to disable wrapping.
const UNCONSTRAINED_WIDTH: f32 = f32::MAX / 4.0;

/// Lay the table out and return the laid-out table (caption plus rows and columns) and its
/// overall height. `table_layout` is the computed `table-layout` of the `display: table`
/// element itself (a non-inherited property, read from that element's own style by the
/// caller). `h_spacing`/`v_spacing` are the resolved `border-spacing` values (the caller
/// collapses them to 0 under `border-collapse: collapse`).
#[allow(clippy::too_many_arguments)]
pub(super) fn layout_table(
    table: &TableBox,
    styles: &HashMap<NodeId, Rc<ComputedStyle>>,
    fonts: &FontCollection,
    containing_width: f32,
    table_layout: TableLayout,
    h_spacing: f32,
    v_spacing: f32,
    x: f32,
    y: f32,
    pos: &mut PosCtx,
) -> (LaidOutTable, f32, f32) {
    // The caption is laid out independently even when there are no rows (so the empty-table-
    // plus-caption case works too, this happens before the column_count == 0 early return).
    // The caption is also taken to establish a new Block Formatting Context, keeping it
    // independent of the outer floats (the same policy as the table body's cells).
    let laid_caption = table.caption.as_deref().map(|caption| {
        let mut caption_float_ctx = FloatContext::new();
        layout_box(
            caption,
            styles,
            fonts,
            containing_width,
            &mut caption_float_ctx,
            x,
            y,
            pos,
        )
    });
    let caption_height = laid_caption
        .as_ref()
        .map(|c| c.layout.margin_box_height())
        .unwrap_or(0.0);
    let caption_is_top = table.caption_side == CaptionSide::Top;
    // With `caption-side: top`, the rows start lower by the height of the caption.
    // With `bottom`, the rows start at `y` as usual and the caption is shifted below them
    // after the rows are laid out (see below). `rows_block_start` is the start of the whole
    // row group (including the `v_spacing` before and after) and `rows_start_y` is where the first row actually goes.
    let rows_block_start = if caption_is_top {
        y + caption_height
    } else {
        y
    };
    let rows_start_y = rows_block_start + v_spacing;

    // Grid placement accounting for rowspan/colspan occupancy. Every later calculation of
    // column widths, row heights and cell placement goes through this grid. The column count
    // falls out of that placement (the maximum colspan sum per row would miss a cell placed
    // past a column filled by a rowspan).
    let (grid, column_count) = build_table_grid(&table.rows);

    if column_count == 0 {
        let (caption, total_height) = match laid_caption {
            Some(c) => (Some(Box::new(c)), caption_height),
            None => (None, 0.0),
        };
        return (
            LaidOutTable {
                caption,
                caption_side: table.caption_side,
                rows: Vec::new(),
            },
            total_height,
            containing_width,
        );
    }

    // In the separate model, `border-spacing` goes not only between columns but also between
    // the table's outer edge and the outermost columns (CSS2.1 17.6.1), so the width
    // available for the columns is reduced by `(column count + 1)` lots of `h_spacing`.
    let available_column_width =
        (containing_width - h_spacing * (column_count + 1) as f32).max(0.0);

    // Resolve the column width hints from `<colgroup>`/`<col>` into used widths (px) at this
    // point. Any beyond the column count are discarded, and any shortfall counts as unspecified.
    let column_hints: Vec<Option<f32>> = (0..column_count)
        .map(|i| {
            table
                .column_widths
                .get(i)
                .copied()
                .flatten()
                .map(|lp| resolve_lp(lp, available_column_width))
        })
        .collect();

    // `table-layout: fixed` is a fast path that looks only at `<col>` and the explicit
    // `width` settings on the first row, skipping content measurement
    // (the cell natural widths in `compute_column_widths`) entirely.
    let col_widths = if table_layout == TableLayout::Fixed {
        compute_fixed_column_widths(
            &grid,
            styles,
            &column_hints,
            column_count,
            available_column_width,
        )
    } else {
        compute_column_widths(
            &grid,
            styles,
            fonts,
            &column_hints,
            column_count,
            available_column_width,
        )
    };
    let mut col_x = vec![0.0f32; column_count + 1];
    col_x[0] = h_spacing;
    for i in 0..column_count {
        col_x[i + 1] = col_x[i] + col_widths[i] + h_spacing;
    }

    // Pass 1: lay each cell out at a provisional position of y=0 to get its "natural
    // height", before the row heights are settled (cells spanning several rows via rowspan
    // are moved to their real positions later, all together via `shift_box_y`, once every row height is known).
    let laid_grid: Vec<Vec<LaidOutBox>> = grid
        .iter()
        .map(|row_cells| {
            row_cells
                .iter()
                .map(|gc| {
                    let outer_width: f32 = if gc.col_end > gc.col_start {
                        col_x[gc.col_end] - col_x[gc.col_start] - h_spacing
                    } else {
                        0.0
                    };
                    let cell_x = x + col_x[gc.col_start];

                    let cell_style = box_style(&gc.cell.content, styles);
                    let cell_padding = resolve_padding(&cell_style, outer_width);
                    let cell_border = resolve_border(&cell_style);
                    let content_width = (outer_width
                        - cell_padding.left
                        - cell_padding.right
                        - cell_border.left
                        - cell_border.right)
                        .max(0.0);

                    // A `display: table` cell establishes a new Block Formatting Context
                    // (CSS2.1 9.4.1), so it gets an empty context independent of the outer floats.
                    //
                    // A cell is laid out at the provisional y=0 and moved down once the row
                    // height is known, but the `absolute`s collected need no moving:
                    // an absolute position is determined solely by the containing block
                    // (static position is unsupported), and where the containing block is
                    // inside the cell, page composition corrects it by the ancestor's real offset.
                    let mut cell_float_ctx = FloatContext::new();
                    layout_box_with_forced_width(
                        &gc.cell.content,
                        styles,
                        fonts,
                        outer_width,
                        content_width,
                        &mut cell_float_ctx,
                        cell_x,
                        0.0,
                        pos,
                    )
                })
                .collect()
        })
        .collect();

    let row_count = table.rows.len();
    // Pass 2: find each row's maximum natural height using only the rowspan=1 cells
    // (the same two-pass approach as colspan column widths).
    let mut row_natural = vec![0.0f32; row_count];
    for (row_cells, laid_row) in grid.iter().zip(laid_grid.iter()) {
        for (gc, laid_cell) in row_cells.iter().zip(laid_row.iter()) {
            if gc.cell.rowspan == 1 {
                row_natural[gc.row_index] =
                    row_natural[gc.row_index].max(laid_cell.layout.margin_box_height());
            }
        }
    }
    // Pass 3: for cells spanning several rows via rowspan, if the sum of the spanned rows'
    // natural heights (plus the `v_spacing` between them, the same reasoning as colspan's
    // h_spacing) falls short of the cell's own natural height, distribute the shortfall evenly over the spanned rows.
    for (row_cells, laid_row) in grid.iter().zip(laid_grid.iter()) {
        for (gc, laid_cell) in row_cells.iter().zip(laid_row.iter()) {
            if gc.cell.rowspan > 1 {
                let end = (gc.row_index + gc.cell.rowspan).min(row_count);
                if end > gc.row_index {
                    let span_count = end - gc.row_index;
                    let span_natural_sum: f32 = row_natural[gc.row_index..end].iter().sum::<f32>()
                        + v_spacing * (span_count - 1) as f32;
                    let cell_natural = laid_cell.layout.margin_box_height();
                    if cell_natural > span_natural_sum {
                        let deficit = cell_natural - span_natural_sum;
                        let share = deficit / span_count as f32;
                        for h in &mut row_natural[gc.row_index..end] {
                            *h += share;
                        }
                    }
                }
            }
        }
    }

    // Pass 4: find each row's absolute Y position (cumulative from the start of the row group, `v_spacing` before and after included).
    let mut row_y = vec![0.0f32; row_count + 1];
    row_y[0] = rows_start_y;
    for r in 0..row_count {
        row_y[r + 1] = row_y[r] + row_natural[r] + v_spacing;
    }

    // Pass 5: translate each cell from its provisional position (y=0) to its real row
    // position and stretch it to the final height settled by rowspan. How the extra space is
    // distributed is decided by the computed `vertical-align` (four cases,
    // top/middle/bottom/baseline, CSS2.1 17.5.3).
    let mut laid_rows = Vec::with_capacity(table.rows.len());
    for (row, (row_cells, laid_row)) in table.rows.iter().zip(grid.iter().zip(laid_grid)) {
        let mut laid_cells: Vec<LaidOutBox> = row_cells
            .iter()
            .zip(laid_row)
            .map(|(gc, mut laid_cell)| {
                shift_box_y_in_place(&mut laid_cell, -row_y[gc.row_index]);
                laid_cell
            })
            .collect();

        // For baseline-aligned cells, find how far the baseline of the cell's own first line
        // sits below the top of the cell, and use the largest across the row as the row's
        // baseline position to align to (only cells starting in that row count, as CSS2.1 defines).
        let row_baseline_offset = laid_cells
            .iter()
            .zip(row_cells.iter())
            .filter(|(cell, _)| cell_vertical_align(cell, styles) == VerticalAlign::Baseline)
            .filter_map(|(cell, _)| own_baseline_offset(cell, fonts))
            .fold(0.0f32, f32::max);

        for (cell, gc) in laid_cells.iter_mut().zip(row_cells.iter()) {
            let span_end = (gc.row_index + gc.cell.rowspan).min(row_count);
            let final_height = if span_end > gc.row_index {
                row_y[span_end] - row_y[gc.row_index] - v_spacing
            } else {
                0.0
            };
            let deficit = final_height - cell.layout.margin_box_height();
            if deficit <= 0.0 {
                continue;
            }
            cell.layout.content.height += deficit;

            let shift_down = match cell_vertical_align(cell, styles) {
                VerticalAlign::Top => 0.0,
                VerticalAlign::Middle => deficit / 2.0,
                VerticalAlign::Bottom => deficit,
                // `sub`/`super`/`text-top`/`text-bottom` and lengths are inline-context-only
                // values and do not apply to a table cell in CSS2.1. They are treated as
                // `baseline`.
                VerticalAlign::Baseline
                | VerticalAlign::Sub
                | VerticalAlign::Super
                | VerticalAlign::TextTop
                | VerticalAlign::TextBottom
                | VerticalAlign::LengthPercentage(_) => match own_baseline_offset(cell, fonts) {
                    Some(own_offset) => row_baseline_offset - own_offset,
                    // Cell content that cannot provide a baseline falls back to the
                    // equivalent of `bottom` (a known simplification; see the comment at the top of this file).
                    None => deficit,
                },
            };
            if shift_down > 0.0 {
                *cell = shift_content_vertical(cell, -shift_down);
            }
        }

        laid_rows.push(LaidOutTableRow {
            node: row.node,
            cells: laid_cells,
            section: row.section,
            group: row.group,
        });
    }

    let rows_height = row_y[row_count] - rows_block_start;
    let total_height = caption_height + rows_height;

    let final_caption = match (laid_caption, caption_is_top) {
        (Some(c), true) => Some(Box::new(c)),
        (Some(c), false) => {
            // The caption is already laid out at `y`, so it is shifted below the rows (down
            // by `rows_height`). `shift_box_y`'s delta subtracts, so a negative value is passed.
            Some(Box::new(shift_box_y(&c, -rows_height)))
        }
        (None, _) => None,
    };

    (
        LaidOutTable {
            caption: final_caption,
            caption_side: table.caption_side,
            rows: laid_rows,
        },
        total_height,
        // The columns can add up to more than the width offered (min-content floors), in which
        // case the table is wider than its box.
        containing_width.max(col_x[column_count]),
    )
}

/// The computed `vertical-align` of the cell (`display: table-cell`) itself.
fn cell_vertical_align(
    cell: &LaidOutBox,
    styles: &HashMap<NodeId, Rc<ComputedStyle>>,
) -> VerticalAlign {
    cell.node
        .and_then(|n| styles.get(&n))
        .map(|s| s.vertical_align)
        .unwrap_or_default()
}

/// Find how far the baseline of the first line of the cell's content sits below the top of
/// the cell itself (`cell.layout.content.y`). Content with no text (a nested table, a
/// replaced element and so on) cannot provide one, so `None` is returned (a known
/// simplification; the caller falls back to the equivalent of `bottom`).
fn own_baseline_offset(cell: &LaidOutBox, fonts: &FontCollection) -> Option<f32> {
    let absolute = first_baseline_absolute_y(cell, fonts)?;
    Some(absolute - cell.layout.content.y)
}

/// Walk `b`'s content depth-first in document order and return the absolute Y coordinate
/// (in the same coordinate space as `b`) of the first text line's baseline.
fn first_baseline_absolute_y(b: &LaidOutBox, fonts: &FontCollection) -> Option<f32> {
    match &b.content {
        LaidOutContent::Inline(lines) => lines.iter().find_map(|line| {
            let first_run = line.runs.first()?;
            let font = fonts.get(first_run.font_index)?;
            let offset = font.baseline_offset(first_run.font_size, line.rect.height);
            Some(line.rect.y + offset)
        }),
        LaidOutContent::Blocks(children) => children
            .iter()
            .find_map(|child| first_baseline_absolute_y(child, fonts)),
        // A nested table, flex, grid or replaced element provides no baseline
        // (a known simplification).
        LaidOutContent::Table(_)
        | LaidOutContent::Flex(_)
        | LaidOutContent::Grid(_)
        | LaidOutContent::Image(_) => None,
    }
}

/// A reference to one cell in the grid, carrying its row number plus its real start and end
/// (exclusive) columns. A simplified version of "table grid construction", CSS2.1 section 17.2.
struct GridCell<'a> {
    cell: &'a TableCell,
    row_index: usize,
    col_start: usize,
    col_end: usize,
}

/// From `rows`, work out the grid placement accounting for rowspan/colspan occupancy (later
/// rows skipping columns filled by a rowspan), and the resulting column count. The grid
/// returned is a list of `GridCell` per row (the outer `Vec` is the rows, the inner one the
/// cells belonging to that row). Where every rowspan is 1, it returns exactly the same result
/// as a simple walk advancing the column cursor by `col += cell.colspan`, so the existing
/// tests (which use no rowspan) stay backward-compatible.
///
/// The column count is worked out here rather than taken from the caller because a mismatch
/// between the placement that skips rowspan-filled columns and the way the count is derived
/// silently loses cells with nowhere to go ("row 1 is a single rowspan cell, row 2 fills the rest").
fn build_table_grid(rows: &[TableRow]) -> (Vec<Vec<GridCell<'_>>>, usize) {
    // occupied[col]: how many more rows a rowspan occupies that column for (0 means free).
    // It grows whenever a placement goes past the known column count, and its final length is the column count.
    let mut occupied: Vec<usize> = Vec::new();
    let mut grid = Vec::with_capacity(rows.len());

    for (row_index, row) in rows.iter().enumerate() {
        let mut row_cells = Vec::with_capacity(row.cells.len());
        let mut col = 0usize;
        for cell in &row.cells {
            while col < occupied.len() && occupied[col] > 0 {
                col += 1;
            }
            let col_start = col;
            let col_end = col_start + cell.colspan;
            if occupied.len() < col_end {
                occupied.resize(col_end, 0);
            }
            for slot in &mut occupied[col_start..col_end] {
                *slot = cell.rowspan;
            }
            row_cells.push(GridCell {
                cell,
                row_index,
                col_start,
                col_end,
            });
            col = col_end;
        }
        grid.push(row_cells);
        // This row is done, so decrement the remaining rowspan counts
        // (consuming this row; a column reaching 0 is free again from the next row).
        for slot in &mut occupied {
            *slot = slot.saturating_sub(1);
        }
    }

    let column_count = occupied.len();
    (grid, column_count)
}

/// Column width determination for `table-layout: fixed` (a simplified version of CSS2.1
/// section 17.5.2.1). The `<col>` hints (`column_hints`) win outright, then the explicit
/// `width` (px or %) on a first-row cell becomes the total width of the columns it occupies
/// (divided evenly across them when a colspan covers several), and columns with neither
/// share the remaining width evenly. Columns absent from the first row (when the first row's
/// colspan sum falls short of `column_count`) are included in that even share. No content is measured at all.
fn compute_fixed_column_widths(
    grid: &[Vec<GridCell<'_>>],
    styles: &HashMap<NodeId, Rc<ComputedStyle>>,
    column_hints: &[Option<f32>],
    column_count: usize,
    containing_width: f32,
) -> Vec<f32> {
    let mut widths: Vec<Option<f32>> = vec![None; column_count];

    if let Some(first_row) = grid.first() {
        for gc in first_row {
            if gc.col_end > gc.col_start {
                let cell_style = box_style(&gc.cell.content, styles);
                if let Some(resolved) = fixed_cell_width(&cell_style, containing_width) {
                    let share = resolved / (gc.col_end - gc.col_start) as f32;
                    for w in &mut widths[gc.col_start..gc.col_end] {
                        *w = Some(share);
                    }
                }
            }
        }
    }

    // A `<col>` setting wins over a first-row cell.
    for (i, hint) in column_hints.iter().enumerate().take(column_count) {
        if let Some(hint) = hint {
            widths[i] = Some(*hint);
        }
    }

    let specified_sum: f32 = widths.iter().filter_map(|w| *w).sum();
    let auto_count = widths.iter().filter(|w| w.is_none()).count();
    let remaining = (containing_width - specified_sum).max(0.0);
    let auto_share = if auto_count > 0 {
        remaining / auto_count as f32
    } else {
        0.0
    };

    widths.iter().map(|w| w.unwrap_or(auto_share)).collect()
}

/// Find each column's used width. The maximum per column of the "natural width" derived
/// from the cells' content is scaled proportionally to fill the containing width exactly. When
/// the table has to shrink instead, the columns give up only their slack above min-content
/// (see [`fit_columns`]).
///
/// A column with a `<col>` hint (`column_hints`) is fixed at that width, and the remaining
/// width is distributed over the unhinted columns in proportion to their natural widths.
fn compute_column_widths(
    grid: &[Vec<GridCell<'_>>],
    styles: &HashMap<NodeId, Rc<ComputedStyle>>,
    fonts: &FontCollection,
    column_hints: &[Option<f32>],
    column_count: usize,
    containing_width: f32,
) -> Vec<f32> {
    let natural = column_widths_by(grid, column_count, |cell| {
        natural_cell_width(cell, styles, fonts)
    });
    // The min-content width of each column, found the same way. A column can never be
    // narrower than its widest unbreakable run (CSS2.1 17.5.2.2), whatever the table width.
    // It costs a second inline layout per cell and only matters when the table has to
    // shrink, so it is measured on demand.
    let min_content = || {
        clear_word_width_cache();
        let min_content = column_widths_by(grid, column_count, |cell| {
            min_cell_width(cell, styles, fonts)
        });
        clear_word_width_cache();
        min_content
            .iter()
            .zip(&natural)
            .map(|(min, natural)| min.min(*natural))
            .collect::<Vec<f32>>()
    };

    let has_hint = column_hints
        .iter()
        .take(column_count)
        .any(|hint| hint.is_some());
    if has_hint {
        return distribute_with_column_hints(
            &natural,
            min_content,
            column_hints,
            column_count,
            containing_width,
        );
    }

    fit_columns(&natural, min_content, containing_width)
}

/// Per-column maximum of `cell_width` over the cells, colspan handled as for column widths
/// throughout: colspan=1 cells first, then a spanning cell's shortfall is spread evenly over
/// the columns it covers.
fn column_widths_by(
    grid: &[Vec<GridCell<'_>>],
    column_count: usize,
    cell_width: impl Fn(&TableCell) -> f32,
) -> Vec<f32> {
    let mut widths = vec![0.0f32; column_count];

    // Pass 1: find each column's maximum width using only the colspan=1 cells.
    for row_cells in grid {
        for gc in row_cells {
            if gc.col_end - gc.col_start == 1 {
                widths[gc.col_start] = widths[gc.col_start].max(cell_width(gc.cell));
            }
        }
    }

    // Pass 2: for cells spanning several columns via colspan, if the sum of the spanned
    // columns' widths falls short of the cell's own width, distribute the shortfall evenly over them.
    for row_cells in grid {
        for gc in row_cells {
            if gc.col_end - gc.col_start > 1 {
                let span_sum: f32 = widths[gc.col_start..gc.col_end].iter().sum();
                let cell = cell_width(gc.cell);
                if cell > span_sum {
                    let share = (cell - span_sum) / (gc.col_end - gc.col_start) as f32;
                    for w in &mut widths[gc.col_start..gc.col_end] {
                        *w += share;
                    }
                }
            }
        }
    }
    widths
}

/// Fit columns with the given natural (max-content) and min-content widths into `target`.
///
/// * The natural widths fit or fall short of `target`: they are scaled up proportionally
///   to fill it exactly (the table stretches to its width).
/// * They exceed `target`: the shrink is taken out of each column's (natural - min-content)
///   slack, in proportion to that slack, so no column goes below its min-content width.
/// * Even the min-content widths exceed `target`: every column stays at its min-content
///   width and the table overflows rather than the columns overlapping.
fn fit_columns(natural: &[f32], min_content: impl FnOnce() -> Vec<f32>, target: f32) -> Vec<f32> {
    let natural_sum: f32 = natural.iter().sum();
    if natural_sum <= 0.0 {
        return vec![target / natural.len().max(1) as f32; natural.len()];
    }
    if natural_sum <= target {
        let scale = target / natural_sum;
        return natural.iter().map(|w| w * scale).collect();
    }
    let min_content = min_content();
    let min_sum: f32 = min_content.iter().sum();
    if min_sum >= target {
        return min_content;
    }
    // `natural_sum > target > min_sum`, so the slack is positive.
    let keep = (target - min_sum) / (natural_sum - min_sum);
    natural
        .iter()
        .zip(&min_content)
        .map(|(n, m)| m + (n - m) * keep)
        .collect()
}

/// Under `table-layout: fixed`, the width a first-row cell contributes to its column.
///
/// * `width` given -> the value clamped by `min-width`/`max-width`
/// * `width: auto` with only `min-width` given -> `min-width` becomes the column's width
/// * neither (including a `max-width`-only setting) -> `None` (left to the even share of the remaining width)
fn fixed_cell_width(cell_style: &ComputedStyle, containing_width: f32) -> Option<f32> {
    match cell_style.width {
        LengthPercentageOrAuto::LengthPercentage(lp) => Some(clamp_used_width(
            cell_style,
            containing_width,
            0.0,
            0.0,
            resolve_lp(lp, containing_width),
        )),
        // The initial value of `min-width` is `0`. A 0 counts as "unspecified".
        LengthPercentageOrAuto::Auto => {
            let min = resolve_lp(cell_style.min_width, containing_width);
            (min > 0.0).then_some(min)
        }
    }
}

/// Fix the columns that have a `<col>` hint and distribute the rest over the unhinted
/// columns in proportion to their natural widths. When the hints add up to more than
/// `containing_width`, only the hinted columns are scaled down proportionally to fit.
fn distribute_with_column_hints(
    natural: &[f32],
    min_content: impl FnOnce() -> Vec<f32>,
    column_hints: &[Option<f32>],
    column_count: usize,
    containing_width: f32,
) -> Vec<f32> {
    let hint_of = |i: usize| column_hints.get(i).copied().flatten();
    let hint_sum: f32 = (0..column_count).filter_map(hint_of).sum();

    if hint_sum > containing_width && hint_sum > 0.0 {
        let scale = containing_width / hint_sum;
        return (0..column_count)
            .map(|i| hint_of(i).map(|w| w * scale).unwrap_or(0.0))
            .collect();
    }

    let auto_natural_sum: f32 = (0..column_count)
        .filter(|&i| hint_of(i).is_none())
        .map(|i| natural[i])
        .sum();
    let remaining = (containing_width - hint_sum).max(0.0);

    // When the unhinted columns have to shrink, they do so down to their min-content widths
    // and no further (the same rule as [`fit_columns`]).
    let auto_cols: Vec<usize> = (0..column_count)
        .filter(|&i| hint_of(i).is_none())
        .collect();
    let shrunk = (auto_natural_sum > remaining).then(|| {
        let n: Vec<f32> = auto_cols.iter().map(|&i| natural[i]).collect();
        fit_columns(
            &n,
            || {
                let all = min_content();
                auto_cols.iter().map(|&i| all[i]).collect()
            },
            remaining,
        )
    });

    (0..column_count)
        .map(|i| match hint_of(i) {
            Some(w) => w,
            None if shrunk.is_some() => {
                let pos = auto_cols.iter().position(|&c| c == i).unwrap_or(0);
                shrunk.as_ref().map_or(0.0, |v| v[pos])
            }
            None if auto_natural_sum > 0.0 => remaining * natural[i] / auto_natural_sum,
            None => {
                let auto_count = (0..column_count).filter(|&i| hint_of(i).is_none()).count();
                remaining / auto_count as f32
            }
        })
        .collect()
}

/// One cell's "natural width" (its content laid out without wrapping, plus padding and border).
///
/// The cell's own `min-width`/`max-width` are applied here as a clamp. A column's natural
/// width is the maximum of the clamped values, but the proportional scaling that follows
/// (fitting the table to the paper width) still happens, so the final column width does not guarantee `min-width`.
fn natural_cell_width(
    cell: &TableCell,
    styles: &HashMap<NodeId, Rc<ComputedStyle>>,
    fonts: &FontCollection,
) -> f32 {
    cell_content_width(cell, styles, fonts, Basis::Max)
}

/// One cell's min-content width (the same clamp and padding/border as [`natural_cell_width`],
/// around the content's min-content width).
fn min_cell_width(
    cell: &TableCell,
    styles: &HashMap<NodeId, Rc<ComputedStyle>>,
    fonts: &FontCollection,
) -> f32 {
    cell_content_width(cell, styles, fonts, Basis::Min)
}

fn cell_content_width(
    cell: &TableCell,
    styles: &HashMap<NodeId, Rc<ComputedStyle>>,
    fonts: &FontCollection,
    basis: Basis,
) -> f32 {
    let style = box_style(&cell.content, styles);
    // A percentage padding cannot resolve here, before layout is settled, because the basis
    // width is unknown, so it resolves against 0 (a simplification).
    let padding = resolve_padding(&style, 0.0);
    let border = resolve_border(&style);
    // The clamp is applied to the content width (min/max are content-box based) and
    // padding/border are added afterwards. The percentage basis for min/max is also unknown
    // at this point, so it too resolves against 0 (the same simplification as padding).
    let content_natural = measure_content_width(&cell.content, styles, fonts, basis);
    let clamped = clamp_used_width(
        &style,
        0.0,
        padding.left + padding.right,
        border.left + border.right,
        content_natural,
    );
    clamped + padding.left + padding.right + border.left + border.right
}

/// One child box's natural or min-content outer width (per `basis`): its content width plus its
/// own padding, border and margins. A definite `width` in px replaces the measured content width
/// (an empty icon box with `width: 10px` still takes 10px), and `box-sizing: border-box` is
/// honoured. A percentage resolves against 0, the basis width being unknown at this point
/// (the same simplification as `natural_cell_width`).
fn outer_content_width(
    child: &LayoutBox,
    styles: &HashMap<NodeId, Rc<ComputedStyle>>,
    fonts: &FontCollection,
    basis: Basis,
) -> f32 {
    let style = box_style(child, styles);
    let padding = resolve_padding(&style, 0.0);
    let border = resolve_border(&style);
    let pb_x = padding.left + padding.right + border.left + border.right;
    let content = match style.width {
        LengthPercentageOrAuto::LengthPercentage(LengthPercentage::Length(px)) => {
            if style.box_sizing == BoxSizing::BorderBox {
                (px - pb_x).max(0.0)
            } else {
                px
            }
        }
        _ => measure_content_width(child, styles, fonts, basis),
    };
    let margin_x =
        resolve_lpa_or_zero(style.margin_left, 0.0) + resolve_lpa_or_zero(style.margin_right, 0.0);
    content + pb_x + margin_x
}

/// The number of tracks `grid-template-columns` declares.
/// `repeat(auto-fill|auto-fit, ...)` counts as a single repetition under a min/max-content
/// constraint (as the CSS Grid spec prescribes).
fn declared_column_count(list: &TrackList) -> usize {
    list.components
        .iter()
        .map(|component| match component {
            TrackComponent::Single(_) => 1,
            TrackComponent::Repeat { count, tracks, .. } => match count {
                RepeatCount::Count(n) => *n as usize * tracks.len(),
                RepeatCount::AutoFill | RepeatCount::AutoFit => tracks.len(),
            },
        })
        .sum()
}

/// Measure a box's natural width (its max-content width): the width its content would take
/// laid out with no wrapping. Shared by the table's automatic column width algorithm, the
/// taffy measure bridge in `layout::flex`, and shrink-to-fit width (`width: auto` on a float, inline-block or absolutely positioned box).
///
/// A nested table, flex or grid is measured recursively according to the meaning of its own
/// axes. The breakdown is not the CSS specification itself but the following approximation,
/// all of it staying within "what can be found without actually solving item placement".
///
/// * flex: the sum of the items plus `column-gap` when the main axis is horizontal, the maximum when it is vertical
/// * grid: rows are cut at the number of tracks `grid-template-columns` declares, and the
///   maximum row sum is taken. `repeat(auto-fill|auto-fit, ...)` counts as one repetition, per the CSS spec.
///   Explicit placement (`grid-column`) and items spanning several tracks are not considered
/// * table: the maximum per row of the sum of the cell widths (`border-spacing` excluded)
///
/// The result is memoised on [`LayoutBox::natural_width`]. The same subtree is re-measured
/// from every ancestor level, and again from the throwaway layouts for each candidate width,
/// so without the memo the cost grows exponentially in the nesting depth.
pub(super) fn measure_natural_content_width(
    b: &LayoutBox,
    styles: &HashMap<NodeId, Rc<ComputedStyle>>,
    fonts: &FontCollection,
) -> f32 {
    if let Some(memo) = b.measured.natural_width() {
        return memo;
    }
    let width = compute_content_width(b, styles, fonts, Basis::Max);
    b.measured.set_natural_width(width);
    width
}

/// The min-content width of a box: the narrowest it can get without its content overflowing,
/// found by breaking every line at each opportunity (so the widest unbreakable run decides).
/// It is measured with the same breakdown as [`measure_natural_content_width`], with each
/// container taking the "min" reading of its own axes (a row flex container still sums its
/// items, since this engine does not shrink them below their own min-content, but a nested
/// table or grid row adds up the min-content of its cells).
pub(super) fn measure_min_content_width(
    b: &LayoutBox,
    styles: &HashMap<NodeId, Rc<ComputedStyle>>,
    fonts: &FontCollection,
) -> f32 {
    if let Some(memo) = b.measured.min_content_width() {
        return memo;
    }
    let width = compute_content_width(b, styles, fonts, Basis::Min);
    b.measured.set_min_content_width(width);
    width
}

/// Which intrinsic width is being measured.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Basis {
    /// Max-content: no line breaks except forced ones.
    Max,
    /// Min-content: a line break at every soft break opportunity.
    Min,
}

fn measure_content_width(
    b: &LayoutBox,
    styles: &HashMap<NodeId, Rc<ComputedStyle>>,
    fonts: &FontCollection,
    basis: Basis,
) -> f32 {
    match basis {
        Basis::Max => measure_natural_content_width(b, styles, fonts),
        Basis::Min => measure_min_content_width(b, styles, fonts),
    }
}

fn compute_content_width(
    b: &LayoutBox,
    styles: &HashMap<NodeId, Rc<ComputedStyle>>,
    fonts: &FontCollection,
    basis: Basis,
) -> f32 {
    match &b.content {
        BoxContent::Inline(spans) => {
            if basis == Basis::Min {
                if let Some(width) = plain_text_min_content_width(spans, styles, fonts, || {
                    measure_natural_content_width(b, styles, fonts)
                }) {
                    return width;
                }
            }
            // This is a measuring pass, so any `absolute` among an `inline-block`'s
            // descendants is discarded (the final layout pass walks the same descendants and collects them).
            let mut discarded = Vec::new();
            let mut pos = PosCtx::new(&mut discarded, (0.0, 0.0));
            let lines = layout_inline_content(
                spans.as_slice(),
                styles,
                fonts,
                // At min-content the line box is as narrow as it can get, so every soft
                // break opportunity is taken and the widest unbreakable run is what remains.
                if basis == Basis::Min {
                    0.0
                } else {
                    UNCONSTRAINED_WIDTH
                },
                0.0,
                0.0,
                None,
                // Not needed in a measuring pass: the width is unbounded, so `text-align` has no slack to distribute.
                None,
                &mut pos,
            );
            lines.iter().map(|l| l.rect.width).fold(0.0f32, f32::max)
        }
        BoxContent::Blocks(children) => children
            .iter()
            .map(|child| outer_content_width(child, styles, fonts, basis))
            .fold(0.0f32, f32::max),
        BoxContent::Flex(flex) => {
            let style = box_style(b, styles);
            let items: Vec<f32> = flex
                .items
                .iter()
                .map(|item| outer_content_width(item, styles, fonts, basis))
                .collect();
            match style.flex_direction {
                FlexDirection::Row | FlexDirection::RowReverse => {
                    let gaps =
                        resolve_lp(style.column_gap, 0.0) * (items.len().saturating_sub(1)) as f32;
                    items.iter().sum::<f32>() + gaps
                }
                // They stack vertically, so the widest item is the natural width outright.
                FlexDirection::Column | FlexDirection::ColumnReverse => {
                    items.into_iter().fold(0.0f32, f32::max)
                }
            }
        }
        BoxContent::Grid(grid) => {
            let style = box_style(b, styles);
            // With no declared tracks (`grid-template-columns: none`) there is one column.
            // Items flow along the row axis, so with one column each item takes a row.
            let columns = declared_column_count(&style.grid_template_columns).max(1);
            let gaps = resolve_lp(style.column_gap, 0.0) * (columns.saturating_sub(1)) as f32;
            grid.items
                .chunks(columns)
                .map(|row| {
                    row.iter()
                        .map(|item| outer_content_width(item, styles, fonts, basis))
                        .sum::<f32>()
                        + gaps
                })
                .fold(0.0f32, f32::max)
        }
        BoxContent::Table(table) => table
            .rows
            .iter()
            .map(|row| {
                row.cells
                    .iter()
                    .map(|cell| cell_content_width(cell, styles, fonts, basis))
                    .sum::<f32>()
            })
            .fold(0.0f32, f32::max),
        BoxContent::Image(image_content) => {
            replaced_natural_content_width(&box_style(b, styles), image_content)
        }
    }
}

/// A block-level replaced element's (`<img>`) content-box contribution to an intrinsic size.
///
/// This is its used width, not the image's natural width: an explicit `width` (or one derived
/// from `height` and the aspect ratio) clamped by `min-width`/`max-width`, and otherwise the
/// `width`/`height` attributes or the natural size, as `apply_replaced_element_auto_size`
/// resolves it for the final layout. A percentage `width` cannot resolve while the container's
/// size is still being determined, so it is treated as `auto` (CSS Sizing 3 5.2.1: a cyclic
/// percentage on a replaced element's width contributes as `auto` to max-content). A percentage
/// `max-width` (Tailwind's `img { max-width: 100% }`) is treated as `none` for the same reason.
/// Browsers also let such a replaced element shrink to 0 for min-content; the measure shared
/// with the callers does not distinguish min-content from max-content (see `layout::flex`).
fn replaced_natural_content_width(style: &ComputedStyle, image: &ImageBoxContent) -> f32 {
    let mut style = style.clone();
    let is_definite = |lp: LengthPercentage| matches!(lp, LengthPercentage::Length(_));
    if let LengthPercentageOrAuto::LengthPercentage(lp) = style.width {
        if !is_definite(lp) {
            style.width = LengthPercentageOrAuto::Auto;
        }
    }
    if let MaxSize::LengthPercentage(lp) = style.max_width {
        if !is_definite(lp) {
            style.max_width = MaxSize::None;
        }
    }
    if !is_definite(style.min_width) {
        style.min_width = LengthPercentage::Length(0.0);
    }
    apply_replaced_element_auto_size(&mut style, image, 0.0);
    let padding = resolve_padding(&style, 0.0);
    let border = resolve_border(&style);
    let padding_lr = padding.left + padding.right;
    let border_lr = border.left + border.right;
    let LengthPercentageOrAuto::LengthPercentage(LengthPercentage::Length(width)) = style.width
    else {
        // A settled `height` with no intrinsic ratio (the decode failed) leaves the width
        // `auto`. The final layout then shrinks to this same measure, so keep the attribute
        // (or natural) width it has always used rather than collapsing to 0.
        return image
            .attr_width
            .map(|w| w as f32)
            .or_else(|| image.image.as_ref().map(|img| img.width))
            .unwrap_or(0.0);
    };
    let width = if style.box_sizing == BoxSizing::BorderBox {
        (width - padding_lr - border_lr).max(0.0)
    } else {
        width
    };
    clamp_used_width(&style, 0.0, padding_lr, border_lr, width)
}

#[cfg(test)]
mod tests {
    use super::super::block::{layout_document, LaidOutBox};
    use super::super::box_tree::{build_box_tree, LayoutBox};
    use super::*;
    use crate::fonts::Font;
    use crate::html::{self, Dom, NodeData};
    use crate::style::{compute_styles, parse_stylesheet, user_agent_stylesheet};

    const TEST_FONT_PATH: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fonts/DejaVuSans.ttf");

    fn test_fonts() -> FontCollection {
        FontCollection::new(vec![
            Font::load(TEST_FONT_PATH).expect("should load bundled test font")
        ])
    }

    fn find(dom: &Dom, id: NodeId, tag: &str) -> Option<NodeId> {
        if let NodeData::Element { name, .. } = &dom.node(id).data {
            if &*name.local == tag {
                return Some(id);
            }
        }
        dom.children(id).find_map(|child| find(dom, child, tag))
    }

    /// A test-only `find_laid_out` that also descends into a `Table` (the caption included).
    fn find_laid_out(b: &LaidOutBox, target: NodeId) -> Option<&LaidOutBox> {
        if b.node == Some(target) {
            return Some(b);
        }
        match &b.content {
            super::super::block::LaidOutContent::Blocks(children) => children
                .iter()
                .find_map(|child| find_laid_out(child, target)),
            super::super::block::LaidOutContent::Grid(grid) => grid
                .rows
                .iter()
                .flat_map(|row| &row.items)
                .find_map(|item| find_laid_out(item, target)),
            super::super::block::LaidOutContent::Table(table) => table
                .caption
                .as_deref()
                .and_then(|caption| find_laid_out(caption, target))
                .or_else(|| {
                    table
                        .rows
                        .iter()
                        .flat_map(|row| &row.cells)
                        .find_map(|cell| find_laid_out(cell, target))
                }),
            super::super::block::LaidOutContent::Flex(children) => children
                .iter()
                .find_map(|child| find_laid_out(child, target)),
            super::super::block::LaidOutContent::Inline(_)
            | super::super::block::LaidOutContent::Image(_) => None,
        }
    }

    fn layout_table_html(html_src: &str, css: &str, containing_width: f32) -> LaidOutBox {
        let dom = html::parse(html_src.as_bytes());
        let ua = user_agent_stylesheet();
        let author = parse_stylesheet(css);
        let styles = compute_styles(&dom, &ua, &author);
        let tree = build_box_tree(&dom, &styles);
        let fonts = test_fonts();
        let laid = layout_document(&tree, &styles, &fonts, containing_width);
        let table_node = find(&dom, dom.document(), "table").expect("table not found");
        find_laid_out(&laid, table_node)
            .expect("table box not found")
            .clone()
    }

    fn cell_widths(table: &LaidOutBox, row: usize) -> Vec<f32> {
        let super::super::block::LaidOutContent::Table(laid_table) = &table.content else {
            panic!("expected a laid-out table");
        };
        laid_table.rows[row]
            .cells
            .iter()
            .map(|c| c.layout.border_box().width)
            .collect()
    }

    fn cell_lefts(table: &LaidOutBox, row: usize) -> Vec<f32> {
        let super::super::block::LaidOutContent::Table(laid_table) = &table.content else {
            panic!("expected a laid-out table");
        };
        laid_table.rows[row]
            .cells
            .iter()
            .map(|c| c.layout.border_box().x)
            .collect()
    }

    fn row_tops(table: &LaidOutBox) -> Vec<f32> {
        let super::super::block::LaidOutContent::Table(laid_table) = &table.content else {
            panic!("expected a laid-out table");
        };
        laid_table
            .rows
            .iter()
            .map(|row| row.cells[0].layout.border_box().y)
            .collect()
    }

    fn row_cells(table: &LaidOutBox, row: usize) -> &[LaidOutBox] {
        let super::super::block::LaidOutContent::Table(laid_table) = &table.content else {
            panic!("expected a laid-out table");
        };
        &laid_table.rows[row].cells
    }

    fn first_line_y(cell: &LaidOutBox) -> f32 {
        let super::super::block::LaidOutContent::Inline(lines) = &cell.content else {
            panic!("expected inline content");
        };
        lines[0].rect.y
    }

    /// Walk `b`'s content and return the `LaidOutTable` of the first nested table found.
    fn find_nested_table(b: &LaidOutBox) -> Option<&LaidOutTable> {
        match &b.content {
            super::super::block::LaidOutContent::Table(table) => Some(table),
            super::super::block::LaidOutContent::Blocks(children)
            | super::super::block::LaidOutContent::Flex(children) => {
                children.iter().find_map(find_nested_table)
            }
            super::super::block::LaidOutContent::Grid(grid) => grid
                .rows
                .iter()
                .flat_map(|row| &row.items)
                .find_map(find_nested_table),
            super::super::block::LaidOutContent::Inline(_)
            | super::super::block::LaidOutContent::Image(_) => None,
        }
    }

    #[test]
    fn table_stretches_to_fill_the_containing_width() {
        // Cancel out body's default margin (from the UA stylesheet) so the containing width
        // reaches the table unchanged.
        let table = layout_table_html(
            "<table><tr><td>a</td><td>bb</td></tr></table>",
            "body { margin: 0; }",
            700.0,
        );
        let super::super::block::LaidOutContent::Table(laid_table) = &table.content else {
            panic!("expected a laid-out table");
        };
        let total_width: f32 = laid_table.rows[0]
            .cells
            .iter()
            .map(|c| c.layout.border_box().width)
            .sum();
        assert!(
            (total_width - 700.0).abs() < 0.5,
            "table should stretch to fill the containing width, got {total_width}"
        );
    }

    #[test]
    fn wider_content_gets_a_proportionally_wider_column() {
        let table = layout_table_html(
            "<table><tr><td>x</td><td>a much much much longer piece of text</td></tr></table>",
            "",
            700.0,
        );
        let widths = cell_widths(&table, 0);
        assert!(
            widths[1] > widths[0] * 3.0,
            "the column with much longer content should be proportionally wider: {widths:?}"
        );
    }

    #[test]
    fn equal_content_produces_roughly_equal_columns() {
        // The same number of characters can still give different glyph widths (the advance of
        // 'a' and 'b' need not be equal), so verifying that the natural widths really are
        // identical requires using the same text.
        let table = layout_table_html(
            "<table><tr><td>identical</td><td>identical</td></tr></table>",
            "",
            700.0,
        );
        let widths = cell_widths(&table, 0);
        assert!(
            (widths[0] - widths[1]).abs() < 0.5,
            "identical content should produce identical column widths: {widths:?}"
        );
    }

    #[test]
    fn colspan_cell_widens_the_columns_it_spans() {
        // A three-column table: row 1 is a wide heading spanning the first two columns plus a
        // narrow cell in column 3; row 2 has the same narrow content in all three ("x"/"y"/"w").
        // On their own content (x/y), columns 0 and 1 would be the same width as column 2 (w),
        // but they are widened to accommodate row 1's wide colspan cell and should end up
        // clearly wider than column 2.
        let table = layout_table_html(
            r#"<table>
                <tr><td colspan="2">a much much much longer heading spanning both columns nicely</td><td>z</td></tr>
                <tr><td>x</td><td>y</td><td>w</td></tr>
            </table>"#,
            "",
            700.0,
        );
        let row1_widths = cell_widths(&table, 1);
        assert!(
            row1_widths[0] + row1_widths[1] > row1_widths[2] * 3.0,
            "columns spanned by the wide header should be widened relative to the untouched column: {row1_widths:?}"
        );
    }

    #[test]
    fn row_height_is_the_tallest_cell_in_that_row() {
        let table = layout_table_html(
            r#"<table>
                <tr><td style="height: 10px;">a</td><td style="height: 80px;">b</td></tr>
            </table>"#,
            "",
            700.0,
        );
        let super::super::block::LaidOutContent::Table(laid_table) = &table.content else {
            panic!("expected a laid-out table");
        };
        for cell in &laid_table.rows[0].cells {
            assert_eq!(
                cell.layout.margin_box_height(),
                80.0,
                "every cell in the row should occupy the tallest cell's height"
            );
        }
    }

    #[test]
    fn cells_in_the_same_row_are_placed_side_by_side() {
        let table = layout_table_html(
            "<table><tr><td>a</td><td>b</td><td>c</td></tr></table>",
            "",
            700.0,
        );
        let super::super::block::LaidOutContent::Table(laid_table) = &table.content else {
            panic!("expected a laid-out table");
        };
        let cells = &laid_table.rows[0].cells;
        for pair in cells.windows(2) {
            assert_eq!(
                pair[1].layout.border_box().x,
                pair[0].layout.border_box().x + pair[0].layout.border_box().width,
                "adjacent cells should touch with no gap"
            );
        }
    }

    #[test]
    fn empty_table_has_no_rows_and_zero_height() {
        let table = layout_table_html("<table></table>", "", 700.0);
        let super::super::block::LaidOutContent::Table(laid_table) = &table.content else {
            panic!("expected a laid-out table");
        };
        assert!(laid_table.rows.is_empty());
        assert_eq!(table.layout.content.height, 0.0);
    }

    #[test]
    fn table_layout_fixed_uses_first_row_widths_and_ignores_content() {
        // The first row's width settings (200px, 500px) become the column widths outright,
        // with the content length ignored entirely (short content such as row 2's "x" must
        // not change the column widths).
        let table = layout_table_html(
            r#"<table style="table-layout: fixed;">
                <tr><td style="width: 200px;">a</td><td style="width: 500px;">a much much much longer piece of text</td></tr>
                <tr><td>x</td><td>x</td></tr>
            </table>"#,
            "",
            700.0,
        );
        let widths = cell_widths(&table, 0);
        assert!((widths[0] - 200.0).abs() < 0.5, "widths: {widths:?}");
        assert!((widths[1] - 500.0).abs() < 0.5, "widths: {widths:?}");
    }

    #[test]
    fn table_layout_fixed_distributes_remaining_width_to_auto_columns() {
        let table = layout_table_html(
            r#"<table style="table-layout: fixed;">
                <tr><td style="width: 100px;">a</td><td>b</td><td>c</td></tr>
            </table>"#,
            "body { margin: 0; }",
            700.0,
        );
        let widths = cell_widths(&table, 0);
        // The remaining 600px is split evenly between the two auto columns = 300px each.
        assert!((widths[0] - 100.0).abs() < 0.5, "widths: {widths:?}");
        assert!((widths[1] - 300.0).abs() < 0.5, "widths: {widths:?}");
        assert!((widths[2] - 300.0).abs() < 0.5, "widths: {widths:?}");
    }

    #[test]
    fn table_layout_fixed_splits_a_colspan_width_evenly_across_spanned_columns() {
        let table = layout_table_html(
            r#"<table style="table-layout: fixed;">
                <tr><td colspan="2" style="width: 400px;">a</td></tr>
            </table>"#,
            "",
            700.0,
        );
        let widths = cell_widths(&table, 0);
        // 400px split evenly over 2 columns = 200px each; the colspan cell itself is 400px wide.
        assert!((widths[0] - 400.0).abs() < 0.5, "widths: {widths:?}");
    }

    #[test]
    fn border_spacing_adds_horizontal_gaps_between_and_around_columns() {
        // Containing width 700px, horizontal border-spacing 20px, 2 columns (equal content).
        // Width available to the columns = 700 - 20*3 (column count + 1 gaps) = 640 -> 320px each.
        let table = layout_table_html(
            "<table><tr><td>identical</td><td>identical</td></tr></table>",
            "body { margin: 0; } table { border-spacing: 20px 0; }",
            700.0,
        );
        let widths = cell_widths(&table, 0);
        let lefts = cell_lefts(&table, 0);
        assert!((widths[0] - 320.0).abs() < 0.5, "widths: {widths:?}");
        assert!((widths[1] - 320.0).abs() < 0.5, "widths: {widths:?}");
        assert!(
            (lefts[0] - 20.0).abs() < 0.5,
            "the first column should be inset by one spacing unit: {lefts:?}"
        );
        assert!(
            (lefts[1] - 360.0).abs() < 0.5,
            "the second column should start after column0 + 2 spacing units: {lefts:?}"
        );
    }

    #[test]
    fn border_spacing_adds_vertical_gaps_between_and_around_rows() {
        let table = layout_table_html(
            r#"<table>
                <tr><td style="height: 30px;">a</td></tr>
                <tr><td style="height: 30px;">b</td></tr>
            </table>"#,
            "body { margin: 0; } table { border-spacing: 0 15px; }",
            700.0,
        );
        let tops = row_tops(&table);
        assert!(
            (tops[0] - 15.0).abs() < 0.5,
            "the first row should be inset by one spacing unit: {tops:?}"
        );
        assert!(
            (tops[1] - 60.0).abs() < 0.5,
            "the second row should start after row0(30px) + 2 spacing units: {tops:?}"
        );
        // The overall height should include the `v_spacing` before and after: 15+30+15+30+15=105.
        assert!(
            (table.layout.content.height - 105.0).abs() < 0.5,
            "table height should include leading/trailing spacing: {}",
            table.layout.content.height
        );
    }

    #[test]
    fn border_collapse_forces_border_spacing_to_zero() {
        // Even with `border-spacing` given explicitly, `border-collapse: collapse` ignores it
        // and the cells should abut with no gap (the two are mutually exclusive).
        let table = layout_table_html(
            "<table><tr><td>a</td><td>b</td></tr></table>",
            "body { margin: 0; } table { border-spacing: 20px; border-collapse: collapse; }",
            700.0,
        );
        let lefts = cell_lefts(&table, 0);
        let widths = cell_widths(&table, 0);
        assert!(
            lefts[0].abs() < 0.5,
            "with collapse the first column should touch the table's edge: {lefts:?}"
        );
        assert!(
            (lefts[1] - (lefts[0] + widths[0])).abs() < 0.5,
            "with collapse adjacent cells should touch with no gap: lefts={lefts:?} widths={widths:?}"
        );
    }

    #[test]
    fn vertical_align_top_keeps_content_flush_with_the_row_top() {
        let table = layout_table_html(
            r#"<table>
                <tr><td style="height: 10px;">a</td><td style="height: 80px;">b</td></tr>
            </table>"#,
            "body { margin: 0; } td { vertical-align: top; }",
            700.0,
        );
        for cell in row_cells(&table, 0) {
            assert_eq!(
                first_line_y(cell),
                0.0,
                "top-aligned content should stay flush with the row top"
            );
        }
    }

    #[test]
    fn vertical_align_bottom_pushes_the_shorter_cells_content_to_the_bottom() {
        let table = layout_table_html(
            r#"<table>
                <tr><td style="height: 10px;">a</td><td style="height: 80px;">b</td></tr>
            </table>"#,
            "body { margin: 0; } td { vertical-align: bottom; }",
            700.0,
        );
        let cells = row_cells(&table, 0);
        assert!(
            first_line_y(&cells[1]).abs() < 0.5,
            "the tallest cell defines the row height so its own content shouldn't shift: {}",
            first_line_y(&cells[1])
        );
        assert!(
            (first_line_y(&cells[0]) - 70.0).abs() < 0.5,
            "the shorter cell's content should be pushed down by the full deficit(80-10=70px): {}",
            first_line_y(&cells[0])
        );
    }

    #[test]
    fn vertical_align_middle_centers_the_shorter_cells_content() {
        let table = layout_table_html(
            r#"<table>
                <tr><td style="height: 10px;">a</td><td style="height: 80px;">b</td></tr>
            </table>"#,
            "body { margin: 0; } td { vertical-align: middle; }",
            700.0,
        );
        let cells = row_cells(&table, 0);
        assert!(
            first_line_y(&cells[1]).abs() < 0.5,
            "the tallest cell defines the row height so its own content shouldn't shift: {}",
            first_line_y(&cells[1])
        );
        assert!(
            (first_line_y(&cells[0]) - 35.0).abs() < 0.5,
            "the shorter cell's content should be pushed down by half the deficit((80-10)/2=35px): {}",
            first_line_y(&cells[0])
        );
    }

    #[test]
    fn vertical_align_baseline_aligns_first_lines_of_cells_with_different_font_sizes() {
        // Even between cells with different font sizes (and so different line heights), the
        // text baselines themselves should line up at the same Y (CSS2.1 17.5.3 baseline alignment).
        let table = layout_table_html(
            r#"<table>
                <tr><td style="font-size: 12px;">Ay</td><td style="font-size: 36px;">Ay</td></tr>
            </table>"#,
            "body { margin: 0; } td { vertical-align: baseline; }",
            700.0,
        );
        let fonts = test_fonts();
        let cells = row_cells(&table, 0);
        let baseline_y = |cell: &LaidOutBox| {
            let super::super::block::LaidOutContent::Inline(lines) = &cell.content else {
                panic!("expected inline content");
            };
            let run = lines[0].runs.first().expect("cell should have text");
            let font = fonts.get(run.font_index).expect("font should be loaded");
            lines[0].rect.y + font.baseline_offset(run.font_size, lines[0].rect.height)
        };

        let small_baseline = baseline_y(&cells[0]);
        let large_baseline = baseline_y(&cells[1]);
        assert!(
            (small_baseline - large_baseline).abs() < 0.5,
            "baseline-aligned cells should share the same baseline Y: small={small_baseline} large={large_baseline}"
        );
    }

    #[test]
    fn vertical_align_baseline_falls_back_to_bottom_for_content_without_a_baseline() {
        // A nested table has no baseline (a known simplification), so it should fall back to
        // the equivalent of `bottom`.
        let table = layout_table_html(
            r#"<table>
                <tr>
                    <td style="height: 80px;">a</td>
                    <td style="height: 10px;"><table><tr><td>nested</td></tr></table></td>
                </tr>
            </table>"#,
            "body { margin: 0; } td { vertical-align: baseline; }",
            700.0,
        );
        let cells = row_cells(&table, 0);
        let nested_top_y = find_nested_table(&cells[1])
            .expect("expected the outer cell to contain a nested table")
            .rows[0]
            .cells[0]
            .layout
            .border_box()
            .y;
        assert!(
            (nested_top_y - 70.0).abs() < 0.5,
            "content without a baseline should fall back to bottom alignment (deficit=80-10=70px): {nested_top_y}"
        );
    }

    fn grid_cell(colspan: usize, rowspan: usize) -> TableCell {
        TableCell {
            node: Some(NodeId(0)),
            colspan,
            rowspan,
            content: LayoutBox::anonymous(BoxContent::Inline(Vec::new())),
        }
    }

    fn grid_row(cells: Vec<TableCell>) -> TableRow {
        TableRow {
            node: Some(NodeId(0)),
            cells,
            section: super::super::box_tree::TableSection::Body,
            group: None,
        }
    }

    /// Convert to a list of `(col_start, col_end)` to make the grid construction easy to check.
    fn grid_spans(grid: &[Vec<GridCell<'_>>]) -> Vec<Vec<(usize, usize)>> {
        grid.iter()
            .map(|row| row.iter().map(|gc| (gc.col_start, gc.col_end)).collect())
            .collect()
    }

    #[test]
    fn build_table_grid_matches_the_naive_colspan_walk_when_rowspan_is_always_one() {
        let rows = vec![
            grid_row(vec![grid_cell(2, 1), grid_cell(1, 1)]),
            grid_row(vec![grid_cell(1, 1), grid_cell(1, 1), grid_cell(1, 1)]),
        ];
        let (grid, column_count) = build_table_grid(&rows);
        assert_eq!(column_count, 3);
        assert_eq!(
            grid_spans(&grid),
            vec![vec![(0, 2), (2, 3)], vec![(0, 1), (1, 2), (2, 3)]]
        );
    }

    #[test]
    fn build_table_grid_skips_columns_occupied_by_a_rowspan_cell() {
        // Row 0: col0 is rowspan=2 and occupies two rows; col1 is an ordinary cell.
        // Row 1: only one cell, but col0 is still filled by the rowspan, so it should be
        // placed from col1.
        // Row 2: the rowspan has expired, so placement should start from col0 again.
        let rows = vec![
            grid_row(vec![grid_cell(1, 2), grid_cell(1, 1)]),
            grid_row(vec![grid_cell(1, 1)]),
            grid_row(vec![grid_cell(1, 1), grid_cell(1, 1)]),
        ];
        let (grid, column_count) = build_table_grid(&rows);
        assert_eq!(column_count, 2);
        assert_eq!(
            grid_spans(&grid),
            vec![vec![(0, 1), (1, 2)], vec![(1, 2)], vec![(0, 1), (1, 2)]]
        );
    }

    #[test]
    fn build_table_grid_handles_rowspan_and_colspan_combined() {
        // Row 0: a cell spanning col0..2 (colspan=2) with rowspan=2, occupying two rows.
        // Row 1: both col0 and col1 are filled, so the next cell is placed from col2.
        let rows = vec![
            grid_row(vec![grid_cell(2, 2), grid_cell(1, 1)]),
            grid_row(vec![grid_cell(1, 1)]),
        ];
        let (grid, column_count) = build_table_grid(&rows);
        assert_eq!(column_count, 3);
        assert_eq!(grid_spans(&grid), vec![vec![(0, 2), (2, 3)], vec![(2, 3)]]);
    }

    #[test]
    fn build_table_grid_counts_a_column_that_only_exists_after_a_rowspan_is_skipped() {
        // Row 0 is a single rowspan=2 cell. Its colspan sum is 1, but row 1's cell goes to
        // col1 because col0 is still filled, so the table has 2 columns.
        let rows = vec![
            grid_row(vec![grid_cell(1, 2)]),
            grid_row(vec![grid_cell(1, 1)]),
        ];
        let (grid, column_count) = build_table_grid(&rows);
        assert_eq!(
            column_count, 2,
            "the column opened up next to the rowspan cell must be counted"
        );
        assert_eq!(grid_spans(&grid), vec![vec![(0, 1)], vec![(1, 2)]]);
    }

    #[test]
    fn rowspan_cell_spans_the_full_height_of_the_rows_it_covers() {
        // "tall" (rowspan=2, an explicit 80px) exceeds the natural heights of rows 0 and 1
        // (which have only 10px cells), so both rows should expand to 40px each and "tall"
        // itself should end up exactly their sum (= 80px).
        let table = layout_table_html(
            r#"<table>
                <tr><td rowspan="2" style="height: 80px;">tall</td><td style="height: 10px;">a</td></tr>
                <tr><td style="height: 10px;">b</td></tr>
            </table>"#,
            "body { margin: 0; }",
            700.0,
        );
        let row0 = row_cells(&table, 0);
        let row1 = row_cells(&table, 1);
        assert_eq!(row1.len(), 1, "row1 should only have its own single cell");

        assert!(
            (row0[0].layout.margin_box_height() - 80.0).abs() < 0.5,
            "the rowspan cell should span exactly the combined height of both rows: {}",
            row0[0].layout.margin_box_height()
        );
        assert!(
            (row0[1].layout.margin_box_height() - 40.0).abs() < 0.5,
            "row0's non-spanning cell should be stretched to row0's height(40px): {}",
            row0[1].layout.margin_box_height()
        );
        assert!(
            (row1[0].layout.border_box().y - 40.0).abs() < 0.5,
            "row1 should start after row0's height(40px): {}",
            row1[0].layout.border_box().y
        );
    }

    #[test]
    fn rowspan_cell_makes_the_following_row_skip_its_occupied_column() {
        // Row 1 has only one cell, but col0 is occupied by row 0's rowspan cell, so it
        // should be placed in col1 (the same column as row 0's second cell).
        let table = layout_table_html(
            r#"<table>
                <tr><td rowspan="2">tall</td><td>a</td></tr>
                <tr><td>b</td></tr>
            </table>"#,
            "body { margin: 0; }",
            700.0,
        );
        let row0_lefts = cell_lefts(&table, 0);
        let row1 = row_cells(&table, 1);
        assert!(
            (row1[0].layout.border_box().x - row0_lefts[1]).abs() < 0.5,
            "row1's single cell should land in column1 (same x as row0's second cell), not column0: row1_x={} row0_col1_x={}",
            row1[0].layout.border_box().x,
            row0_lefts[1]
        );
    }

    // ===== <colgroup>/<col> (column width settings) =====

    #[test]
    fn col_width_fixes_the_column_width_in_auto_layout() {
        // Set border-spacing to 0 so the column width and the cell's border-box width compare directly.
        let table = layout_table_html(
            r#"<table>
                 <colgroup><col style="width: 100px;"><col></colgroup>
                 <tr><td>a</td><td>bbbbbbbbbbbbbbbb</td></tr>
               </table>"#,
            "body { margin: 0; } table { border-spacing: 0; }",
            500.0,
        );
        let widths = cell_widths(&table, 0);
        assert!((widths[0] - 100.0).abs() < 0.5, "got {widths:?}");
        // The unspecified columns get all of the remaining width.
        assert!((widths[1] - 400.0).abs() < 0.5, "got {widths:?}");
    }

    #[test]
    fn col_percentage_width_resolves_against_the_table_width() {
        let table = layout_table_html(
            r#"<table>
                 <colgroup><col style="width: 20%;"><col></colgroup>
                 <tr><td>a</td><td>b</td></tr>
               </table>"#,
            "body { margin: 0; } table { border-spacing: 0; }",
            500.0,
        );
        let widths = cell_widths(&table, 0);
        assert!((widths[0] - 100.0).abs() < 0.5, "got {widths:?}");
    }

    #[test]
    fn col_span_applies_the_same_width_to_several_columns() {
        let table = layout_table_html(
            r#"<table>
                 <colgroup><col span="2" style="width: 50px;"><col></colgroup>
                 <tr><td>a</td><td>b</td><td>c</td></tr>
               </table>"#,
            "body { margin: 0; } table { border-spacing: 0; }",
            500.0,
        );
        let widths = cell_widths(&table, 0);
        assert!((widths[0] - 50.0).abs() < 0.5, "got {widths:?}");
        assert!((widths[1] - 50.0).abs() < 0.5, "got {widths:?}");
        assert!((widths[2] - 400.0).abs() < 0.5, "got {widths:?}");
    }

    #[test]
    fn colgroup_span_without_col_children_defines_the_columns_itself() {
        let table = layout_table_html(
            r#"<table>
                 <colgroup span="2" style="width: 60px;"></colgroup>
                 <tr><td>a</td><td>b</td><td>c</td></tr>
               </table>"#,
            "body { margin: 0; } table { border-spacing: 0; }",
            500.0,
        );
        let widths = cell_widths(&table, 0);
        assert!((widths[0] - 60.0).abs() < 0.5, "got {widths:?}");
        assert!((widths[1] - 60.0).abs() < 0.5, "got {widths:?}");
        assert!((widths[2] - 380.0).abs() < 0.5, "got {widths:?}");
    }

    #[test]
    fn columns_without_a_col_hint_share_the_rest_proportionally_to_their_content() {
        let table = layout_table_html(
            r#"<table>
                 <colgroup><col style="width: 100px;"><col><col></colgroup>
                 <tr><td>a</td><td>short</td><td>a much much much longer cell</td></tr>
               </table>"#,
            "body { margin: 0; } table { border-spacing: 0; }",
            500.0,
        );
        let widths = cell_widths(&table, 0);
        assert!((widths[0] - 100.0).abs() < 0.5, "got {widths:?}");
        assert!(
            widths[2] > widths[1],
            "the column with more content should get more of the remaining width: {widths:?}"
        );
        let total: f32 = widths.iter().sum();
        assert!((total - 500.0).abs() < 1.0, "got {widths:?}");
    }

    #[test]
    fn col_hints_wider_than_the_table_are_scaled_down_to_fit() {
        // When the settings add up to more than the available width, only the specified columns are scaled down.
        let table = layout_table_html(
            r#"<table>
                 <colgroup><col style="width: 600px;"><col style="width: 200px;"></colgroup>
                 <tr><td>a</td><td>b</td></tr>
               </table>"#,
            "body { margin: 0; } table { border-spacing: 0; }",
            400.0,
        );
        let widths = cell_widths(&table, 0);
        assert!((widths[0] - 300.0).abs() < 0.5, "got {widths:?}");
        assert!((widths[1] - 100.0).abs() < 0.5, "got {widths:?}");
    }

    #[test]
    fn col_width_takes_precedence_over_the_first_row_cell_in_fixed_layout() {
        let table = layout_table_html(
            r#"<table>
                 <colgroup><col style="width: 300px;"><col></colgroup>
                 <tr><td style="width: 100px;">a</td><td>b</td></tr>
               </table>"#,
            "body { margin: 0; } table { table-layout: fixed; border-spacing: 0; }",
            500.0,
        );
        let widths = cell_widths(&table, 0);
        assert!(
            (widths[0] - 300.0).abs() < 0.5,
            "the <col> width must win over the first row cell: {widths:?}"
        );
        assert!((widths[1] - 200.0).abs() < 0.5, "got {widths:?}");
    }

    #[test]
    fn a_table_without_colgroup_keeps_the_previous_behaviour() {
        // Regression check: with no hints at all, every column is scaled proportionally as before.
        let table = layout_table_html(
            r#"<table><tr><td>a</td><td>a much much much longer cell</td></tr></table>"#,
            "body { margin: 0; } table { border-spacing: 0; }",
            500.0,
        );
        let widths = cell_widths(&table, 0);
        let total: f32 = widths.iter().sum();
        assert!((total - 500.0).abs() < 1.0, "got {widths:?}");
        assert!(widths[1] > widths[0], "got {widths:?}");
    }

    /// The widest line laid out inside a box (descending through nested blocks).
    fn widest_line(b: &LaidOutBox) -> f32 {
        match &b.content {
            super::super::block::LaidOutContent::Inline(lines) => {
                lines.iter().map(|l| l.rect.width).fold(0.0, f32::max)
            }
            super::super::block::LaidOutContent::Blocks(children) => {
                children.iter().map(widest_line).fold(0.0, f32::max)
            }
            _ => 0.0,
        }
    }

    /// Assert that no cell's text runs past its content box (the content box is the cell's
    /// border box minus its horizontal padding, which these tests set to a known value).
    fn assert_no_cell_overflows(table: &LaidOutBox, padding: f32) {
        let super::super::block::LaidOutContent::Table(laid_table) = &table.content else {
            panic!("expected a laid-out table");
        };
        for row in &laid_table.rows {
            for cell in &row.cells {
                let content = cell.layout.border_box().width - 2.0 * padding;
                let line = widest_line(cell);
                assert!(
                    line <= content + 0.01,
                    "text of {line} overflows a cell content box of {content}"
                );
            }
        }
    }

    const SHRINK_HTML: &str = "<table><tr><th>ITEM</th><th>PRICE</th><th>TOTAL</th></tr>\
        <tr><td>Refund August overpayment caused by understated sibling deposit</td>\
        <td>$300.00</td><td>$3,480.00</td></tr></table>";
    const SHRINK_CSS: &str = "body { margin: 0; } td, th { padding: 4px; }";

    #[test]
    fn shrinking_takes_the_space_from_the_wrappable_column() {
        // The table's natural width is above 300, so it must shrink. The amounts cannot wrap,
        // so the long first column has to give up all of the space.
        let table = layout_table_html(SHRINK_HTML, SHRINK_CSS, 300.0);
        assert_no_cell_overflows(&table, 4.0);
        let widths = cell_widths(&table, 1);
        assert!(
            (widths.iter().sum::<f32>() - 300.0).abs() < 0.5,
            "got {widths:?}"
        );
    }

    #[test]
    fn a_column_of_unbreakable_text_keeps_its_min_content_width_at_any_table_width() {
        for containing in [260.0, 300.0, 400.0, 600.0] {
            let table = layout_table_html(SHRINK_HTML, SHRINK_CSS, containing);
            assert_no_cell_overflows(&table, 4.0);
        }
    }

    #[test]
    fn columns_overflow_instead_of_overlapping_when_min_content_exceeds_the_table() {
        // 60px cannot hold the two amounts side by side, so the table overflows its
        // container and the columns stay laid out one after another.
        let table = layout_table_html(SHRINK_HTML, SHRINK_CSS, 60.0);
        assert_no_cell_overflows(&table, 4.0);
        let lefts = cell_lefts(&table, 1);
        let widths = cell_widths(&table, 1);
        for i in 1..lefts.len() {
            assert!(
                lefts[i] >= lefts[i - 1] + widths[i - 1] - 0.01,
                "columns overlap: lefts {lefts:?}, widths {widths:?}"
            );
        }
    }

    #[test]
    fn fit_columns_shrinks_only_the_slack_above_min_content() {
        // natural 100 + 40, min 20 + 40: the whole 30 of shrinking comes out of column 0.
        let w = fit_columns(&[100.0, 40.0], || vec![20.0, 40.0], 110.0);
        assert!(
            (w[0] - 70.0).abs() < 0.01 && (w[1] - 40.0).abs() < 0.01,
            "{w:?}"
        );
        // The shrink is shared in proportion to the slack when both columns have some.
        let w = fit_columns(&[100.0, 50.0], || vec![40.0, 30.0], 120.0);
        assert!((w.iter().sum::<f32>() - 120.0).abs() < 0.01, "{w:?}");
        assert!(w[0] >= 40.0 && w[1] >= 30.0, "{w:?}");
    }

    #[test]
    fn fit_columns_stretches_proportionally_and_never_goes_below_min_content() {
        let w = fit_columns(&[10.0, 30.0], || vec![5.0, 30.0], 80.0);
        assert!(
            (w[0] - 20.0).abs() < 0.01 && (w[1] - 60.0).abs() < 0.01,
            "{w:?}"
        );
        // Even the min-content widths do not fit: they are kept (the table overflows).
        let w = fit_columns(&[100.0, 40.0], || vec![20.0, 40.0], 50.0);
        assert_eq!(w, vec![20.0, 40.0]);
    }

    #[test]
    fn unhinted_columns_keep_min_content_next_to_a_col_width_hint() {
        let table = layout_table_html(
            "<table><colgroup><col style=\"width: 130px\"><col><col></colgroup>\
             <tr><td>Refund August overpayment caused by understated sibling deposit</td>\
             <td>$300.00</td><td>$3,480.00</td></tr></table>",
            SHRINK_CSS,
            300.0,
        );
        assert_no_cell_overflows(&table, 4.0);
        let widths = cell_widths(&table, 0);
        assert!((widths[0] - 130.0).abs() < 0.5, "got {widths:?}");
    }

    /// The widest line from a full layout at width 0 (what min-content falls back to).
    fn slow_min_content(b: &LayoutBox, styles: &HashMap<NodeId, Rc<ComputedStyle>>) -> f32 {
        let BoxContent::Inline(spans) = &b.content else {
            panic!("expected inline content");
        };
        let mut discarded = Vec::new();
        let mut pos = PosCtx::new(&mut discarded, (0.0, 0.0));
        layout_inline_content(
            spans.as_slice(),
            styles,
            &test_fonts(),
            0.0,
            0.0,
            0.0,
            None,
            None,
            &mut pos,
        )
        .iter()
        .map(|l| l.rect.width)
        .fold(0.0f32, f32::max)
    }

    #[test]
    fn plain_text_min_content_matches_a_zero_width_line_layout() {
        clear_word_width_cache();
        let texts = [
            "$3,480.00",
            "Refund August overpayment caused by understated sibling deposit",
            "  leading and   trailing   ",
            "a-very-long-hyphenated-word is here",
            "W i i i",
        ];
        for css in [
            "",
            "td { letter-spacing: 2px; font-size: 20px; }",
            "td { letter-spacing: -1px; }",
            "td { hyphens: auto; }",
            "td { hyphens: none; }",
            "td { text-indent: 20px; }",
        ] {
            for text in texts {
                let dom =
                    html::parse(format!("<table><tr><td>{text}</td></tr></table>").as_bytes());
                let ua = user_agent_stylesheet();
                let styles = compute_styles(&dom, &ua, &parse_stylesheet(css));
                let tree = build_box_tree(&dom, &styles);
                fn first_cell(b: &LayoutBox) -> Option<&LayoutBox> {
                    match &b.content {
                        BoxContent::Table(t) => t.rows.first()?.cells.first().map(|c| &c.content),
                        BoxContent::Blocks(children) => children.iter().find_map(first_cell),
                        _ => None,
                    }
                }
                let cell = first_cell(&tree).expect("cell");
                let BoxContent::Inline(spans) = &cell.content else {
                    panic!("expected inline content");
                };
                let fast = plain_text_min_content_width(spans, &styles, &test_fonts(), || {
                    measure_natural_content_width(cell, &styles, &test_fonts())
                });
                let slow = slow_min_content(cell, &styles);
                match fast {
                    Some(fast) => assert!(
                        (fast - slow).abs() < 0.01,
                        "{text:?} with {css:?}: fast {fast} vs layout {slow}"
                    ),
                    // `text-indent` is left to the full layout.
                    None => assert!(css.contains("text-indent"), "{text:?} with {css:?}"),
                }
            }
        }
    }

    const NOWRAP_ROW: &str = r#"<table><tr><td class="item">Refund August overpayment caused by an understated sibling deposit, final</td><td>$3,480.00</td></tr></table>"#;

    #[test]
    fn nowrap_cell_keeps_its_line_and_the_table_box_grows_with_the_columns() {
        let css = "body { margin: 0; } table { width: 540px; border-spacing: 0; } .item { white-space: nowrap; }";
        let table = layout_table_html(NOWRAP_ROW, css, 800.0);
        let widths = cell_widths(&table, 0);
        let total: f32 = widths.iter().sum();
        assert!(total > 540.0, "columns must overflow 540px, got {widths:?}");
        assert!(
            (table.layout.content.width - total).abs() < 0.5,
            "the table box must grow with its columns: box {} vs columns {total}",
            table.layout.content.width
        );
    }

    #[test]
    fn table_box_keeps_its_specified_width_when_the_columns_fit() {
        let css = "body { margin: 0; } table { width: 800px; border-spacing: 0; } .item { white-space: nowrap; }";
        let table = layout_table_html(NOWRAP_ROW, css, 800.0);
        assert!((table.layout.content.width - 800.0).abs() < 0.5);
    }

    /// The border box width of the first element with this tag.
    fn laid_out_width_of(html_src: &str, css: &str, containing_width: f32, tag: &str) -> f32 {
        let dom = html::parse(html_src.as_bytes());
        let ua = user_agent_stylesheet();
        let author = parse_stylesheet(css);
        let styles = compute_styles(&dom, &ua, &author);
        let tree = build_box_tree(&dom, &styles);
        let fonts = test_fonts();
        let laid = layout_document(&tree, &styles, &fonts, containing_width);
        let node = find(&dom, dom.document(), tag).expect("element not found");
        find_laid_out(&laid, node)
            .expect("box not found")
            .layout
            .border_box()
            .width
    }

    #[test]
    fn float_with_nowrap_text_does_not_shrink_below_the_line() {
        let css = "body { margin: 0; } .w { width: 60px; } .f { float: left; }";
        let nowrap = laid_out_width_of(
            r#"<div class="w"><p class="f" style="white-space: nowrap">aaaa bbbb cccc dddd</p></div>"#,
            css,
            800.0,
            "p",
        );
        let wide = laid_out_width_of(
            r#"<div><p class="f" style="white-space: nowrap">aaaa bbbb cccc dddd</p></div>"#,
            css,
            800.0,
            "p",
        );
        assert!((nowrap - wide).abs() < 0.5, "{nowrap} vs {wide}");
        assert!(nowrap > 60.0);
    }

    #[test]
    fn float_with_wrappable_text_still_shrinks_to_the_available_width() {
        let css = "body { margin: 0; } .w { width: 100px; } .f { float: left; }";
        let w = laid_out_width_of(
            r#"<div class="w"><p class="f">aaaa bbbb cccc dddd eeee ffff</p></div>"#,
            css,
            800.0,
            "p",
        );
        assert!((w - 100.0).abs() < 0.5, "got {w}");
    }
}