taffy/compute/flexbox.rs
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 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202
//! Computes the [flexbox](https://css-tricks.com/snippets/css/a-guide-to-flexbox/) layout algorithm on [`TaffyTree`](crate::TaffyTree) according to the [spec](https://www.w3.org/TR/css-flexbox-1/)
use crate::compute::common::alignment::compute_alignment_offset;
use crate::geometry::{Line, Point, Rect, Size};
use crate::style::{
AlignContent, AlignItems, AlignSelf, AvailableSpace, Dimension, Display, FlexWrap, JustifyContent,
LengthPercentageAuto, Overflow, Position,
};
use crate::style::{FlexDirection, Style};
use crate::style_helpers::{TaffyMaxContent, TaffyMinContent};
use crate::tree::{Layout, LayoutInput, LayoutOutput, RunMode, SizingMode};
use crate::tree::{NodeId, PartialLayoutTree, PartialLayoutTreeExt};
use crate::util::debug::debug_log;
use crate::util::sys::{f32_max, new_vec_with_capacity, Vec};
use crate::util::MaybeMath;
use crate::util::{MaybeResolve, ResolveOrZero};
#[cfg(feature = "content_size")]
use super::common::content_size::compute_content_size_contribution;
/// The intermediate results of a flexbox calculation for a single item
struct FlexItem {
/// The identifier for the associated node
node: NodeId,
/// The order of the node relative to it's siblings
order: u32,
/// The base size of this item
size: Size<Option<f32>>,
/// The minimum allowable size of this item
min_size: Size<Option<f32>>,
/// The maximum allowable size of this item
max_size: Size<Option<f32>>,
/// The cross-alignment of this item
align_self: AlignSelf,
/// The overflow style of the item
overflow: Point<Overflow>,
/// The width of the scrollbars (if it has any)
scrollbar_width: f32,
/// The flex shrink style of the item
flex_shrink: f32,
/// The flex grow style of the item
flex_grow: f32,
/// The minimum size of the item. This differs from min_size above because it also
/// takes into account content based automatic minimum sizes
resolved_minimum_main_size: f32,
/// The final offset of this item
inset: Rect<Option<f32>>,
/// The margin of this item
margin: Rect<f32>,
/// Whether each margin is an auto margin or not
margin_is_auto: Rect<bool>,
/// The padding of this item
padding: Rect<f32>,
/// The border of this item
border: Rect<f32>,
/// The default size of this item
flex_basis: f32,
/// The default size of this item, minus padding and border
inner_flex_basis: f32,
/// The amount by which this item has deviated from its target size
violation: f32,
/// Is the size of this item locked
frozen: bool,
/// Either the max- or min- content flex fraction
/// See https://www.w3.org/TR/css-flexbox-1/#intrinsic-main-sizes
content_flex_fraction: f32,
/// The proposed inner size of this item
hypothetical_inner_size: Size<f32>,
/// The proposed outer size of this item
hypothetical_outer_size: Size<f32>,
/// The size that this item wants to be
target_size: Size<f32>,
/// The size that this item wants to be, plus any padding and border
outer_target_size: Size<f32>,
/// The position of the bottom edge of this item
baseline: f32,
/// A temporary value for the main offset
///
/// Offset is the relative position from the item's natural flow position based on
/// relative position values, alignment, and justification. Does not include margin/padding/border.
offset_main: f32,
/// A temporary value for the cross offset
///
/// Offset is the relative position from the item's natural flow position based on
/// relative position values, alignment, and justification. Does not include margin/padding/border.
offset_cross: f32,
}
/// A line of [`FlexItem`] used for intermediate computation
struct FlexLine<'a> {
/// The slice of items to iterate over during computation of this line
items: &'a mut [FlexItem],
/// The dimensions of the cross-axis
cross_size: f32,
/// The relative offset of the cross-axis
offset_cross: f32,
}
/// Values that can be cached during the flexbox algorithm
struct AlgoConstants {
/// The direction of the current segment being laid out
dir: FlexDirection,
/// Is this segment a row
is_row: bool,
/// Is this segment a column
is_column: bool,
/// Is wrapping enabled (in either direction)
is_wrap: bool,
/// Is the wrap direction inverted
is_wrap_reverse: bool,
/// The item's min_size style
min_size: Size<Option<f32>>,
/// The item's max_size style
max_size: Size<Option<f32>>,
/// The margin of this section
margin: Rect<f32>,
/// The border of this section
border: Rect<f32>,
/// The space between the content box and the border box.
/// This consists of padding + border + scrollbar_gutter.
content_box_inset: Rect<f32>,
/// The size reserved for scrollbar gutters in each axis
scrollbar_gutter: Point<f32>,
/// The gap of this section
gap: Size<f32>,
/// The align_items property of this node
align_items: AlignItems,
/// The align_content property of this node
align_content: AlignContent,
/// The justify_content property of this node
justify_content: Option<JustifyContent>,
/// The border-box size of the node being laid out (if known)
node_outer_size: Size<Option<f32>>,
/// The content-box size of the node being laid out (if known)
node_inner_size: Size<Option<f32>>,
/// The size of the virtual container containing the flex items.
container_size: Size<f32>,
/// The size of the internal container
inner_container_size: Size<f32>,
}
/// Computes the layout of [`PartialLayoutTree`] according to the flexbox algorithm
pub fn compute_flexbox_layout(tree: &mut impl PartialLayoutTree, node: NodeId, inputs: LayoutInput) -> LayoutOutput {
let LayoutInput { known_dimensions, parent_size, run_mode, .. } = inputs;
let style = tree.get_style(node);
// Pull these out earlier to avoid borrowing issues
let aspect_ratio = style.aspect_ratio;
let min_size = style.min_size.maybe_resolve(parent_size).maybe_apply_aspect_ratio(aspect_ratio);
let max_size = style.max_size.maybe_resolve(parent_size).maybe_apply_aspect_ratio(aspect_ratio);
let clamped_style_size = if inputs.sizing_mode == SizingMode::InherentSize {
style.size.maybe_resolve(parent_size).maybe_apply_aspect_ratio(aspect_ratio).maybe_clamp(min_size, max_size)
} else {
Size::NONE
};
// If both min and max in a given axis are set and max <= min then this determines the size in that axis
let min_max_definite_size = min_size.zip_map(max_size, |min, max| match (min, max) {
(Some(min), Some(max)) if max <= min => Some(min),
_ => None,
});
let styled_based_known_dimensions = known_dimensions.or(min_max_definite_size).or(clamped_style_size);
// Short-circuit layout if the container's size is fully determined by the container's size and the run mode
// is ComputeSize (and thus the container's size is all that we're interested in)
if run_mode == RunMode::ComputeSize {
if let Size { width: Some(width), height: Some(height) } = styled_based_known_dimensions {
return LayoutOutput::from_outer_size(Size { width, height });
}
}
debug_log!("FLEX: single-pass");
compute_preliminary(tree, node, LayoutInput { known_dimensions: styled_based_known_dimensions, ..inputs })
}
/// Compute a preliminary size for an item
fn compute_preliminary(tree: &mut impl PartialLayoutTree, node: NodeId, inputs: LayoutInput) -> LayoutOutput {
let LayoutInput { known_dimensions, parent_size, available_space, run_mode, .. } = inputs;
// Define some general constants we will need for the remainder of the algorithm.
let mut constants = compute_constants(tree.get_style(node), known_dimensions, parent_size);
// 9. Flex Layout Algorithm
// 9.1. Initial Setup
// 1. Generate anonymous flex items as described in §4 Flex Items.
debug_log!("generate_anonymous_flex_items");
let mut flex_items = generate_anonymous_flex_items(tree, node, &constants);
// 9.2. Line Length Determination
// 2. Determine the available main and cross space for the flex items
debug_log!("determine_available_space");
let available_space = determine_available_space(known_dimensions, available_space, &constants);
// 3. Determine the flex base size and hypothetical main size of each item.
debug_log!("determine_flex_base_size");
determine_flex_base_size(tree, &constants, available_space, &mut flex_items);
#[cfg(feature = "debug")]
for item in flex_items.iter() {
debug_log!("item.flex_basis", item.flex_basis);
debug_log!("item.inner_flex_basis", item.inner_flex_basis);
debug_log!("item.hypothetical_outer_size", dbg:item.hypothetical_outer_size);
debug_log!("item.hypothetical_inner_size", dbg:item.hypothetical_inner_size);
debug_log!("item.resolved_minimum_main_size", dbg:item.resolved_minimum_main_size);
}
// 4. Determine the main size of the flex container
// This has already been done as part of compute_constants. The inner size is exposed as constants.node_inner_size.
// 9.3. Main Size Determination
// 5. Collect flex items into flex lines.
debug_log!("collect_flex_lines");
let mut flex_lines = collect_flex_lines(&constants, available_space, &mut flex_items);
// If container size is undefined, determine the container's main size
// and then re-resolve gaps based on newly determined size
debug_log!("determine_container_main_size");
let original_gap = constants.gap;
if let Some(inner_main_size) = constants.node_inner_size.main(constants.dir) {
let outer_main_size = inner_main_size + constants.content_box_inset.main_axis_sum(constants.dir);
constants.inner_container_size.set_main(constants.dir, inner_main_size);
constants.container_size.set_main(constants.dir, outer_main_size);
} else {
// Sets constants.container_size and constants.outer_container_size
determine_container_main_size(tree, available_space, &mut flex_lines, &mut constants);
constants.node_inner_size.set_main(constants.dir, Some(constants.inner_container_size.main(constants.dir)));
constants.node_outer_size.set_main(constants.dir, Some(constants.container_size.main(constants.dir)));
debug_log!("constants.node_outer_size", dbg:constants.node_outer_size);
debug_log!("constants.node_inner_size", dbg:constants.node_inner_size);
// Re-resolve percentage gaps
let style = tree.get_style(node);
let inner_container_size = constants.inner_container_size.main(constants.dir);
let new_gap = style.gap.main(constants.dir).maybe_resolve(inner_container_size).unwrap_or(0.0);
constants.gap.set_main(constants.dir, new_gap);
}
// 6. Resolve the flexible lengths of all the flex items to find their used main size.
debug_log!("resolve_flexible_lengths");
for line in &mut flex_lines {
resolve_flexible_lengths(line, &constants, original_gap);
}
// 9.4. Cross Size Determination
// 7. Determine the hypothetical cross size of each item.
debug_log!("determine_hypothetical_cross_size");
for line in &mut flex_lines {
determine_hypothetical_cross_size(tree, line, &constants, available_space);
}
// Calculate child baselines. This function is internally smart and only computes child baselines
// if they are necessary.
debug_log!("calculate_children_base_lines");
calculate_children_base_lines(tree, known_dimensions, available_space, &mut flex_lines, &constants);
// 8. Calculate the cross size of each flex line.
debug_log!("calculate_cross_size");
calculate_cross_size(&mut flex_lines, known_dimensions, &constants);
// 9. Handle 'align-content: stretch'.
debug_log!("handle_align_content_stretch");
handle_align_content_stretch(&mut flex_lines, known_dimensions, &constants);
// 10. Collapse visibility:collapse items. If any flex items have visibility: collapse,
// note the cross size of the line they’re in as the item’s strut size, and restart
// layout from the beginning.
//
// In this second layout round, when collecting items into lines, treat the collapsed
// items as having zero main size. For the rest of the algorithm following that step,
// ignore the collapsed items entirely (as if they were display:none) except that after
// calculating the cross size of the lines, if any line’s cross size is less than the
// largest strut size among all the collapsed items in the line, set its cross size to
// that strut size.
//
// Skip this step in the second layout round.
// TODO implement once (if ever) we support visibility:collapse
// 11. Determine the used cross size of each flex item.
debug_log!("determine_used_cross_size");
determine_used_cross_size(tree, &mut flex_lines, &constants);
// 9.5. Main-Axis Alignment
// 12. Distribute any remaining free space.
debug_log!("distribute_remaining_free_space");
distribute_remaining_free_space(&mut flex_lines, &constants);
// 9.6. Cross-Axis Alignment
// 13. Resolve cross-axis auto margins (also includes 14).
debug_log!("resolve_cross_axis_auto_margins");
resolve_cross_axis_auto_margins(&mut flex_lines, &constants);
// 15. Determine the flex container’s used cross size.
debug_log!("determine_container_cross_size");
let total_line_cross_size = determine_container_cross_size(&flex_lines, known_dimensions, &mut constants);
// We have the container size.
// If our caller does not care about performing layout we are done now.
if run_mode == RunMode::ComputeSize {
return LayoutOutput::from_outer_size(constants.container_size);
}
// 16. Align all flex lines per align-content.
debug_log!("align_flex_lines_per_align_content");
align_flex_lines_per_align_content(&mut flex_lines, &constants, total_line_cross_size);
// Do a final layout pass and gather the resulting layouts
debug_log!("final_layout_pass");
let inflow_content_size = final_layout_pass(tree, &mut flex_lines, &constants);
// Before returning we perform absolute layout on all absolutely positioned children
debug_log!("perform_absolute_layout_on_absolute_children");
let absolute_content_size = perform_absolute_layout_on_absolute_children(tree, node, &constants);
debug_log!("hidden_layout");
let len = tree.child_count(node);
for order in 0..len {
let child = tree.get_child_id(node, order);
if tree.get_style(child).display == Display::None {
tree.set_unrounded_layout(child, &Layout::with_order(order as u32));
tree.perform_child_layout(
child,
Size::NONE,
Size::NONE,
Size::MAX_CONTENT,
SizingMode::InherentSize,
Line::FALSE,
);
}
}
// 8.5. Flex Container Baselines: calculate the flex container's first baseline
// See https://www.w3.org/TR/css-flexbox-1/#flex-baselines
let first_vertical_baseline = if flex_lines.is_empty() {
None
} else {
flex_lines[0]
.items
.iter()
.find(|item| constants.is_column || item.align_self == AlignSelf::Baseline)
.or_else(|| flex_lines[0].items.iter().next())
.map(|child| {
let offset_vertical = if constants.is_row { child.offset_cross } else { child.offset_main };
offset_vertical + child.baseline
})
};
LayoutOutput::from_sizes_and_baselines(
constants.container_size,
inflow_content_size.f32_max(absolute_content_size),
Point { x: None, y: first_vertical_baseline },
)
}
/// Compute constants that can be reused during the flexbox algorithm.
#[inline]
fn compute_constants(
style: &Style,
known_dimensions: Size<Option<f32>>,
parent_size: Size<Option<f32>>,
) -> AlgoConstants {
let dir = style.flex_direction;
let is_row = dir.is_row();
let is_column = dir.is_column();
let is_wrap = matches!(style.flex_wrap, FlexWrap::Wrap | FlexWrap::WrapReverse);
let is_wrap_reverse = style.flex_wrap == FlexWrap::WrapReverse;
let aspect_ratio = style.aspect_ratio;
let margin = style.margin.resolve_or_zero(parent_size.width);
let padding = style.padding.resolve_or_zero(parent_size.width);
let border = style.border.resolve_or_zero(parent_size.width);
let align_items = style.align_items.unwrap_or(AlignItems::Stretch);
let align_content = style.align_content.unwrap_or(AlignContent::Stretch);
let justify_content = style.justify_content;
// Scrollbar gutters are reserved when the `overflow` property is set to `Overflow::Scroll`.
// However, the axis are switched (transposed) because a node that scrolls vertically needs
// *horizontal* space to be reserved for a scrollbar
let scrollbar_gutter = style.overflow.transpose().map(|overflow| match overflow {
Overflow::Scroll => style.scrollbar_width,
_ => 0.0,
});
// TODO: make side configurable based on the `direction` property
let mut content_box_inset = padding + border;
content_box_inset.right += scrollbar_gutter.x;
content_box_inset.bottom += scrollbar_gutter.y;
let node_outer_size = known_dimensions;
let node_inner_size = node_outer_size.maybe_sub(content_box_inset.sum_axes());
let gap = style.gap.resolve_or_zero(node_inner_size.or(Size::zero()));
let container_size = Size::zero();
let inner_container_size = Size::zero();
AlgoConstants {
dir,
is_row,
is_column,
is_wrap,
is_wrap_reverse,
min_size: style.min_size.maybe_resolve(parent_size).maybe_apply_aspect_ratio(aspect_ratio),
max_size: style.max_size.maybe_resolve(parent_size).maybe_apply_aspect_ratio(aspect_ratio),
margin,
border,
gap,
content_box_inset,
scrollbar_gutter,
align_items,
align_content,
justify_content,
node_outer_size,
node_inner_size,
container_size,
inner_container_size,
}
}
/// Generate anonymous flex items.
///
/// # [9.1. Initial Setup](https://www.w3.org/TR/css-flexbox-1/#box-manip)
///
/// - [**Generate anonymous flex items**](https://www.w3.org/TR/css-flexbox-1/#algo-anon-box) as described in [§4 Flex Items](https://www.w3.org/TR/css-flexbox-1/#flex-items).
#[inline]
fn generate_anonymous_flex_items(
tree: &impl PartialLayoutTree,
node: NodeId,
constants: &AlgoConstants,
) -> Vec<FlexItem> {
tree.child_ids(node)
.enumerate()
.map(|(index, child)| (index, child, tree.get_style(child)))
.filter(|(_, _, style)| style.position != Position::Absolute)
.filter(|(_, _, style)| style.display != Display::None)
.map(|(index, child, child_style)| {
let aspect_ratio = child_style.aspect_ratio;
FlexItem {
node: child,
order: index as u32,
size: child_style.size.maybe_resolve(constants.node_inner_size).maybe_apply_aspect_ratio(aspect_ratio),
min_size: child_style
.min_size
.maybe_resolve(constants.node_inner_size)
.maybe_apply_aspect_ratio(aspect_ratio),
max_size: child_style
.max_size
.maybe_resolve(constants.node_inner_size)
.maybe_apply_aspect_ratio(aspect_ratio),
inset: child_style.inset.zip_size(constants.node_inner_size, |p, s| p.maybe_resolve(s)),
margin: child_style.margin.resolve_or_zero(constants.node_inner_size.width),
margin_is_auto: child_style.margin.map(|m| m == LengthPercentageAuto::Auto),
padding: child_style.padding.resolve_or_zero(constants.node_inner_size.width),
border: child_style.border.resolve_or_zero(constants.node_inner_size.width),
align_self: child_style.align_self.unwrap_or(constants.align_items),
overflow: child_style.overflow,
scrollbar_width: child_style.scrollbar_width,
flex_grow: child_style.flex_grow,
flex_shrink: child_style.flex_shrink,
flex_basis: 0.0,
inner_flex_basis: 0.0,
violation: 0.0,
frozen: false,
resolved_minimum_main_size: 0.0,
hypothetical_inner_size: Size::zero(),
hypothetical_outer_size: Size::zero(),
target_size: Size::zero(),
outer_target_size: Size::zero(),
content_flex_fraction: 0.0,
baseline: 0.0,
offset_main: 0.0,
offset_cross: 0.0,
}
})
.collect()
}
/// Determine the available main and cross space for the flex items.
///
/// # [9.2. Line Length Determination](https://www.w3.org/TR/css-flexbox-1/#line-sizing)
///
/// - [**Determine the available main and cross space for the flex items**](https://www.w3.org/TR/css-flexbox-1/#algo-available).
/// For each dimension, if that dimension of the flex container’s content box is a definite size, use that;
/// if that dimension of the flex container is being sized under a min or max-content constraint, the available space in that dimension is that constraint;
/// otherwise, subtract the flex container’s margin, border, and padding from the space available to the flex container in that dimension and use that value.
/// **This might result in an infinite value**.
#[inline]
#[must_use]
fn determine_available_space(
known_dimensions: Size<Option<f32>>,
outer_available_space: Size<AvailableSpace>,
constants: &AlgoConstants,
) -> Size<AvailableSpace> {
// Note: min/max/preferred size styles have already been applied to known_dimensions in the `compute` function above
let width = match known_dimensions.width {
Some(node_width) => AvailableSpace::Definite(node_width - constants.content_box_inset.horizontal_axis_sum()),
None => outer_available_space
.width
.maybe_sub(constants.margin.horizontal_axis_sum())
.maybe_sub(constants.content_box_inset.horizontal_axis_sum()),
};
let height = match known_dimensions.height {
Some(node_height) => AvailableSpace::Definite(node_height - constants.content_box_inset.vertical_axis_sum()),
None => outer_available_space
.height
.maybe_sub(constants.margin.vertical_axis_sum())
.maybe_sub(constants.content_box_inset.vertical_axis_sum()),
};
Size { width, height }
}
/// Determine the flex base size and hypothetical main size of each item.
///
/// # [9.2. Line Length Determination](https://www.w3.org/TR/css-flexbox-1/#line-sizing)
///
/// - [**Determine the flex base size and hypothetical main size of each item:**](https://www.w3.org/TR/css-flexbox-1/#algo-main-item)
///
/// - A. If the item has a definite used flex basis, that’s the flex base size.
///
/// - B. If the flex item has ...
///
/// - an intrinsic aspect ratio,
/// - a used flex basis of content, and
/// - a definite cross size,
///
/// then the flex base size is calculated from its inner cross size and the flex item’s intrinsic aspect ratio.
///
/// - C. If the used flex basis is content or depends on its available space, and the flex container is being sized under a min-content
/// or max-content constraint (e.g. when performing automatic table layout \[CSS21\]), size the item under that constraint.
/// The flex base size is the item’s resulting main size.
///
/// - E. Otherwise, size the item into the available space using its used flex basis in place of its main size, treating a value of content as max-content.
/// If a cross size is needed to determine the main size (e.g. when the flex item’s main size is in its block axis) and the flex item’s cross size is auto and not definite,
/// in this calculation use fit-content as the flex item’s cross size. The flex base size is the item’s resulting main size.
///
/// When determining the flex base size, the item’s min and max main sizes are ignored (no clamping occurs).
/// Furthermore, the sizing calculations that floor the content box size at zero when applying box-sizing are also ignored.
/// (For example, an item with a specified size of zero, positive padding, and box-sizing: border-box will have an outer flex base size of zero—and hence a negative inner flex base size.)
#[inline]
fn determine_flex_base_size(
tree: &mut impl PartialLayoutTree,
constants: &AlgoConstants,
available_space: Size<AvailableSpace>,
flex_items: &mut [FlexItem],
) {
let dir = constants.dir;
for child in flex_items.iter_mut() {
let child_style = tree.get_style(child.node);
// Parent size for child sizing
let cross_axis_parent_size = constants.node_inner_size.cross(dir);
let child_parent_size = Size::NONE.with_cross(dir, cross_axis_parent_size);
// Available space for child sizing
let cross_axis_margin_sum = constants.margin.cross_axis_sum(dir);
let child_min_cross = child.min_size.cross(dir).maybe_add(cross_axis_margin_sum);
let child_max_cross = child.max_size.cross(dir).maybe_add(cross_axis_margin_sum);
let cross_axis_available_space: AvailableSpace = available_space
.cross(dir)
.map_definite_value(|val| cross_axis_parent_size.unwrap_or(val))
.maybe_clamp(child_min_cross, child_max_cross);
// Known dimensions for child sizing
let child_known_dimensions = {
let mut ckd = child.size.with_main(dir, None);
if child.align_self == AlignSelf::Stretch && ckd.cross(dir).is_none() {
ckd.set_cross(
dir,
cross_axis_available_space.into_option().maybe_sub(child.margin.cross_axis_sum(dir)),
);
}
ckd
};
child.flex_basis = 'flex_basis: {
// A. If the item has a definite used flex basis, that’s the flex base size.
// B. If the flex item has an intrinsic aspect ratio,
// a used flex basis of content, and a definite cross size,
// then the flex base size is calculated from its inner
// cross size and the flex item’s intrinsic aspect ratio.
// Note: `child.size` has already been resolved against aspect_ratio in generate_anonymous_flex_items
// So B will just work here by using main_size without special handling for aspect_ratio
let flex_basis = child_style.flex_basis.maybe_resolve(constants.node_inner_size.main(dir));
let main_size = child.size.main(dir);
if let Some(flex_basis) = flex_basis.or(main_size) {
break 'flex_basis flex_basis;
};
// C. If the used flex basis is content or depends on its available space,
// and the flex container is being sized under a min-content or max-content
// constraint (e.g. when performing automatic table layout [CSS21]),
// size the item under that constraint. The flex base size is the item’s
// resulting main size.
// This is covered by the implementation of E below, which passes the available_space constraint
// through to the child size computation. It may need a separate implementation if/when D is implemented.
// D. Otherwise, if the used flex basis is content or depends on its
// available space, the available main size is infinite, and the flex item’s
// inline axis is parallel to the main axis, lay the item out using the rules
// for a box in an orthogonal flow [CSS3-WRITING-MODES]. The flex base size
// is the item’s max-content main size.
// TODO if/when vertical writing modes are supported
// E. Otherwise, size the item into the available space using its used flex basis
// in place of its main size, treating a value of content as max-content.
// If a cross size is needed to determine the main size (e.g. when the
// flex item’s main size is in its block axis) and the flex item’s cross size
// is auto and not definite, in this calculation use fit-content as the
// flex item’s cross size. The flex base size is the item’s resulting main size.
let child_available_space = Size::MAX_CONTENT
.with_main(
dir,
// Map AvailableSpace::Definite to AvailableSpace::MaxContent
if available_space.main(dir) == AvailableSpace::MinContent {
AvailableSpace::MinContent
} else {
AvailableSpace::MaxContent
},
)
.with_cross(dir, cross_axis_available_space);
break 'flex_basis tree.measure_child_size(
child.node,
child_known_dimensions,
child_parent_size,
child_available_space,
SizingMode::ContentSize,
dir.main_axis(),
Line::FALSE,
);
};
// Floor flex-basis by the padding_border_sum (floors inner_flex_basis at zero)
// This seems to be in violation of the spec which explicitly states that the content box should not be floored at zero
// (like it usually is) when calculating the flex-basis. But including this matches both Chrome and Firefox's behaviour.
//
// TODO: resolve spec violation
// Spec: https://www.w3.org/TR/css-flexbox-1/#intrinsic-item-contributions
// Spec: https://www.w3.org/TR/css-flexbox-1/#change-2016-max-contribution
let padding_border_sum = child.padding.main_axis_sum(constants.dir) + child.border.main_axis_sum(constants.dir);
child.flex_basis = child.flex_basis.max(padding_border_sum);
// The hypothetical main size is the item’s flex base size clamped according to its
// used min and max main sizes (and flooring the content box size at zero).
child.inner_flex_basis =
child.flex_basis - child.padding.main_axis_sum(constants.dir) - child.border.main_axis_sum(constants.dir);
let padding_border_axes_sums = (child.padding + child.border).sum_axes().map(Some);
let hypothetical_inner_min_main =
child.min_size.main(constants.dir).maybe_max(padding_border_axes_sums.main(constants.dir));
let hypothetical_inner_size =
child.flex_basis.maybe_clamp(hypothetical_inner_min_main, child.max_size.main(constants.dir));
let hypothetical_outer_size = hypothetical_inner_size + child.margin.main_axis_sum(constants.dir);
child.hypothetical_inner_size.set_main(constants.dir, hypothetical_inner_size);
child.hypothetical_outer_size.set_main(constants.dir, hypothetical_outer_size);
// Note that it is important that the `parent_size` parameter in the main axis is not set for this
// function call as it used for resolving percentages, and percentage size in an axis should not contribute
// to a min-content contribution in that same axis. However the `parent_size` and `available_space` *should*
// be set to their usual values in the cross axis so that wrapping content can wrap correctly.
//
// See https://drafts.csswg.org/css-sizing-3/#min-percentage-contribution
let style_min_main_size =
child.min_size.or(child.overflow.map(Overflow::maybe_into_automatic_min_size).into()).main(dir);
child.resolved_minimum_main_size = style_min_main_size.unwrap_or({
let min_content_main_size = {
let child_available_space = Size::MIN_CONTENT.with_cross(dir, cross_axis_available_space);
tree.measure_child_size(
child.node,
child_known_dimensions,
child_parent_size,
child_available_space,
SizingMode::ContentSize,
dir.main_axis(),
Line::FALSE,
)
};
// 4.5. Automatic Minimum Size of Flex Items
// https://www.w3.org/TR/css-flexbox-1/#min-size-auto
let clamped_min_content_size =
min_content_main_size.maybe_min(child.size.main(dir)).maybe_min(child.max_size.main(dir));
clamped_min_content_size.maybe_max(padding_border_axes_sums.main(dir))
});
}
}
/// Collect flex items into flex lines.
///
/// # [9.3. Main Size Determination](https://www.w3.org/TR/css-flexbox-1/#main-sizing)
///
/// - [**Collect flex items into flex lines**](https://www.w3.org/TR/css-flexbox-1/#algo-line-break):
///
/// - If the flex container is single-line, collect all the flex items into a single flex line.
///
/// - Otherwise, starting from the first uncollected item, collect consecutive items one by one until the first time that the next collected item would not fit into the flex container’s inner main size
/// (or until a forced break is encountered, see [§10 Fragmenting Flex Layout](https://www.w3.org/TR/css-flexbox-1/#pagination)).
/// If the very first uncollected item wouldn't fit, collect just it into the line.
///
/// For this step, the size of a flex item is its outer hypothetical main size. (**Note: This can be negative**.)
///
/// Repeat until all flex items have been collected into flex lines.
///
/// **Note that the "collect as many" line will collect zero-sized flex items onto the end of the previous line even if the last non-zero item exactly "filled up" the line**.
#[inline]
fn collect_flex_lines<'a>(
constants: &AlgoConstants,
available_space: Size<AvailableSpace>,
flex_items: &'a mut Vec<FlexItem>,
) -> Vec<FlexLine<'a>> {
if !constants.is_wrap {
let mut lines = new_vec_with_capacity(1);
lines.push(FlexLine { items: flex_items.as_mut_slice(), cross_size: 0.0, offset_cross: 0.0 });
lines
} else {
match available_space.main(constants.dir) {
// If we're sizing under a max-content constraint then the flex items will never wrap
// (at least for now - future extensions to the CSS spec may add provisions for forced wrap points)
AvailableSpace::MaxContent => {
let mut lines = new_vec_with_capacity(1);
lines.push(FlexLine { items: flex_items.as_mut_slice(), cross_size: 0.0, offset_cross: 0.0 });
lines
}
// If flex-wrap is Wrap and we're sizing under a min-content constraint, then we take every possible wrapping opportunity
// and place each item in it's own line
AvailableSpace::MinContent => {
let mut lines = new_vec_with_capacity(flex_items.len());
let mut items = &mut flex_items[..];
while !items.is_empty() {
let (line_items, rest) = items.split_at_mut(1);
lines.push(FlexLine { items: line_items, cross_size: 0.0, offset_cross: 0.0 });
items = rest;
}
lines
}
AvailableSpace::Definite(main_axis_available_space) => {
let mut lines = new_vec_with_capacity(1);
let mut flex_items = &mut flex_items[..];
let main_axis_gap = constants.gap.main(constants.dir);
while !flex_items.is_empty() {
// Find index of the first item in the next line
// (or the last item if all remaining items are in the current line)
let mut line_length = 0.0;
let index = flex_items
.iter()
.enumerate()
.find(|&(idx, child)| {
// Gaps only occur between items (not before the first one or after the last one)
// So first item in the line does not contribute a gap to the line length
let gap_contribution = if idx == 0 { 0.0 } else { main_axis_gap };
line_length += child.hypothetical_outer_size.main(constants.dir) + gap_contribution;
line_length > main_axis_available_space && idx != 0
})
.map(|(idx, _)| idx)
.unwrap_or(flex_items.len());
let (items, rest) = flex_items.split_at_mut(index);
lines.push(FlexLine { items, cross_size: 0.0, offset_cross: 0.0 });
flex_items = rest;
}
lines
}
}
}
}
/// Determine the container's main size (if not already known)
fn determine_container_main_size(
tree: &mut impl PartialLayoutTree,
available_space: Size<AvailableSpace>,
lines: &mut Vec<FlexLine<'_>>,
constants: &mut AlgoConstants,
) {
let dir = constants.dir;
let main_content_box_inset = constants.content_box_inset.main_axis_sum(constants.dir);
let outer_main_size: f32 = constants.node_outer_size.main(constants.dir).unwrap_or_else(|| {
match available_space.main(dir) {
AvailableSpace::Definite(main_axis_available_space) => {
let longest_line_length: f32 = lines
.iter()
.map(|line| {
let line_main_axis_gap = sum_axis_gaps(constants.gap.main(constants.dir), line.items.len());
let total_target_size = line
.items
.iter()
.map(|child| {
let padding_border_sum = (child.padding + child.border).main_axis_sum(constants.dir);
(child.flex_basis + child.margin.main_axis_sum(constants.dir)).max(padding_border_sum)
})
.sum::<f32>();
total_target_size + line_main_axis_gap
})
.max_by(|a, b| a.total_cmp(b))
.unwrap_or(0.0);
let size = longest_line_length + main_content_box_inset;
if lines.len() > 1 {
f32_max(size, main_axis_available_space)
} else {
size
}
}
AvailableSpace::MinContent if constants.is_wrap => {
let longest_line_length: f32 = lines
.iter()
.map(|line| {
let line_main_axis_gap = sum_axis_gaps(constants.gap.main(constants.dir), line.items.len());
let total_target_size = line
.items
.iter()
.map(|child| {
let padding_border_sum = (child.padding + child.border).main_axis_sum(constants.dir);
(child.flex_basis + child.margin.main_axis_sum(constants.dir)).max(padding_border_sum)
})
.sum::<f32>();
total_target_size + line_main_axis_gap
})
.max_by(|a, b| a.total_cmp(b))
.unwrap_or(0.0);
longest_line_length + main_content_box_inset
}
AvailableSpace::MinContent | AvailableSpace::MaxContent => {
// Define a base main_size variable. This is mutated once for iteration over the outer
// loop over the flex lines as:
// "The flex container’s max-content size is the largest sum of the afore-calculated sizes of all items within a single line."
let mut main_size = 0.0;
for line in lines.iter_mut() {
for item in line.items.iter_mut() {
let style_min = item.min_size.main(constants.dir);
let style_preferred = item.size.main(constants.dir);
let style_max = item.max_size.main(constants.dir);
// The spec seems a bit unclear on this point (my initial reading was that the `.maybe_max(style_preferred)` should
// not be included here), however this matches both Chrome and Firefox as of 9th March 2023.
//
// Spec: https://www.w3.org/TR/css-flexbox-1/#intrinsic-item-contributions
// Spec modifcation: https://www.w3.org/TR/css-flexbox-1/#change-2016-max-contribution
// Issue: https://github.com/w3c/csswg-drafts/issues/1435
// Gentest: padding_border_overrides_size_flex_basis_0.html
let clamping_basis = Some(item.flex_basis).maybe_max(style_preferred);
let flex_basis_min = clamping_basis.filter(|_| item.flex_shrink == 0.0);
let flex_basis_max = clamping_basis.filter(|_| item.flex_grow == 0.0);
let min_main_size = style_min
.maybe_max(flex_basis_min)
.or(flex_basis_min)
.unwrap_or(item.resolved_minimum_main_size)
.max(item.resolved_minimum_main_size);
let max_main_size =
style_max.maybe_min(flex_basis_max).or(flex_basis_max).unwrap_or(f32::INFINITY);
let content_contribution = match (min_main_size, style_preferred, max_main_size) {
// If the clamping values are such that max <= min, then we can avoid the expensive step of computing the content size
// as we know that the clamping values will override it anyway
(min, Some(pref), max) if max <= min || max <= pref => {
pref.min(max).max(min) + item.margin.main_axis_sum(constants.dir)
}
(min, _, max) if max <= min => min + item.margin.main_axis_sum(constants.dir),
// Else compute the min- or -max content size and apply the full formula for computing the
// min- or max- content contributuon
_ => {
// Parent size for child sizing
let cross_axis_parent_size = constants.node_inner_size.cross(dir);
// Available space for child sizing
let cross_axis_margin_sum = constants.margin.cross_axis_sum(dir);
let child_min_cross = item.min_size.cross(dir).maybe_add(cross_axis_margin_sum);
let child_max_cross = item.max_size.cross(dir).maybe_add(cross_axis_margin_sum);
let cross_axis_available_space: AvailableSpace = available_space
.cross(dir)
.map_definite_value(|val| cross_axis_parent_size.unwrap_or(val))
.maybe_clamp(child_min_cross, child_max_cross);
let child_available_space = available_space.with_cross(dir, cross_axis_available_space);
// Either the min- or max- content size depending on which constraint we are sizing under.
// TODO: Optimise by using already computed values where available
let content_main_size = tree.measure_child_size(
item.node,
Size::NONE,
constants.node_inner_size,
child_available_space,
SizingMode::InherentSize,
dir.main_axis(),
Line::FALSE,
) + item.margin.main_axis_sum(constants.dir);
// This is somewhat bizarre in that it's asymetrical depending whether the flex container is a column or a row.
//
// I *think* this might relate to https://drafts.csswg.org/css-flexbox-1/#algo-main-container:
//
// "The automatic block size of a block-level flex container is its max-content size."
//
// Which could suggest that flex-basis defining a vertical size does not shrink because it is in the block axis, and the automatic size
// in the block axis is a MAX content size. Whereas a flex-basis defining a horizontal size does shrink because the automatic size in
// inline axis is MIN content size (although I don't have a reference for that).
//
// Ultimately, this was not found by reading the spec, but by trial and error fixing tests to align with Webkit/Firefox output.
// (see the `flex_basis_unconstraint_row` and `flex_basis_uncontraint_column` generated tests which demonstrate this)
if constants.is_row {
content_main_size.maybe_clamp(style_min, style_max).max(main_content_box_inset)
} else {
content_main_size
.max(item.flex_basis)
.maybe_clamp(style_min, style_max)
.max(main_content_box_inset)
}
}
};
item.content_flex_fraction = {
let diff = content_contribution - item.flex_basis;
if diff > 0.0 {
diff / f32_max(1.0, item.flex_grow)
} else if diff < 0.0 {
let scaled_shrink_factor = f32_max(1.0, item.flex_shrink * item.inner_flex_basis);
diff / scaled_shrink_factor
} else {
// We are assuming that diff is 0.0 here and that we haven't accidentally introduced a NaN
0.0
}
};
}
// TODO Spec says to scale everything by the line's max flex fraction. But neither Chrome nor firefox implement this
// so we don't either. But if we did want to, we'd need this computation here (and to use it below):
//
// Within each line, find the largest max-content flex fraction among all the flex items.
// let line_flex_fraction = line
// .items
// .iter()
// .map(|item| item.content_flex_fraction)
// .max_by(|a, b| a.total_cmp(b))
// .unwrap_or(0.0); // Unwrap case never gets hit because there is always at least one item a line
// Add each item’s flex base size to the product of:
// - its flex grow factor (or scaled flex shrink factor,if the chosen max-content flex fraction was negative)
// - the chosen max-content flex fraction
// then clamp that result by the max main size floored by the min main size.
//
// The flex container’s max-content size is the largest sum of the afore-calculated sizes of all items within a single line.
let item_main_size_sum = line
.items
.iter_mut()
.map(|item| {
let flex_fraction = item.content_flex_fraction;
// let flex_fraction = line_flex_fraction;
let flex_contribution = if item.content_flex_fraction > 0.0 {
f32_max(1.0, item.flex_grow) * flex_fraction
} else if item.content_flex_fraction < 0.0 {
let scaled_shrink_factor = f32_max(1.0, item.flex_shrink) * item.inner_flex_basis;
scaled_shrink_factor * flex_fraction
} else {
0.0
};
let size = item.flex_basis + flex_contribution;
item.outer_target_size.set_main(constants.dir, size);
item.target_size.set_main(constants.dir, size);
size
})
.sum::<f32>();
let gap_sum = sum_axis_gaps(constants.gap.main(constants.dir), line.items.len());
main_size = f32_max(main_size, item_main_size_sum + gap_sum)
}
main_size + main_content_box_inset
}
}
});
let outer_main_size = outer_main_size
.maybe_clamp(constants.min_size.main(constants.dir), constants.max_size.main(constants.dir))
.max(main_content_box_inset - constants.scrollbar_gutter.main(constants.dir));
// let outer_main_size = inner_main_size + constants.padding_border.main_axis_sum(constants.dir);
let inner_main_size = f32_max(outer_main_size - main_content_box_inset, 0.0);
constants.container_size.set_main(constants.dir, outer_main_size);
constants.inner_container_size.set_main(constants.dir, inner_main_size);
constants.node_inner_size.set_main(constants.dir, Some(inner_main_size));
}
/// Resolve the flexible lengths of the items within a flex line.
/// Sets the `main` component of each item's `target_size` and `outer_target_size`
///
/// # [9.7. Resolving Flexible Lengths](https://www.w3.org/TR/css-flexbox-1/#resolve-flexible-lengths)
#[inline]
fn resolve_flexible_lengths(line: &mut FlexLine, constants: &AlgoConstants, original_gap: Size<f32>) {
let total_original_main_axis_gap = sum_axis_gaps(original_gap.main(constants.dir), line.items.len());
let total_main_axis_gap = sum_axis_gaps(constants.gap.main(constants.dir), line.items.len());
// 1. Determine the used flex factor. Sum the outer hypothetical main sizes of all
// items on the line. If the sum is less than the flex container’s inner main size,
// use the flex grow factor for the rest of this algorithm; otherwise, use the
// flex shrink factor.
let total_hypothetical_outer_main_size =
line.items.iter().map(|child| child.hypothetical_outer_size.main(constants.dir)).sum::<f32>();
let used_flex_factor: f32 = total_original_main_axis_gap + total_hypothetical_outer_main_size;
let growing = used_flex_factor < constants.node_inner_size.main(constants.dir).unwrap_or(0.0);
let shrinking = !growing;
// 2. Size inflexible items. Freeze, setting its target main size to its hypothetical main size
// - Any item that has a flex factor of zero
// - If using the flex grow factor: any item that has a flex base size
// greater than its hypothetical main size
// - If using the flex shrink factor: any item that has a flex base size
// smaller than its hypothetical main size
for child in line.items.iter_mut() {
let inner_target_size = child.hypothetical_inner_size.main(constants.dir);
child.target_size.set_main(constants.dir, inner_target_size);
if (child.flex_grow == 0.0 && child.flex_shrink == 0.0)
|| (growing && child.flex_basis > child.hypothetical_inner_size.main(constants.dir))
|| (shrinking && child.flex_basis < child.hypothetical_inner_size.main(constants.dir))
{
child.frozen = true;
let outer_target_size = inner_target_size + child.margin.main_axis_sum(constants.dir);
child.outer_target_size.set_main(constants.dir, outer_target_size);
}
}
// 3. Calculate initial free space. Sum the outer sizes of all items on the line,
// and subtract this from the flex container’s inner main size. For frozen items,
// use their outer target main size; for other items, use their outer flex base size.
let used_space: f32 = total_main_axis_gap
+ line
.items
.iter()
.map(|child| {
child.margin.main_axis_sum(constants.dir)
+ if child.frozen { child.outer_target_size.main(constants.dir) } else { child.flex_basis }
})
.sum::<f32>();
let initial_free_space = constants.node_inner_size.main(constants.dir).maybe_sub(used_space).unwrap_or(0.0);
// 4. Loop
loop {
// a. Check for flexible items. If all the flex items on the line are frozen,
// free space has been distributed; exit this loop.
if line.items.iter().all(|child| child.frozen) {
break;
}
// b. Calculate the remaining free space as for initial free space, above.
// If the sum of the unfrozen flex items’ flex factors is less than one,
// multiply the initial free space by this sum. If the magnitude of this
// value is less than the magnitude of the remaining free space, use this
// as the remaining free space.
let used_space: f32 = total_main_axis_gap
+ line
.items
.iter()
.map(|child| {
child.margin.main_axis_sum(constants.dir)
+ if child.frozen { child.outer_target_size.main(constants.dir) } else { child.flex_basis }
})
.sum::<f32>();
let mut unfrozen: Vec<&mut FlexItem> = line.items.iter_mut().filter(|child| !child.frozen).collect();
let (sum_flex_grow, sum_flex_shrink): (f32, f32) =
unfrozen.iter().fold((0.0, 0.0), |(flex_grow, flex_shrink), item| {
(flex_grow + item.flex_grow, flex_shrink + item.flex_shrink)
});
let free_space = if growing && sum_flex_grow < 1.0 {
(initial_free_space * sum_flex_grow - total_main_axis_gap)
.maybe_min(constants.node_inner_size.main(constants.dir).maybe_sub(used_space))
} else if shrinking && sum_flex_shrink < 1.0 {
(initial_free_space * sum_flex_shrink - total_main_axis_gap)
.maybe_max(constants.node_inner_size.main(constants.dir).maybe_sub(used_space))
} else {
(constants.node_inner_size.main(constants.dir).maybe_sub(used_space))
.unwrap_or(used_flex_factor - used_space)
};
// c. Distribute free space proportional to the flex factors.
// - If the remaining free space is zero
// Do Nothing
// - If using the flex grow factor
// Find the ratio of the item’s flex grow factor to the sum of the
// flex grow factors of all unfrozen items on the line. Set the item’s
// target main size to its flex base size plus a fraction of the remaining
// free space proportional to the ratio.
// - If using the flex shrink factor
// For every unfrozen item on the line, multiply its flex shrink factor by
// its inner flex base size, and note this as its scaled flex shrink factor.
// Find the ratio of the item’s scaled flex shrink factor to the sum of the
// scaled flex shrink factors of all unfrozen items on the line. Set the item’s
// target main size to its flex base size minus a fraction of the absolute value
// of the remaining free space proportional to the ratio. Note this may result
// in a negative inner main size; it will be corrected in the next step.
// - Otherwise
// Do Nothing
if free_space.is_normal() {
if growing && sum_flex_grow > 0.0 {
for child in &mut unfrozen {
child
.target_size
.set_main(constants.dir, child.flex_basis + free_space * (child.flex_grow / sum_flex_grow));
}
} else if shrinking && sum_flex_shrink > 0.0 {
let sum_scaled_shrink_factor: f32 =
unfrozen.iter().map(|child| child.inner_flex_basis * child.flex_shrink).sum();
if sum_scaled_shrink_factor > 0.0 {
for child in &mut unfrozen {
let scaled_shrink_factor = child.inner_flex_basis * child.flex_shrink;
child.target_size.set_main(
constants.dir,
child.flex_basis + free_space * (scaled_shrink_factor / sum_scaled_shrink_factor),
)
}
}
}
}
// d. Fix min/max violations. Clamp each non-frozen item’s target main size by its
// used min and max main sizes and floor its content-box size at zero. If the
// item’s target main size was made smaller by this, it’s a max violation.
// If the item’s target main size was made larger by this, it’s a min violation.
let total_violation = unfrozen.iter_mut().fold(0.0, |acc, child| -> f32 {
let resolved_min_main: Option<f32> = child.resolved_minimum_main_size.into();
let max_main = child.max_size.main(constants.dir);
let clamped = child.target_size.main(constants.dir).maybe_clamp(resolved_min_main, max_main).max(0.0);
child.violation = clamped - child.target_size.main(constants.dir);
child.target_size.set_main(constants.dir, clamped);
child.outer_target_size.set_main(
constants.dir,
child.target_size.main(constants.dir) + child.margin.main_axis_sum(constants.dir),
);
acc + child.violation
});
// e. Freeze over-flexed items. The total violation is the sum of the adjustments
// from the previous step ∑(clamped size - unclamped size). If the total violation is:
// - Zero
// Freeze all items.
// - Positive
// Freeze all the items with min violations.
// - Negative
// Freeze all the items with max violations.
for child in &mut unfrozen {
match total_violation {
v if v > 0.0 => child.frozen = child.violation > 0.0,
v if v < 0.0 => child.frozen = child.violation < 0.0,
_ => child.frozen = true,
}
}
// f. Return to the start of this loop.
}
}
/// Determine the hypothetical cross size of each item.
///
/// # [9.4. Cross Size Determination](https://www.w3.org/TR/css-flexbox-1/#cross-sizing)
///
/// - [**Determine the hypothetical cross size of each item**](https://www.w3.org/TR/css-flexbox-1/#algo-cross-item)
/// by performing layout with the used main size and the available space, treating auto as fit-content.
#[inline]
fn determine_hypothetical_cross_size(
tree: &mut impl PartialLayoutTree,
line: &mut FlexLine,
constants: &AlgoConstants,
available_space: Size<AvailableSpace>,
) {
for child in line.items.iter_mut() {
let padding_border_sum = (child.padding + child.border).cross_axis_sum(constants.dir);
let child_known_main = constants.container_size.main(constants.dir).into();
let child_cross = child
.size
.cross(constants.dir)
.maybe_clamp(child.min_size.cross(constants.dir), child.max_size.cross(constants.dir))
.maybe_max(padding_border_sum);
let child_available_cross = available_space
.cross(constants.dir)
.maybe_clamp(child.min_size.cross(constants.dir), child.max_size.cross(constants.dir))
.maybe_max(padding_border_sum);
let child_inner_cross = child_cross.unwrap_or_else(|| {
tree.measure_child_size(
child.node,
Size {
width: if constants.is_row { child.target_size.width.into() } else { child_cross },
height: if constants.is_row { child_cross } else { child.target_size.height.into() },
},
constants.node_inner_size,
Size {
width: if constants.is_row { child_known_main } else { child_available_cross },
height: if constants.is_row { child_available_cross } else { child_known_main },
},
SizingMode::ContentSize,
constants.dir.cross_axis(),
Line::FALSE,
)
.maybe_clamp(child.min_size.cross(constants.dir), child.max_size.cross(constants.dir))
.max(padding_border_sum)
});
let child_outer_cross = child_inner_cross + child.margin.cross_axis_sum(constants.dir);
child.hypothetical_inner_size.set_cross(constants.dir, child_inner_cross);
child.hypothetical_outer_size.set_cross(constants.dir, child_outer_cross);
}
}
/// Calculate the base lines of the children.
#[inline]
fn calculate_children_base_lines(
tree: &mut impl PartialLayoutTree,
node_size: Size<Option<f32>>,
available_space: Size<AvailableSpace>,
flex_lines: &mut [FlexLine],
constants: &AlgoConstants,
) {
// Only compute baselines for flex rows because we only support baseline alignment in the cross axis
// where that axis is also the inline axis
// TODO: this may need revisiting if/when we support vertical writing modes
if !constants.is_row {
return;
}
for line in flex_lines {
// If a flex line has one or zero items participating in baseline alignment then baseline alignment is a no-op so we skip
let line_baseline_child_count =
line.items.iter().filter(|child| child.align_self == AlignSelf::Baseline).count();
if line_baseline_child_count <= 1 {
continue;
}
for child in line.items.iter_mut() {
// Only calculate baselines for children participating in baseline alignment
if child.align_self != AlignSelf::Baseline {
continue;
}
let measured_size_and_baselines = tree.perform_child_layout(
child.node,
Size {
width: if constants.is_row {
child.target_size.width.into()
} else {
child.hypothetical_inner_size.width.into()
},
height: if constants.is_row {
child.hypothetical_inner_size.height.into()
} else {
child.target_size.height.into()
},
},
constants.node_inner_size,
Size {
width: if constants.is_row {
constants.container_size.width.into()
} else {
available_space.width.maybe_set(node_size.width)
},
height: if constants.is_row {
available_space.height.maybe_set(node_size.height)
} else {
constants.container_size.height.into()
},
},
SizingMode::ContentSize,
Line::FALSE,
);
let baseline = measured_size_and_baselines.first_baselines.y;
let height = measured_size_and_baselines.size.height;
child.baseline = baseline.unwrap_or(height) + child.margin.top;
}
}
}
/// Calculate the cross size of each flex line.
///
/// # [9.4. Cross Size Determination](https://www.w3.org/TR/css-flexbox-1/#cross-sizing)
///
/// - [**Calculate the cross size of each flex line**](https://www.w3.org/TR/css-flexbox-1/#algo-cross-line).
///
/// If the flex container is single-line and has a definite cross size, the cross size of the flex line is the flex container’s inner cross size.
///
/// Otherwise, for each flex line:
///
/// 1. Collect all the flex items whose inline-axis is parallel to the main-axis, whose align-self is baseline, and whose cross-axis margins are both non-auto.
/// Find the largest of the distances between each item’s baseline and its hypothetical outer cross-start edge,
/// and the largest of the distances between each item’s baseline and its hypothetical outer cross-end edge, and sum these two values.
///
/// 2. Among all the items not collected by the previous step, find the largest outer hypothetical cross size.
///
/// 3. The used cross-size of the flex line is the largest of the numbers found in the previous two steps and zero.
///
/// If the flex container is single-line, then clamp the line’s cross-size to be within the container’s computed min and max cross sizes.
/// **Note that if CSS 2.1’s definition of min/max-width/height applied more generally, this behavior would fall out automatically**.
#[inline]
fn calculate_cross_size(flex_lines: &mut [FlexLine], node_size: Size<Option<f32>>, constants: &AlgoConstants) {
// Note: AlignContent::SpaceEvenly and AlignContent::SpaceAround behave like AlignContent::Stretch when there is only
// a single flex line in the container. See: https://www.w3.org/TR/css-flexbox-1/#align-content-property
// Also: align_content is ignored entirely (and thus behaves like Stretch) when `flex_wrap` is set to `nowrap`.
if flex_lines.len() == 1
&& node_size.cross(constants.dir).is_some()
&& (!constants.is_wrap
|| matches!(
constants.align_content,
AlignContent::Stretch | AlignContent::SpaceEvenly | AlignContent::SpaceAround
))
{
let cross_axis_padding_border = constants.content_box_inset.cross_axis_sum(constants.dir);
let cross_min_size = constants.min_size.cross(constants.dir);
let cross_max_size = constants.max_size.cross(constants.dir);
flex_lines[0].cross_size = node_size
.cross(constants.dir)
.maybe_clamp(cross_min_size, cross_max_size)
.maybe_sub(cross_axis_padding_border)
.maybe_max(0.0)
.unwrap_or(0.0);
} else {
for line in flex_lines.iter_mut() {
// 1. Collect all the flex items whose inline-axis is parallel to the main-axis, whose
// align-self is baseline, and whose cross-axis margins are both non-auto. Find the
// largest of the distances between each item’s baseline and its hypothetical outer
// cross-start edge, and the largest of the distances between each item’s baseline
// and its hypothetical outer cross-end edge, and sum these two values.
// 2. Among all the items not collected by the previous step, find the largest
// outer hypothetical cross size.
// 3. The used cross-size of the flex line is the largest of the numbers found in the
// previous two steps and zero.
let max_baseline: f32 = line.items.iter().map(|child| child.baseline).fold(0.0, |acc, x| acc.max(x));
line.cross_size = line
.items
.iter()
.map(|child| {
if child.align_self == AlignSelf::Baseline
&& !child.margin_is_auto.cross_start(constants.dir)
&& !child.margin_is_auto.cross_end(constants.dir)
{
max_baseline - child.baseline + child.hypothetical_outer_size.cross(constants.dir)
} else {
child.hypothetical_outer_size.cross(constants.dir)
}
})
.fold(0.0, |acc, x| acc.max(x));
}
}
}
/// Handle 'align-content: stretch'.
///
/// # [9.4. Cross Size Determination](https://www.w3.org/TR/css-flexbox-1/#cross-sizing)
///
/// - [**Handle 'align-content: stretch'**](https://www.w3.org/TR/css-flexbox-1/#algo-line-stretch). If the flex container has a definite cross size, align-content is stretch,
/// and the sum of the flex lines' cross sizes is less than the flex container’s inner cross size,
/// increase the cross size of each flex line by equal amounts such that the sum of their cross sizes exactly equals the flex container’s inner cross size.
#[inline]
fn handle_align_content_stretch(flex_lines: &mut [FlexLine], node_size: Size<Option<f32>>, constants: &AlgoConstants) {
if constants.align_content == AlignContent::Stretch {
let cross_axis_padding_border = constants.content_box_inset.cross_axis_sum(constants.dir);
let cross_min_size = constants.min_size.cross(constants.dir);
let cross_max_size = constants.max_size.cross(constants.dir);
let container_min_inner_cross = node_size
.cross(constants.dir)
.or(cross_min_size)
.maybe_clamp(cross_min_size, cross_max_size)
.maybe_sub(cross_axis_padding_border)
.maybe_max(0.0)
.unwrap_or(0.0);
let total_cross_axis_gap = sum_axis_gaps(constants.gap.cross(constants.dir), flex_lines.len());
let lines_total_cross: f32 = flex_lines.iter().map(|line| line.cross_size).sum::<f32>() + total_cross_axis_gap;
if lines_total_cross < container_min_inner_cross {
let remaining = container_min_inner_cross - lines_total_cross;
let addition = remaining / flex_lines.len() as f32;
flex_lines.iter_mut().for_each(|line| line.cross_size += addition);
}
}
}
/// Determine the used cross size of each flex item.
///
/// # [9.4. Cross Size Determination](https://www.w3.org/TR/css-flexbox-1/#cross-sizing)
///
/// - [**Determine the used cross size of each flex item**](https://www.w3.org/TR/css-flexbox-1/#algo-stretch). If a flex item has align-self: stretch, its computed cross size property is auto,
/// and neither of its cross-axis margins are auto, the used outer cross size is the used cross size of its flex line, clamped according to the item’s used min and max cross sizes.
/// Otherwise, the used cross size is the item’s hypothetical cross size.
///
/// If the flex item has align-self: stretch, redo layout for its contents, treating this used size as its definite cross size so that percentage-sized children can be resolved.
///
/// **Note that this step does not affect the main size of the flex item, even if it has an intrinsic aspect ratio**.
#[inline]
fn determine_used_cross_size(tree: &impl PartialLayoutTree, flex_lines: &mut [FlexLine], constants: &AlgoConstants) {
for line in flex_lines {
let line_cross_size = line.cross_size;
for child in line.items.iter_mut() {
let child_style = tree.get_style(child.node);
child.target_size.set_cross(
constants.dir,
if child.align_self == AlignSelf::Stretch
&& !child.margin_is_auto.cross_start(constants.dir)
&& !child.margin_is_auto.cross_end(constants.dir)
&& child_style.size.cross(constants.dir) == Dimension::Auto
{
// For some reason this particular usage of max_width is an exception to the rule that max_width's transfer
// using the aspect_ratio (if set). Both Chrome and Firefox agree on this. And reading the spec, it seems like
// a reasonable interpretation. Although it seems to me that the spec *should* apply aspect_ratio here.
let max_size_ignoring_aspect_ratio = child_style.max_size.maybe_resolve(constants.node_inner_size);
(line_cross_size - child.margin.cross_axis_sum(constants.dir)).maybe_clamp(
child.min_size.cross(constants.dir),
max_size_ignoring_aspect_ratio.cross(constants.dir),
)
} else {
child.hypothetical_inner_size.cross(constants.dir)
},
);
child.outer_target_size.set_cross(
constants.dir,
child.target_size.cross(constants.dir) + child.margin.cross_axis_sum(constants.dir),
);
}
}
}
/// Distribute any remaining free space.
///
/// # [9.5. Main-Axis Alignment](https://www.w3.org/TR/css-flexbox-1/#main-alignment)
///
/// - [**Distribute any remaining free space**](https://www.w3.org/TR/css-flexbox-1/#algo-main-align). For each flex line:
///
/// 1. If the remaining free space is positive and at least one main-axis margin on this line is `auto`, distribute the free space equally among these margins.
/// Otherwise, set all `auto` margins to zero.
///
/// 2. Align the items along the main-axis per `justify-content`.
#[inline]
fn distribute_remaining_free_space(flex_lines: &mut [FlexLine], constants: &AlgoConstants) {
for line in flex_lines {
let total_main_axis_gap = sum_axis_gaps(constants.gap.main(constants.dir), line.items.len());
let used_space: f32 = total_main_axis_gap
+ line.items.iter().map(|child| child.outer_target_size.main(constants.dir)).sum::<f32>();
let free_space = constants.inner_container_size.main(constants.dir) - used_space;
let mut num_auto_margins = 0;
for child in line.items.iter_mut() {
if child.margin_is_auto.main_start(constants.dir) {
num_auto_margins += 1;
}
if child.margin_is_auto.main_end(constants.dir) {
num_auto_margins += 1;
}
}
if free_space > 0.0 && num_auto_margins > 0 {
let margin = free_space / num_auto_margins as f32;
for child in line.items.iter_mut() {
if child.margin_is_auto.main_start(constants.dir) {
if constants.is_row {
child.margin.left = margin;
} else {
child.margin.top = margin;
}
}
if child.margin_is_auto.main_end(constants.dir) {
if constants.is_row {
child.margin.right = margin;
} else {
child.margin.bottom = margin;
}
}
}
} else {
let num_items = line.items.len();
let layout_reverse = constants.dir.is_reverse();
let gap = constants.gap.main(constants.dir);
let justify_content_mode = constants.justify_content.unwrap_or(JustifyContent::FlexStart);
let justify_item = |(i, child): (usize, &mut FlexItem)| {
child.offset_main =
compute_alignment_offset(free_space, num_items, gap, justify_content_mode, layout_reverse, i == 0);
};
if layout_reverse {
line.items.iter_mut().rev().enumerate().for_each(justify_item);
} else {
line.items.iter_mut().enumerate().for_each(justify_item);
}
}
}
}
/// Resolve cross-axis `auto` margins.
///
/// # [9.6. Cross-Axis Alignment](https://www.w3.org/TR/css-flexbox-1/#cross-alignment)
///
/// - [**Resolve cross-axis `auto` margins**](https://www.w3.org/TR/css-flexbox-1/#algo-cross-margins).
/// If a flex item has auto cross-axis margins:
///
/// - If its outer cross size (treating those auto margins as zero) is less than the cross size of its flex line,
/// distribute the difference in those sizes equally to the auto margins.
///
/// - Otherwise, if the block-start or inline-start margin (whichever is in the cross axis) is auto, set it to zero.
/// Set the opposite margin so that the outer cross size of the item equals the cross size of its flex line.
#[inline]
fn resolve_cross_axis_auto_margins(flex_lines: &mut [FlexLine], constants: &AlgoConstants) {
for line in flex_lines {
let line_cross_size = line.cross_size;
let max_baseline: f32 = line.items.iter_mut().map(|child| child.baseline).fold(0.0, |acc, x| acc.max(x));
for child in line.items.iter_mut() {
let free_space = line_cross_size - child.outer_target_size.cross(constants.dir);
if child.margin_is_auto.cross_start(constants.dir) && child.margin_is_auto.cross_end(constants.dir) {
if constants.is_row {
child.margin.top = free_space / 2.0;
child.margin.bottom = free_space / 2.0;
} else {
child.margin.left = free_space / 2.0;
child.margin.right = free_space / 2.0;
}
} else if child.margin_is_auto.cross_start(constants.dir) {
if constants.is_row {
child.margin.top = free_space;
} else {
child.margin.left = free_space;
}
} else if child.margin_is_auto.cross_end(constants.dir) {
if constants.is_row {
child.margin.bottom = free_space;
} else {
child.margin.right = free_space;
}
} else {
// 14. Align all flex items along the cross-axis.
child.offset_cross = align_flex_items_along_cross_axis(child, free_space, max_baseline, constants);
}
}
}
}
/// Align all flex items along the cross-axis.
///
/// # [9.6. Cross-Axis Alignment](https://www.w3.org/TR/css-flexbox-1/#cross-alignment)
///
/// - [**Align all flex items along the cross-axis**](https://www.w3.org/TR/css-flexbox-1/#algo-cross-align) per `align-self`,
/// if neither of the item's cross-axis margins are `auto`.
#[inline]
fn align_flex_items_along_cross_axis(
child: &FlexItem,
free_space: f32,
max_baseline: f32,
constants: &AlgoConstants,
) -> f32 {
match child.align_self {
AlignSelf::Start => 0.0,
AlignSelf::FlexStart => {
if constants.is_wrap_reverse {
free_space
} else {
0.0
}
}
AlignSelf::End => free_space,
AlignSelf::FlexEnd => {
if constants.is_wrap_reverse {
0.0
} else {
free_space
}
}
AlignSelf::Center => free_space / 2.0,
AlignSelf::Baseline => {
if constants.is_row {
max_baseline - child.baseline
} else {
// Until we support vertical writing modes, baseline alignment only makes sense if
// the constants.direction is row, so we treat it as flex-start alignment in columns.
if constants.is_wrap_reverse {
free_space
} else {
0.0
}
}
}
AlignSelf::Stretch => {
if constants.is_wrap_reverse {
free_space
} else {
0.0
}
}
}
}
/// Determine the flex container’s used cross size.
///
/// # [9.6. Cross-Axis Alignment](https://www.w3.org/TR/css-flexbox-1/#cross-alignment)
///
/// - [**Determine the flex container’s used cross size**](https://www.w3.org/TR/css-flexbox-1/#algo-cross-container):
///
/// - If the cross size property is a definite size, use that, clamped by the used min and max cross sizes of the flex container.
///
/// - Otherwise, use the sum of the flex lines' cross sizes, clamped by the used min and max cross sizes of the flex container.
#[inline]
#[must_use]
fn determine_container_cross_size(
flex_lines: &[FlexLine],
node_size: Size<Option<f32>>,
constants: &mut AlgoConstants,
) -> f32 {
let total_cross_axis_gap = sum_axis_gaps(constants.gap.cross(constants.dir), flex_lines.len());
let total_line_cross_size: f32 = flex_lines.iter().map(|line| line.cross_size).sum::<f32>();
let padding_border_sum = constants.content_box_inset.cross_axis_sum(constants.dir);
let cross_scrollbar_gutter = constants.scrollbar_gutter.cross(constants.dir);
let min_cross_size = constants.min_size.cross(constants.dir);
let max_cross_size = constants.max_size.cross(constants.dir);
let outer_container_size = node_size
.cross(constants.dir)
.unwrap_or(total_line_cross_size + total_cross_axis_gap + padding_border_sum)
.maybe_clamp(min_cross_size, max_cross_size)
.max(padding_border_sum - cross_scrollbar_gutter);
let inner_container_size = f32_max(outer_container_size - padding_border_sum, 0.0);
constants.container_size.set_cross(constants.dir, outer_container_size);
constants.inner_container_size.set_cross(constants.dir, inner_container_size);
total_line_cross_size
}
/// Align all flex lines per `align-content`.
///
/// # [9.6. Cross-Axis Alignment](https://www.w3.org/TR/css-flexbox-1/#cross-alignment)
///
/// - [**Align all flex lines**](https://www.w3.org/TR/css-flexbox-1/#algo-line-align) per `align-content`.
#[inline]
fn align_flex_lines_per_align_content(flex_lines: &mut [FlexLine], constants: &AlgoConstants, total_cross_size: f32) {
let num_lines = flex_lines.len();
let gap = constants.gap.cross(constants.dir);
let align_content_mode = constants.align_content;
let total_cross_axis_gap = sum_axis_gaps(gap, num_lines);
let free_space = constants.inner_container_size.cross(constants.dir) - total_cross_size - total_cross_axis_gap;
let align_line = |(i, line): (usize, &mut FlexLine)| {
line.offset_cross =
compute_alignment_offset(free_space, num_lines, gap, align_content_mode, constants.is_wrap_reverse, i == 0);
};
if constants.is_wrap_reverse {
flex_lines.iter_mut().rev().enumerate().for_each(align_line);
} else {
flex_lines.iter_mut().enumerate().for_each(align_line);
}
}
/// Calculates the layout for a flex-item
#[allow(clippy::too_many_arguments)]
fn calculate_flex_item(
tree: &mut impl PartialLayoutTree,
item: &mut FlexItem,
total_offset_main: &mut f32,
total_offset_cross: f32,
line_offset_cross: f32,
#[cfg(feature = "content_size")] total_content_size: &mut Size<f32>,
container_size: Size<f32>,
node_inner_size: Size<Option<f32>>,
direction: FlexDirection,
) {
let layout_output = tree.perform_child_layout(
item.node,
item.target_size.map(|s| s.into()),
node_inner_size,
container_size.map(|s| s.into()),
SizingMode::ContentSize,
Line::FALSE,
);
let LayoutOutput {
size,
#[cfg(feature = "content_size")]
content_size,
..
} = layout_output;
let offset_main = *total_offset_main
+ item.offset_main
+ item.margin.main_start(direction)
+ (item.inset.main_start(direction).or(item.inset.main_end(direction).map(|pos| -pos)).unwrap_or(0.0));
let offset_cross = total_offset_cross
+ item.offset_cross
+ line_offset_cross
+ item.margin.cross_start(direction)
+ (item.inset.cross_start(direction).or(item.inset.cross_end(direction).map(|pos| -pos)).unwrap_or(0.0));
if direction.is_row() {
let baseline_offset_cross = total_offset_cross + item.offset_cross + item.margin.cross_start(direction);
let inner_baseline = layout_output.first_baselines.y.unwrap_or(size.height);
item.baseline = baseline_offset_cross + inner_baseline;
} else {
let baseline_offset_main = *total_offset_main + item.offset_main + item.margin.main_start(direction);
let inner_baseline = layout_output.first_baselines.y.unwrap_or(size.height);
item.baseline = baseline_offset_main + inner_baseline;
}
let location = match direction.is_row() {
true => Point { x: offset_main, y: offset_cross },
false => Point { x: offset_cross, y: offset_main },
};
let scrollbar_size = Size {
width: if item.overflow.y == Overflow::Scroll { item.scrollbar_width } else { 0.0 },
height: if item.overflow.x == Overflow::Scroll { item.scrollbar_width } else { 0.0 },
};
tree.set_unrounded_layout(
item.node,
&Layout {
order: item.order,
size,
#[cfg(feature = "content_size")]
content_size,
scrollbar_size,
location,
padding: item.padding,
border: item.border,
},
);
*total_offset_main += item.offset_main + item.margin.main_axis_sum(direction) + size.main(direction);
#[cfg(feature = "content_size")]
{
*total_content_size =
total_content_size.f32_max(compute_content_size_contribution(location, size, content_size, item.overflow));
}
}
/// Calculates the layout line
#[allow(clippy::too_many_arguments)]
fn calculate_layout_line(
tree: &mut impl PartialLayoutTree,
line: &mut FlexLine,
total_offset_cross: &mut f32,
#[cfg(feature = "content_size")] content_size: &mut Size<f32>,
container_size: Size<f32>,
node_inner_size: Size<Option<f32>>,
padding_border: Rect<f32>,
direction: FlexDirection,
) {
let mut total_offset_main = padding_border.main_start(direction);
let line_offset_cross = line.offset_cross;
if direction.is_reverse() {
for item in line.items.iter_mut().rev() {
calculate_flex_item(
tree,
item,
&mut total_offset_main,
*total_offset_cross,
line_offset_cross,
#[cfg(feature = "content_size")]
content_size,
container_size,
node_inner_size,
direction,
);
}
} else {
for item in line.items.iter_mut() {
calculate_flex_item(
tree,
item,
&mut total_offset_main,
*total_offset_cross,
line_offset_cross,
#[cfg(feature = "content_size")]
content_size,
container_size,
node_inner_size,
direction,
);
}
}
*total_offset_cross += line_offset_cross + line.cross_size;
}
/// Do a final layout pass and collect the resulting layouts.
#[inline]
fn final_layout_pass(
tree: &mut impl PartialLayoutTree,
flex_lines: &mut [FlexLine],
constants: &AlgoConstants,
) -> Size<f32> {
let mut total_offset_cross = constants.content_box_inset.cross_start(constants.dir);
#[cfg_attr(not(feature = "content_size"), allow(unused_mut))]
let mut content_size = Size::ZERO;
if constants.is_wrap_reverse {
for line in flex_lines.iter_mut().rev() {
calculate_layout_line(
tree,
line,
&mut total_offset_cross,
#[cfg(feature = "content_size")]
&mut content_size,
constants.container_size,
constants.node_inner_size,
constants.content_box_inset,
constants.dir,
);
}
} else {
for line in flex_lines.iter_mut() {
calculate_layout_line(
tree,
line,
&mut total_offset_cross,
#[cfg(feature = "content_size")]
&mut content_size,
constants.container_size,
constants.node_inner_size,
constants.content_box_inset,
constants.dir,
);
}
}
content_size
}
/// Perform absolute layout on all absolutely positioned children.
#[inline]
fn perform_absolute_layout_on_absolute_children(
tree: &mut impl PartialLayoutTree,
node: NodeId,
constants: &AlgoConstants,
) -> Size<f32> {
let container_width = constants.container_size.width;
let container_height = constants.container_size.height;
#[cfg_attr(not(feature = "content_size"), allow(unused_mut))]
let mut content_size = Size::ZERO;
for order in 0..tree.child_count(node) {
let child = tree.get_child_id(node, order);
let child_style = tree.get_style(child);
// Skip items that are display:none or are not position:absolute
if child_style.display == Display::None || child_style.position != Position::Absolute {
continue;
}
let overflow = child_style.overflow;
let scrollbar_width = child_style.scrollbar_width;
let aspect_ratio = child_style.aspect_ratio;
let align_self = child_style.align_self.unwrap_or(constants.align_items);
let margin = child_style.margin.map(|margin| margin.resolve_to_option(container_width));
let padding = child_style.padding.resolve_or_zero(Some(container_width));
let border = child_style.border.resolve_or_zero(Some(container_width));
let padding_border_sum = (padding + border).sum_axes();
// Resolve inset
let left = child_style.inset.left.maybe_resolve(container_width);
let right = child_style.inset.right.maybe_resolve(container_width);
let top = child_style.inset.top.maybe_resolve(container_height);
let bottom = child_style.inset.bottom.maybe_resolve(container_height);
// Compute known dimensions from min/max/inherent size styles
let style_size =
child_style.size.maybe_resolve(constants.container_size).maybe_apply_aspect_ratio(aspect_ratio);
let min_size = child_style
.min_size
.maybe_resolve(constants.container_size)
.maybe_apply_aspect_ratio(aspect_ratio)
.or(padding_border_sum.map(Some))
.maybe_max(padding_border_sum);
let max_size =
child_style.max_size.maybe_resolve(constants.container_size).maybe_apply_aspect_ratio(aspect_ratio);
let mut known_dimensions = style_size.maybe_clamp(min_size, max_size);
// Fill in width from left/right and reapply aspect ratio if:
// - Width is not already known
// - Item has both left and right inset properties set
if let (None, Some(left), Some(right)) = (known_dimensions.width, left, right) {
let new_width_raw = container_width.maybe_sub(margin.left).maybe_sub(margin.right) - left - right;
known_dimensions.width = Some(f32_max(new_width_raw, 0.0));
known_dimensions = known_dimensions.maybe_apply_aspect_ratio(aspect_ratio).maybe_clamp(min_size, max_size);
}
// Fill in height from top/bottom and reapply aspect ratio if:
// - Height is not already known
// - Item has both top and bottom inset properties set
if let (None, Some(top), Some(bottom)) = (known_dimensions.height, top, bottom) {
let new_height_raw = container_height.maybe_sub(margin.top).maybe_sub(margin.bottom) - top - bottom;
known_dimensions.height = Some(f32_max(new_height_raw, 0.0));
known_dimensions = known_dimensions.maybe_apply_aspect_ratio(aspect_ratio).maybe_clamp(min_size, max_size);
}
let layout_output = tree.perform_child_layout(
child,
known_dimensions,
constants.node_inner_size,
Size {
width: AvailableSpace::Definite(container_width.maybe_clamp(min_size.width, max_size.width)),
height: AvailableSpace::Definite(container_height.maybe_clamp(min_size.height, max_size.height)),
},
SizingMode::ContentSize,
Line::FALSE,
);
let measured_size = layout_output.size;
let final_size = known_dimensions.unwrap_or(measured_size).maybe_clamp(min_size, max_size);
let non_auto_margin = margin.map(|m| m.unwrap_or(0.0));
let free_space = Size {
width: constants.container_size.width - final_size.width - non_auto_margin.horizontal_axis_sum(),
height: constants.container_size.height - final_size.height - non_auto_margin.vertical_axis_sum(),
}
.f32_max(Size::ZERO);
// Expand auto margins to fill available space
let resolved_margin = {
let auto_margin_size = Size {
width: {
let auto_margin_count = margin.left.is_none() as u8 + margin.right.is_none() as u8;
if auto_margin_count > 0 {
free_space.width / auto_margin_count as f32
} else {
0.0
}
},
height: {
let auto_margin_count = margin.top.is_none() as u8 + margin.bottom.is_none() as u8;
if auto_margin_count > 0 {
free_space.height / auto_margin_count as f32
} else {
0.0
}
},
};
Rect {
left: margin.left.unwrap_or(auto_margin_size.width),
right: margin.right.unwrap_or(auto_margin_size.width),
top: margin.top.unwrap_or(auto_margin_size.height),
bottom: margin.bottom.unwrap_or(auto_margin_size.height),
}
};
// Determine flex-relative insets
let (start_main, end_main) = if constants.is_row { (left, right) } else { (top, bottom) };
let (start_cross, end_cross) = if constants.is_row { (top, bottom) } else { (left, right) };
// Apply main-axis alignment
// let free_main_space = free_space.main(constants.dir) - resolved_margin.main_axis_sum(constants.dir);
let offset_main = if let Some(start) = start_main {
start + constants.border.main_start(constants.dir) + resolved_margin.main_start(constants.dir)
} else if let Some(end) = end_main {
constants.container_size.main(constants.dir)
- constants.border.main_end(constants.dir)
- final_size.main(constants.dir)
- end
- resolved_margin.main_end(constants.dir)
} else {
// Stretch is an invalid value for justify_content in the flexbox algorithm, so we
// treat it as if it wasn't set (and thus we default to FlexStart behaviour)
match (constants.justify_content.unwrap_or(JustifyContent::Start), constants.is_wrap_reverse) {
(JustifyContent::SpaceBetween, _)
| (JustifyContent::Start, _)
| (JustifyContent::Stretch, false)
| (JustifyContent::FlexStart, false)
| (JustifyContent::FlexEnd, true) => {
constants.content_box_inset.main_start(constants.dir) + resolved_margin.main_start(constants.dir)
}
(JustifyContent::End, _)
| (JustifyContent::FlexEnd, false)
| (JustifyContent::FlexStart, true)
| (JustifyContent::Stretch, true) => {
constants.container_size.main(constants.dir)
- constants.content_box_inset.main_end(constants.dir)
- final_size.main(constants.dir)
- resolved_margin.main_end(constants.dir)
}
(JustifyContent::SpaceEvenly, _) | (JustifyContent::SpaceAround, _) | (JustifyContent::Center, _) => {
(constants.container_size.main(constants.dir)
+ constants.content_box_inset.main_start(constants.dir)
- constants.content_box_inset.main_end(constants.dir)
- final_size.main(constants.dir)
+ resolved_margin.main_start(constants.dir)
- resolved_margin.main_end(constants.dir))
/ 2.0
}
}
};
// Apply cross-axis alignment
// let free_cross_space = free_space.cross(constants.dir) - resolved_margin.cross_axis_sum(constants.dir);
let offset_cross = if let Some(start) = start_cross {
start + constants.border.cross_start(constants.dir) + resolved_margin.cross_start(constants.dir)
} else if let Some(end) = end_cross {
constants.container_size.cross(constants.dir)
- constants.border.cross_end(constants.dir)
- final_size.cross(constants.dir)
- end
- resolved_margin.cross_end(constants.dir)
} else {
match (align_self, constants.is_wrap_reverse) {
// Stretch alignment does not apply to absolutely positioned items
// See "Example 3" at https://www.w3.org/TR/css-flexbox-1/#abspos-items
// Note: Stretch should be FlexStart not Start when we support both
(AlignSelf::Start, _)
| (AlignSelf::Baseline | AlignSelf::Stretch | AlignSelf::FlexStart, false)
| (AlignSelf::FlexEnd, true) => {
constants.content_box_inset.cross_start(constants.dir) + resolved_margin.cross_start(constants.dir)
}
(AlignSelf::End, _)
| (AlignSelf::Baseline | AlignSelf::Stretch | AlignSelf::FlexStart, true)
| (AlignSelf::FlexEnd, false) => {
constants.container_size.cross(constants.dir)
- constants.content_box_inset.cross_end(constants.dir)
- final_size.cross(constants.dir)
- resolved_margin.cross_end(constants.dir)
}
(AlignSelf::Center, _) => {
(constants.container_size.cross(constants.dir)
+ constants.content_box_inset.cross_start(constants.dir)
- constants.content_box_inset.cross_end(constants.dir)
- final_size.cross(constants.dir)
+ resolved_margin.cross_start(constants.dir)
- resolved_margin.cross_end(constants.dir))
/ 2.0
}
}
};
let location = match constants.is_row {
true => Point { x: offset_main, y: offset_cross },
false => Point { x: offset_cross, y: offset_main },
};
let scrollbar_size = Size {
width: if overflow.y == Overflow::Scroll { scrollbar_width } else { 0.0 },
height: if overflow.x == Overflow::Scroll { scrollbar_width } else { 0.0 },
};
tree.set_unrounded_layout(
child,
&Layout {
order: order as u32,
size: final_size,
#[cfg(feature = "content_size")]
content_size: layout_output.content_size,
scrollbar_size,
location,
padding,
border,
},
);
#[cfg(feature = "content_size")]
{
let size_content_size_contribution = Size {
width: match overflow.x {
Overflow::Visible => f32_max(final_size.width, layout_output.content_size.width),
_ => final_size.width,
},
height: match overflow.y {
Overflow::Visible => f32_max(final_size.height, layout_output.content_size.height),
_ => final_size.height,
},
};
if size_content_size_contribution.has_non_zero_area() {
let content_size_contribution = Size {
width: location.x + size_content_size_contribution.width,
height: location.y + size_content_size_contribution.height,
};
content_size = content_size.f32_max(content_size_contribution);
}
}
}
content_size
}
/// Computes the total space taken up by gaps in an axis given:
/// - The size of each gap
/// - The number of items (children or flex-lines) between which there are gaps
#[inline(always)]
fn sum_axis_gaps(gap: f32, num_items: usize) -> f32 {
// Gaps only exist between items, so...
if num_items <= 1 {
// ...if there are less than 2 items then there are no gaps
0.0
} else {
// ...otherwise there are (num_items - 1) gaps
gap * (num_items - 1) as f32
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::redundant_clone)]
use crate::{
geometry::Size,
style::{FlexWrap, Style},
util::{MaybeMath, ResolveOrZero},
TaffyTree,
};
// Make sure we get correct constants
#[test]
fn correct_constants() {
let mut tree: TaffyTree<()> = TaffyTree::with_capacity(16);
let style = Style::default();
let node_id = tree.new_leaf(style.clone()).unwrap();
let node_size = Size::NONE;
let parent_size = Size::NONE;
let constants = super::compute_constants(tree.style(node_id).unwrap(), node_size, parent_size);
assert!(constants.dir == style.flex_direction);
assert!(constants.is_row == style.flex_direction.is_row());
assert!(constants.is_column == style.flex_direction.is_column());
assert!(constants.is_wrap_reverse == (style.flex_wrap == FlexWrap::WrapReverse));
let margin = style.margin.resolve_or_zero(parent_size);
assert_eq!(constants.margin, margin);
let border = style.border.resolve_or_zero(parent_size);
let padding = style.padding.resolve_or_zero(parent_size);
let padding_border = padding + border;
assert_eq!(constants.border, border);
assert_eq!(constants.content_box_inset, padding_border);
let inner_size = Size {
width: node_size.width.maybe_sub(padding_border.horizontal_axis_sum()),
height: node_size.height.maybe_sub(padding_border.vertical_axis_sum()),
};
assert_eq!(constants.node_inner_size, inner_size);
assert_eq!(constants.container_size, Size::zero());
assert_eq!(constants.inner_container_size, Size::zero());
}
}