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 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792
|
/*
* Copyright (C) 2011 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "RenderFlexibleBox.h"
#include "BaselineAlignment.h"
#include "FlexibleBoxAlgorithm.h"
#include "FontBaseline.h"
#include "HitTestResult.h"
#include "InspectorInstrumentation.h"
#include "LayoutIntegrationCoverage.h"
#include "LayoutIntegrationFlexLayout.h"
#include "LayoutRepainter.h"
#include "LayoutUnit.h"
#include "RenderBlockInlines.h"
#include "RenderBoxInlines.h"
#include "RenderBoxModelObjectInlines.h"
#include "RenderChildIterator.h"
#include "RenderElementInlines.h"
#include "RenderLayer.h"
#include "RenderLayoutState.h"
#include "RenderObjectEnums.h"
#include "RenderObjectInlines.h"
#include "RenderReplaced.h"
#include "RenderSVGRoot.h"
#include "RenderStyleConstants.h"
#include "RenderTable.h"
#include "RenderView.h"
#include "WritingMode.h"
#include <limits>
#include <wtf/MathExtras.h>
#include <wtf/SetForScope.h>
#include <wtf/TZoneMallocInlines.h>
#include <wtf/TypeCasts.h>
namespace WebCore {
WTF_MAKE_TZONE_OR_ISO_ALLOCATED_IMPL(RenderFlexibleBox);
struct RenderFlexibleBox::LineState {
LineState(LayoutUnit crossAxisOffset, LayoutUnit crossAxisExtent, std::optional<BaselineAlignmentState> baselineAlignmentState, FlexLayoutItems&& flexLayoutItems)
: crossAxisOffset(crossAxisOffset)
, crossAxisExtent(crossAxisExtent)
, baselineAlignmentState(baselineAlignmentState)
, flexLayoutItems(flexLayoutItems)
{
}
LayoutUnit crossAxisOffset;
LayoutUnit crossAxisExtent;
std::optional<BaselineAlignmentState> baselineAlignmentState;
FlexLayoutItems flexLayoutItems;
};
RenderFlexibleBox::RenderFlexibleBox(Type type, Element& element, RenderStyle&& style)
: RenderBlock(type, element, WTFMove(style), TypeFlag::IsFlexibleBox)
{
ASSERT(isRenderFlexibleBox());
setChildrenInline(false); // All of our children must be block-level.
}
RenderFlexibleBox::RenderFlexibleBox(Type type, Document& document, RenderStyle&& style)
: RenderBlock(type, document, WTFMove(style), TypeFlag::IsFlexibleBox)
{
ASSERT(isRenderFlexibleBox());
setChildrenInline(false); // All of our children must be block-level.
}
RenderFlexibleBox::~RenderFlexibleBox() = default;
ASCIILiteral RenderFlexibleBox::renderName() const
{
return "RenderFlexibleBox"_s;
}
void RenderFlexibleBox::computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const
{
auto addScrollbarWidth = [&]() {
LayoutUnit scrollbarWidth(scrollbarLogicalWidth());
maxLogicalWidth += scrollbarWidth;
minLogicalWidth += scrollbarWidth;
};
if (shouldApplySizeOrInlineSizeContainment()) {
if (auto width = explicitIntrinsicInnerLogicalWidth()) {
minLogicalWidth = width.value();
maxLogicalWidth = width.value();
}
addScrollbarWidth();
return;
}
LayoutUnit flexItemMinWidth;
LayoutUnit flexItemMaxWidth;
bool hadExcludedChildren = computePreferredWidthsForExcludedChildren(flexItemMinWidth, flexItemMaxWidth);
// FIXME: We're ignoring flex-basis here and we shouldn't. We can't start
// honoring it though until the flex shorthand stops setting it to 0. See
// https://bugs.webkit.org/show_bug.cgi?id=116117 and
// https://crbug.com/240765.
size_t numItemsWithNormalLayout = 0;
for (RenderBox* flexItem = firstChildBox(); flexItem; flexItem = flexItem->nextSiblingBox()) {
if (flexItem->isOutOfFlowPositioned() || flexItem->isExcludedFromNormalLayout())
continue;
++numItemsWithNormalLayout;
// Pre-layout orthogonal children in order to get a valid value for the preferred width.
if (writingMode().isOrthogonal(flexItem->writingMode()))
flexItem->layoutIfNeeded();
LayoutUnit margin = marginIntrinsicLogicalWidthForChild(*flexItem);
LayoutUnit minPreferredLogicalWidth;
LayoutUnit maxPreferredLogicalWidth;
computeChildPreferredLogicalWidths(*flexItem, minPreferredLogicalWidth, maxPreferredLogicalWidth);
minPreferredLogicalWidth += margin;
maxPreferredLogicalWidth += margin;
if (!isColumnFlow()) {
maxLogicalWidth += maxPreferredLogicalWidth;
if (isMultiline()) {
// For multiline, the min preferred width is if you put a break between
// each item.
minLogicalWidth = std::max(minLogicalWidth, minPreferredLogicalWidth);
} else
minLogicalWidth += minPreferredLogicalWidth;
} else {
minLogicalWidth = std::max(minPreferredLogicalWidth, minLogicalWidth);
maxLogicalWidth = std::max(maxPreferredLogicalWidth, maxLogicalWidth);
}
}
if (!isColumnFlow() && numItemsWithNormalLayout > 1) {
LayoutUnit inlineGapSize = (numItemsWithNormalLayout - 1) * computeGap(GapType::BetweenItems);
maxLogicalWidth += inlineGapSize;
if (!isMultiline())
minLogicalWidth += inlineGapSize;
}
maxLogicalWidth = std::max(minLogicalWidth, maxLogicalWidth);
// Due to negative margins, it is possible that we calculated a negative
// intrinsic width. Make sure that we never return a negative width.
minLogicalWidth = std::max(0_lu, minLogicalWidth);
maxLogicalWidth = std::max(0_lu, maxLogicalWidth);
if (hadExcludedChildren) {
minLogicalWidth = std::max(minLogicalWidth, flexItemMinWidth);
maxLogicalWidth = std::max(maxLogicalWidth, flexItemMaxWidth);
}
addScrollbarWidth();
}
#define SET_OR_CLEAR_OVERRIDING_SIZE(box, SizeType, size) \
{ \
if (size) \
box.setOverridingBorderBoxLogical##SizeType(*size); \
else \
box.clearOverridingBorderBoxLogical##SizeType(); \
}
// RAII class which defines a scope in which overriding sizes of a box are either:
// 1) replaced by other size in one axis if size is specified
// 2) cleared in both axis if size == std::nullopt
//
// In any case the previous overriding sizes are restored on destruction (in case of
// not having a previous value it's simply cleared).
class OverridingSizesScope {
public:
enum class Axis {
Inline,
Block,
Both
};
OverridingSizesScope(RenderBox& box, Axis axis, std::optional<LayoutUnit> size = std::nullopt)
: m_box(box)
, m_axis(axis)
{
ASSERT(!size || (axis != Axis::Both));
if (axis == Axis::Both || axis == Axis::Inline) {
m_overridingWidth = box.overridingBorderBoxLogicalWidth();
SET_OR_CLEAR_OVERRIDING_SIZE(m_box, Width, size);
}
if (axis == Axis::Both || axis == Axis::Block) {
m_overridingHeight = box.overridingBorderBoxLogicalHeight();
SET_OR_CLEAR_OVERRIDING_SIZE(m_box, Height, size);
}
}
~OverridingSizesScope()
{
if (m_axis == Axis::Inline || m_axis == Axis::Both)
SET_OR_CLEAR_OVERRIDING_SIZE(m_box, Width, m_overridingWidth);
if (m_axis == Axis::Block || m_axis == Axis::Both)
SET_OR_CLEAR_OVERRIDING_SIZE(m_box, Height, m_overridingHeight);
}
private:
RenderBox& m_box;
Axis m_axis;
std::optional<LayoutUnit> m_overridingWidth;
std::optional<LayoutUnit> m_overridingHeight;
};
static void updateFlexItemDirtyBitsBeforeLayout(bool relayoutFlexItem, RenderBox& flexItem)
{
if (flexItem.isOutOfFlowPositioned())
return;
// FIXME: Technically percentage height objects only need a relayout if their percentage isn't going to be turned into
// an auto value. Add a method to determine this, so that we can avoid the relayout.
if (relayoutFlexItem || flexItem.hasRelativeLogicalHeight())
flexItem.setChildNeedsLayout(MarkOnlyThis);
}
void RenderFlexibleBox::computeChildIntrinsicLogicalWidths(RenderBox& flexBoxChild, LayoutUnit& minPreferredLogicalWidth, LayoutUnit& maxPreferredLogicalWidth) const
{
// Children excluded from normal layout are handled here too (e.g. legend when fieldset is set to flex).
ASSERT(flexBoxChild.isFlexItem() || (flexBoxChild.parent() == this && flexBoxChild.isExcludedFromNormalLayout()));
// If the item cross size should use the definite container cross size then set the overriding size now so
// the intrinsic sizes are properly computed in the presence of aspect ratios. The only exception is when
// we are both a flex item&container, because our parent might have already set our overriding size.
if (flexItemCrossSizeShouldUseContainerCrossSize(flexBoxChild) && !isFlexItem()) {
auto axis = mainAxisIsFlexItemInlineAxis(flexBoxChild) ? OverridingSizesScope::Axis::Block : OverridingSizesScope::Axis::Inline;
OverridingSizesScope overridingSizeScope(flexBoxChild, axis, computeCrossSizeForFlexItemUsingContainerCrossSize(flexBoxChild));
auto flexItemIntrinsicSizeComputation = SetForScope(m_inFlexItemIntrinsicWidthComputation, true);
RenderBlock::computeChildIntrinsicLogicalWidths(flexBoxChild, minPreferredLogicalWidth, maxPreferredLogicalWidth);
return;
}
OverridingSizesScope cleanOverridingSizesScope(flexBoxChild, OverridingSizesScope::Axis::Both);
RenderBlock::computeChildIntrinsicLogicalWidths(flexBoxChild, minPreferredLogicalWidth, maxPreferredLogicalWidth);
}
LayoutUnit RenderFlexibleBox::baselinePosition(FontBaseline, bool, LineDirectionMode direction, LinePositionMode) const
{
auto baseline = firstLineBaseline();
if (!baseline)
return synthesizedBaseline(*this, *parentStyle(), direction, BorderBox) + marginLogicalHeight();
return baseline.value() + (direction == HorizontalLine ? marginTop() : marginRight()).toInt();
}
std::optional<LayoutUnit> RenderFlexibleBox::firstLineBaseline() const
{
if ((isWritingModeRoot() && !isFlexItem()) || !m_numberOfFlexItemsOnFirstLine || shouldApplyLayoutContainment())
return { };
auto* baselineFlexItem = flexItemForFirstBaseline();
if (!baselineFlexItem)
return { };
if (!isColumnFlow() && !mainAxisIsFlexItemInlineAxis(*baselineFlexItem))
return LayoutUnit { (crossAxisExtentForFlexItem(*baselineFlexItem) + baselineFlexItem->logicalTop()).toInt() };
if (isColumnFlow() && mainAxisIsFlexItemInlineAxis(*baselineFlexItem))
return LayoutUnit { (mainAxisExtentForFlexItem(*baselineFlexItem) + baselineFlexItem->logicalTop()).toInt() };
std::optional<LayoutUnit> baseline = baselineFlexItem->firstLineBaseline();
if (!baseline) {
// FIXME: We should pass |direction| into firstLineBoxBaseline and stop bailing out if we're a writing mode root.
// This would also fix some cases where the flexbox is orthogonal to its container.
LineDirectionMode direction = isHorizontalWritingMode() ? HorizontalLine : VerticalLine;
return synthesizedBaseline(*baselineFlexItem, style(), direction, BorderBox) + baselineFlexItem->logicalTop();
}
return LayoutUnit { (baseline.value() + baselineFlexItem->logicalTop()).toInt() };
}
std::optional <LayoutUnit> RenderFlexibleBox::lastLineBaseline() const
{
if (isWritingModeRoot() || !m_numberOfFlexItemsOnLastLine || shouldApplyLayoutContainment())
return { };
auto* baselineFlexItem = flexItemForLastBaseline();
if (!baselineFlexItem)
return { };
if (!isColumnFlow() && !mainAxisIsFlexItemInlineAxis(*baselineFlexItem))
return LayoutUnit { (crossAxisExtentForFlexItem(*baselineFlexItem) + baselineFlexItem->logicalTop()).toInt() };
if (isColumnFlow() && mainAxisIsFlexItemInlineAxis(*baselineFlexItem))
return LayoutUnit { (mainAxisExtentForFlexItem(*baselineFlexItem) + baselineFlexItem->logicalTop()).toInt() };
auto baseline = baselineFlexItem->lastLineBaseline();
if (!baseline) {
// FIXME: We should pass |direction| into firstLineBoxBaseline and stop bailing out if we're a writing mode root.
// This would also fix some cases where the flexbox is orthogonal to its container.
LineDirectionMode direction = isHorizontalWritingMode() ? HorizontalLine : VerticalLine;
return synthesizedBaseline(*baselineFlexItem, style(), direction, BorderBox) + baselineFlexItem->logicalTop();
}
return LayoutUnit { (baseline.value() + baselineFlexItem->logicalTop()).toInt() };
}
std::optional<LayoutUnit> RenderFlexibleBox::inlineBlockBaseline(LineDirectionMode) const
{
return firstLineBaseline();
}
static const StyleContentAlignmentData& contentAlignmentNormalBehavior()
{
// The justify-content property applies along the main axis, but since
// flexing in the main axis is controlled by flex, stretch behaves as
// flex-start (ignoring the specified fallback alignment, if any).
// https://drafts.csswg.org/css-align/#distribution-flex
static const StyleContentAlignmentData normalBehavior = { ContentPosition::Normal, ContentDistribution::Stretch};
return normalBehavior;
}
void RenderFlexibleBox::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
{
RenderBlock::styleDidChange(diff, oldStyle);
if (!oldStyle || diff != StyleDifference::Layout)
return;
auto oldStyleAlignItemsIsStretch = oldStyle->resolvedAlignItems(selfAlignmentNormalBehavior()).position() == ItemPosition::Stretch;
for (auto& flexItem : childrenOfType<RenderBox>(*this)) {
// Flex items that were previously stretching need to be relayed out so we
// can compute new available cross axis space. This is only necessary for
// stretching since other alignment values don't change the size of the
// box.
if (oldStyleAlignItemsIsStretch) {
ItemPosition previousAlignment = flexItem.style().resolvedAlignSelf(oldStyle, selfAlignmentNormalBehavior()).position();
if (previousAlignment == ItemPosition::Stretch && previousAlignment != flexItem.style().resolvedAlignSelf(&style(), selfAlignmentNormalBehavior()).position())
flexItem.setChildNeedsLayout(MarkOnlyThis);
}
}
}
bool RenderFlexibleBox::hitTestChildren(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& adjustedLocation, HitTestAction hitTestAction)
{
if (hitTestAction != HitTestForeground)
return false;
LayoutPoint scrolledOffset = hasNonVisibleOverflow() ? adjustedLocation - toLayoutSize(scrollPosition()) : adjustedLocation;
// If collecting the children in reverse order is bad for performance, this Vector could be determined at layout time.
Vector<RenderBox*> reversedOrderIteratorForHitTesting;
for (auto* flexItem = m_orderIterator.first(); flexItem; flexItem = m_orderIterator.next()) {
if (flexItem->isOutOfFlowPositioned())
continue;
reversedOrderIteratorForHitTesting.append(flexItem);
}
reversedOrderIteratorForHitTesting.reverse();
for (auto* flexItem : reversedOrderIteratorForHitTesting) {
if (flexItem->hasSelfPaintingLayer())
continue;
auto location = flipForWritingModeForChild(*flexItem, scrolledOffset);
if (flexItem->hitTest(request, result, locationInContainer, location)) {
updateHitTestResult(result, flipForWritingMode(toLayoutPoint(locationInContainer.point() - adjustedLocation)));
return true;
}
}
return false;
}
void RenderFlexibleBox::layoutBlock(RelayoutChildren relayoutChildren, LayoutUnit)
{
ASSERT(needsLayout());
if (relayoutChildren == RelayoutChildren::No) {
auto simplifiedLayoutScope = SetForScope(m_inSimplifiedLayout, true);
if (simplifiedLayout())
return;
}
LayoutRepainter repainter(*this);
resetLogicalHeightBeforeLayoutIfNeeded();
m_relaidOutFlexItems.clear();
bool oldInLayout = m_inLayout;
m_inLayout = true;
if (!style().marginTrim().isEmpty())
initializeMarginTrimState();
if (recomputeLogicalWidth())
relayoutChildren = RelayoutChildren::Yes;
LayoutUnit previousHeight = logicalHeight();
setLogicalHeight(borderAndPaddingLogicalHeight() + scrollbarLogicalHeight());
{
LayoutStateMaintainer statePusher(*this, locationOffset(), isTransformed() || hasReflection() || writingMode().isBlockFlipped());
preparePaginationBeforeBlockLayout(relayoutChildren);
m_numberOfFlexItemsOnFirstLine = { };
m_numberOfFlexItemsOnLastLine = { };
m_justifyContentStartOverflow = 0;
beginUpdateScrollInfoAfterLayoutTransaction();
prepareOrderIteratorAndMargins();
// Fieldsets need to find their legend and position it inside the border of the object.
// The legend then gets skipped during normal layout. The same is true for ruby text.
// It doesn't get included in the normal layout process but is instead skipped.
layoutExcludedChildren(relayoutChildren);
FlexItemFrameRects oldFlexItemRects;
appendFlexItemFrameRects(oldFlexItemRects);
performFlexLayout(relayoutChildren);
{
auto scrollbarLayout = SetForScope(m_inPostFlexUpdateScrollbarLayout, true);
endAndCommitUpdateScrollInfoAfterLayoutTransaction();
}
if (logicalHeight() != previousHeight)
relayoutChildren = RelayoutChildren::Yes;
if (isDocumentElementRenderer())
layoutPositionedObjects(RelayoutChildren::Yes);
else
layoutPositionedObjects(relayoutChildren);
repaintFlexItemsDuringLayoutIfMoved(oldFlexItemRects);
// FIXME: css3/flexbox/repaint-rtl-column.html seems to repaint more overflow than it needs to.
computeOverflow(layoutOverflowLogicalBottom(*this));
updateDescendantTransformsAfterLayout();
}
updateLayerTransform();
// We have to reset this, because changes to our ancestors' style can affect
// this value. Also, this needs to be before we call updateAfterLayout, as
// that function may re-enter this one.
resetHasDefiniteHeight();
// Update our scroll information if we're overflow:auto/scroll/hidden now that we know if we overflow or not.
updateScrollInfoAfterLayout();
repainter.repaintAfterLayout();
clearNeedsLayout();
m_inLayout = oldInLayout;
}
void RenderFlexibleBox::appendFlexItemFrameRects(FlexItemFrameRects& flexItemFrameRects)
{
for (RenderBox* flexItem = m_orderIterator.first(); flexItem; flexItem = m_orderIterator.next()) {
if (!flexItem->isOutOfFlowPositioned())
flexItemFrameRects.append(flexItem->frameRect());
}
}
void RenderFlexibleBox::repaintFlexItemsDuringLayoutIfMoved(const FlexItemFrameRects& oldFlexItemRects)
{
size_t index = 0;
for (RenderBox* flexItem = m_orderIterator.first(); flexItem; flexItem = m_orderIterator.next()) {
if (flexItem->isOutOfFlowPositioned())
continue;
// If the child moved, we have to repaint it as well as any floating/positioned
// descendants. An exception is if we need a layout. In this case, we know we're going to
// repaint ourselves (and the child) anyway.
if (!selfNeedsLayout() && flexItem->checkForRepaintDuringLayout())
flexItem->repaintDuringLayoutIfMoved(oldFlexItemRects[index]);
++index;
}
ASSERT(index == oldFlexItemRects.size());
}
void RenderFlexibleBox::paintChildren(PaintInfo& paintInfo, const LayoutPoint& paintOffset, PaintInfo& paintInfoForFlexItem, bool usePrintRect)
{
for (RenderBox* flexItem = m_orderIterator.first(); flexItem; flexItem = m_orderIterator.next()) {
if (!paintChild(*flexItem, paintInfo, paintOffset, paintInfoForFlexItem, usePrintRect, PaintAsInlineBlock))
return;
}
}
void RenderFlexibleBox::repositionLogicalHeightDependentFlexItems(FlexLineStates& lineStates, LayoutUnit gapBetweenLines)
{
auto flexLayoutScope = SetForScope(m_inCrossAxisLayout, true);
LayoutUnit crossAxisStartEdge = lineStates.isEmpty() ? 0_lu : lineStates[0].crossAxisOffset;
// If we have a single line flexbox, the line height is all the available space. For flex-direction: row,
// this means we need to use the height, so we do this after calling updateLogicalHeight.
if (!isMultiline() && !lineStates.isEmpty())
lineStates[0].crossAxisExtent = crossAxisContentExtent();
alignFlexLines(lineStates, gapBetweenLines);
alignFlexItems(lineStates);
if (style().flexWrap() == FlexWrap::Reverse)
flipForWrapReverse(lineStates, crossAxisStartEdge);
// direction:rtl + flex-direction:column means the cross-axis direction is
// flipped.
flipForRightToLeftColumn(lineStates);
}
bool RenderFlexibleBox::mainAxisIsFlexItemInlineAxis(const RenderBox& flexItem) const
{
return isHorizontalFlow() == flexItem.isHorizontalWritingMode();
}
bool RenderFlexibleBox::isColumnFlow() const
{
return style().isColumnFlexDirection();
}
bool RenderFlexibleBox::isColumnOrRowReverse() const
{
return style().flexDirection() == FlexDirection::ColumnReverse || style().flexDirection() == FlexDirection::RowReverse;
}
bool RenderFlexibleBox::isHorizontalFlow() const
{
if (isHorizontalWritingMode())
return !isColumnFlow();
return isColumnFlow();
}
bool RenderFlexibleBox::isLeftToRightFlow() const
{
if (isColumnFlow())
return writingMode().blockDirection() == FlowDirection::TopToBottom || writingMode().blockDirection() == FlowDirection::LeftToRight;
return writingMode().isLogicalLeftInlineStart() ^ (style().flexDirection() == FlexDirection::RowReverse);
}
bool RenderFlexibleBox::isMultiline() const
{
return style().flexWrap() != FlexWrap::NoWrap;
}
// https://drafts.csswg.org/css-flexbox/#min-size-auto
bool RenderFlexibleBox::shouldApplyMinSizeAutoForFlexItem(const RenderBox& flexItem) const
{
auto minSize = mainSizeLengthForFlexItem(RenderBox::SizeType::MinSize, flexItem);
// min, max and fit-content are equivalent to the automatic size for block sizes https://drafts.csswg.org/css-sizing-3/#valdef-width-min-content.
bool flexItemBlockSizeIsEquivalentToAutomaticSize = !mainAxisIsFlexItemInlineAxis(flexItem) && (minSize.isMinContent() || minSize.isMaxContent() || minSize.isFitContent());
return (minSize.isAuto() || flexItemBlockSizeIsEquivalentToAutomaticSize) && (mainAxisOverflowForFlexItem(flexItem) == Overflow::Visible);
}
bool RenderFlexibleBox::shouldApplyMinBlockSizeAutoForFlexItem(const RenderBox& flexItem) const
{
return !mainAxisIsFlexItemInlineAxis(flexItem) && shouldApplyMinSizeAutoForFlexItem(flexItem);
}
Length RenderFlexibleBox::flexBasisForFlexItem(const RenderBox& flexItem) const
{
Length flexLength = flexItem.style().flexBasis();
if (flexLength.isAuto())
flexLength = mainSizeLengthForFlexItem(RenderBox::SizeType::MainOrPreferredSize, flexItem);
return flexLength;
}
LayoutUnit RenderFlexibleBox::crossAxisExtentForFlexItem(const RenderBox& flexItem) const
{
return isHorizontalFlow() ? flexItem.height() : flexItem.width();
}
LayoutUnit RenderFlexibleBox::cachedFlexItemIntrinsicContentLogicalHeight(const RenderBox& flexItem) const
{
if (auto* renderReplaced = dynamicDowncast<RenderReplaced>(flexItem))
return renderReplaced->intrinsicLogicalHeight();
if (m_intrinsicContentLogicalHeights.contains(flexItem))
return m_intrinsicContentLogicalHeights.get(flexItem);
return flexItem.contentBoxLogicalHeight();
}
void RenderFlexibleBox::setCachedFlexItemIntrinsicContentLogicalHeight(const RenderBox& flexItem, LayoutUnit height)
{
if (flexItem.isRenderReplaced())
return; // Replaced elements know their intrinsic height already, so save space by not caching.
m_intrinsicContentLogicalHeights.set(flexItem, height);
}
void RenderFlexibleBox::clearCachedFlexItemIntrinsicContentLogicalHeight(const RenderBox& flexItem)
{
if (flexItem.isRenderReplaced())
return; // Replaced elements know their intrinsic height already, so nothing to do.
m_intrinsicContentLogicalHeights.remove(flexItem);
}
LayoutUnit RenderFlexibleBox::flexItemIntrinsicLogicalHeight(RenderBox& flexItem) const
{
// This should only be called if the logical height is the cross size
ASSERT(mainAxisIsFlexItemInlineAxis(flexItem));
if (needToStretchFlexItemLogicalHeight(flexItem)) {
LayoutUnit flexItemContentHeight = cachedFlexItemIntrinsicContentLogicalHeight(flexItem);
LayoutUnit flexItemLogicalHeight = flexItemContentHeight + flexItem.scrollbarLogicalHeight() + flexItem.borderAndPaddingLogicalHeight();
return flexItem.constrainLogicalHeightByMinMax(flexItemLogicalHeight, flexItemContentHeight);
}
return flexItem.logicalHeight();
}
LayoutUnit RenderFlexibleBox::flexItemIntrinsicLogicalWidth(RenderBox& flexItem)
{
// This should only be called if the logical width is the cross size
ASSERT(!mainAxisIsFlexItemInlineAxis(flexItem));
if (flexItemCrossSizeIsDefinite(flexItem, flexItem.style().logicalWidth()))
return flexItem.logicalWidth();
LogicalExtentComputedValues values;
{
OverridingSizesScope cleanOverridingWidthScope(flexItem, OverridingSizesScope::Axis::Inline);
flexItem.computeLogicalWidth(values);
}
return values.m_extent;
}
LayoutUnit RenderFlexibleBox::crossAxisIntrinsicExtentForFlexItem(RenderBox& flexItem)
{
return mainAxisIsFlexItemInlineAxis(flexItem) ? flexItemIntrinsicLogicalHeight(flexItem) : flexItemIntrinsicLogicalWidth(flexItem);
}
LayoutUnit RenderFlexibleBox::mainAxisExtentForFlexItem(const RenderBox& flexItem) const
{
return isHorizontalFlow() ? flexItem.size().width() : flexItem.size().height();
}
LayoutUnit RenderFlexibleBox::mainAxisContentExtentForFlexItemIncludingScrollbar(const RenderBox& flexItem) const
{
return isHorizontalFlow() ? flexItem.contentBoxWidth() + flexItem.verticalScrollbarWidth() : flexItem.contentBoxHeight() + flexItem.horizontalScrollbarHeight();
}
LayoutUnit RenderFlexibleBox::crossAxisExtent() const
{
return isHorizontalFlow() ? size().height() : size().width();
}
LayoutUnit RenderFlexibleBox::mainAxisExtent() const
{
return isHorizontalFlow() ? size().width() : size().height();
}
LayoutUnit RenderFlexibleBox::crossAxisContentExtent() const
{
return isHorizontalFlow() ? contentBoxHeight() : contentBoxWidth();
}
LayoutUnit RenderFlexibleBox::mainAxisContentExtent(LayoutUnit contentLogicalHeight)
{
if (!isColumnFlow())
return contentBoxLogicalWidth();
LayoutUnit borderPaddingAndScrollbar = borderAndPaddingLogicalHeight() + scrollbarLogicalHeight();
LayoutUnit borderBoxLogicalHeight = contentLogicalHeight + borderPaddingAndScrollbar;
auto computedValues = computeLogicalHeight(borderBoxLogicalHeight, logicalTop());
if (computedValues.m_extent == LayoutUnit::max())
return computedValues.m_extent;
return std::max(0_lu, computedValues.m_extent - borderPaddingAndScrollbar);
}
// FIXME: consider adding this check to RenderBox::hasIntrinsicAspectRatio(). We could even make it
// virtual returning false by default. RenderReplaced will overwrite it with the current implementation
// plus this extra check. See wkb.ug/231955.
static bool isSVGRootWithIntrinsicAspectRatio(const RenderBox& flexItem)
{
if (!flexItem.isRenderOrLegacyRenderSVGRoot())
return false;
// It's common for some replaced elements, such as SVGs, to have intrinsic aspect ratios but no intrinsic sizes.
// That's why it isn't enough just to check for intrinsic sizes in those cases.
return downcast<RenderReplaced>(flexItem).computeIntrinsicAspectRatio() > 0;
};
static bool flexItemHasAspectRatio(const RenderBox& flexItem)
{
return flexItem.hasIntrinsicAspectRatio() || flexItem.style().hasAspectRatio() || isSVGRootWithIntrinsicAspectRatio(flexItem);
}
std::optional<LayoutUnit> RenderFlexibleBox::computeMainAxisExtentForFlexItem(RenderBox& flexItem, RenderBox::SizeType sizeType, const Length& size)
{
// If we have a horizontal flow, that means the main size is the width.
// That's the logical width for horizontal writing modes, and the logical
// height in vertical writing modes. For a vertical flow, main size is the
// height, so it's the inverse. So we need the logical width if we have a
// horizontal flow and horizontal writing mode, or vertical flow and vertical
// writing mode. Otherwise we need the logical height.
if (!mainAxisIsFlexItemInlineAxis(flexItem)) {
// We don't have to check for "auto" here - computeContentLogicalHeight
// will just return a null Optional for that case anyway. It's safe to access
// scrollbarLogicalHeight here because ComputeNextFlexLine will have
// already forced layout on the child. We previously did a layout out the child
// if necessary (see ComputeNextFlexLine and the call to
// flexItemHasIntrinsicMainAxisSize) so we can be sure that the two height
// calls here will return up-to-date data.
std::optional<LayoutUnit> height = flexItem.computeContentLogicalHeight(sizeType, size, cachedFlexItemIntrinsicContentLogicalHeight(flexItem));
if (!height)
return height;
// Tables interpret overriding sizes as the size of captions + rows. However the specified height of a table
// only includes the size of the rows. That's why we need to add the size of the captions here so that the table
// layout algorithm behaves appropiately.
LayoutUnit captionsHeight;
if (CheckedPtr table = dynamicDowncast<RenderTable>(flexItem); table && flexItemMainSizeIsDefinite(flexItem, size))
captionsHeight = table->sumCaptionsLogicalHeight();
return *height + flexItem.scrollbarLogicalHeight() + captionsHeight;
}
// computeLogicalWidth always re-computes the intrinsic widths. However, when
// our logical width is auto, we can just use our cached value. So let's do
// that here. (Compare code in RenderBlock::computePreferredLogicalWidths)
if (flexItem.style().logicalWidth().isAuto() && !flexItemHasAspectRatio(flexItem)) {
if (size.isMinContent()) {
if (flexItem.needsPreferredWidthsRecalculation())
flexItem.setPreferredLogicalWidthsDirty(true, MarkOnlyThis);
return flexItem.minPreferredLogicalWidth() - flexItem.borderAndPaddingLogicalWidth();
}
if (size.isMaxContent()) {
if (flexItem.needsPreferredWidthsRecalculation())
flexItem.setPreferredLogicalWidthsDirty(true, MarkOnlyThis);
return flexItem.maxPreferredLogicalWidth() - flexItem.borderAndPaddingLogicalWidth();
}
}
auto mainAxisWidth = isColumnFlow() ? availableLogicalHeight(AvailableLogicalHeightType::ExcludeMarginBorderPadding) : contentBoxLogicalWidth();
return flexItem.computeLogicalWidthUsing(sizeType, size, mainAxisWidth, *this) - flexItem.borderAndPaddingLogicalWidth();
}
FlowDirection RenderFlexibleBox::transformedBlockFlowDirection() const
{
if (!isColumnFlow())
return writingMode().blockDirection();
return writingMode().inlineDirection();
}
LayoutUnit RenderFlexibleBox::flowAwareBorderStart() const
{
if (isHorizontalFlow())
return isLeftToRightFlow() ? borderLeft() : borderRight();
return isLeftToRightFlow() ? borderTop() : borderBottom();
}
LayoutUnit RenderFlexibleBox::flowAwareBorderEnd() const
{
if (isHorizontalFlow())
return isLeftToRightFlow() ? borderRight() : borderLeft();
return isLeftToRightFlow() ? borderBottom() : borderTop();
}
LayoutUnit RenderFlexibleBox::flowAwareBorderBefore() const
{
switch (transformedBlockFlowDirection()) {
case FlowDirection::TopToBottom:
return borderTop();
case FlowDirection::BottomToTop:
return borderBottom();
case FlowDirection::LeftToRight:
return borderLeft();
case FlowDirection::RightToLeft:
return borderRight();
}
ASSERT_NOT_REACHED();
return borderTop();
}
LayoutUnit RenderFlexibleBox::flowAwareBorderAfter() const
{
switch (transformedBlockFlowDirection()) {
case FlowDirection::TopToBottom:
return borderBottom();
case FlowDirection::BottomToTop:
return borderTop();
case FlowDirection::LeftToRight:
return borderRight();
case FlowDirection::RightToLeft:
return borderLeft();
}
ASSERT_NOT_REACHED();
return borderTop();
}
LayoutUnit RenderFlexibleBox::flowAwarePaddingStart() const
{
if (isHorizontalFlow())
return isLeftToRightFlow() ? paddingLeft() : paddingRight();
return isLeftToRightFlow() ? paddingTop() : paddingBottom();
}
LayoutUnit RenderFlexibleBox::flowAwarePaddingEnd() const
{
if (isHorizontalFlow())
return isLeftToRightFlow() ? paddingRight() : paddingLeft();
return isLeftToRightFlow() ? paddingBottom() : paddingTop();
}
LayoutUnit RenderFlexibleBox::flowAwarePaddingBefore() const
{
switch (transformedBlockFlowDirection()) {
case FlowDirection::TopToBottom:
return paddingTop();
case FlowDirection::BottomToTop:
return paddingBottom();
case FlowDirection::LeftToRight:
return paddingLeft();
case FlowDirection::RightToLeft:
return paddingRight();
}
ASSERT_NOT_REACHED();
return paddingTop();
}
LayoutUnit RenderFlexibleBox::flowAwarePaddingAfter() const
{
switch (transformedBlockFlowDirection()) {
case FlowDirection::TopToBottom:
return paddingBottom();
case FlowDirection::BottomToTop:
return paddingTop();
case FlowDirection::LeftToRight:
return paddingRight();
case FlowDirection::RightToLeft:
return paddingLeft();
}
ASSERT_NOT_REACHED();
return paddingTop();
}
LayoutUnit RenderFlexibleBox::flowAwareMarginStartForFlexItem(const RenderBox& flexItem) const
{
if (isHorizontalFlow())
return isLeftToRightFlow() ? flexItem.marginLeft() : flexItem.marginRight();
return isLeftToRightFlow() ? flexItem.marginTop() : flexItem.marginBottom();
}
LayoutUnit RenderFlexibleBox::flowAwareMarginEndForFlexItem(const RenderBox& flexItem) const
{
if (isHorizontalFlow())
return isLeftToRightFlow() ? flexItem.marginRight() : flexItem.marginLeft();
return isLeftToRightFlow() ? flexItem.marginBottom() : flexItem.marginTop();
}
LayoutUnit RenderFlexibleBox::flowAwareMarginBeforeForFlexItem(const RenderBox& flexItem) const
{
switch (transformedBlockFlowDirection()) {
case FlowDirection::TopToBottom:
return flexItem.marginTop();
case FlowDirection::BottomToTop:
return flexItem.marginBottom();
case FlowDirection::LeftToRight:
return flexItem.marginLeft();
case FlowDirection::RightToLeft:
return flexItem.marginRight();
}
ASSERT_NOT_REACHED();
return marginTop();
}
void RenderFlexibleBox::initializeMarginTrimState()
{
// When computeIntrinsicLogicalWidth goes through each of the children, it
// will include the margins when computing the flexbox's min and max widths.
// We need to trim the margins of the first and last child early so that
// these margins do not incorrectly constribute to the box's min/max width
auto marginTrim = style().marginTrim();
auto isRowsFlexbox = isHorizontalFlow();
if (auto flexItem = firstInFlowChildBox(); flexItem && marginTrim.contains(MarginTrimType::InlineStart))
isRowsFlexbox ? m_marginTrimItems.m_itemsAtFlexLineStart.add(*flexItem) : m_marginTrimItems.m_itemsOnFirstFlexLine.add(*flexItem);
if (auto flexItem = lastInFlowChildBox(); flexItem && marginTrim.contains(MarginTrimType::InlineEnd))
isRowsFlexbox ? m_marginTrimItems.m_itemsAtFlexLineEnd.add(*flexItem) : m_marginTrimItems.m_itemsOnLastFlexLine.add(*flexItem);
}
LayoutUnit RenderFlexibleBox::mainAxisMarginExtentForFlexItem(const RenderBox& flexItem) const
{
if (!flexItem.needsLayout())
return isHorizontalFlow() ? flexItem.horizontalMarginExtent() : flexItem.verticalMarginExtent();
LayoutUnit marginStart;
LayoutUnit marginEnd;
if (isHorizontalFlow())
flexItem.computeInlineDirectionMargins(*this, flexItem.containingBlockLogicalWidthForContent(), flexItem.logicalWidth(), { }, marginStart, marginEnd);
else
flexItem.computeBlockDirectionMargins(*this, marginStart, marginEnd);
return marginStart + marginEnd;
}
LayoutUnit RenderFlexibleBox::crossAxisMarginExtentForFlexItem(const RenderBox& flexItem) const
{
if (!flexItem.needsLayout())
return isHorizontalFlow() ? flexItem.verticalMarginExtent() : flexItem.horizontalMarginExtent();
LayoutUnit marginStart;
LayoutUnit marginEnd;
if (isHorizontalFlow())
flexItem.computeBlockDirectionMargins(*this, marginStart, marginEnd);
else
flexItem.computeInlineDirectionMargins(*this, flexItem.containingBlockLogicalWidthForContent(), flexItem.logicalWidth(), { }, marginStart, marginEnd);
return marginStart + marginEnd;
}
bool RenderFlexibleBox::isChildEligibleForMarginTrim(MarginTrimType marginTrimType, const RenderBox& flexItem) const
{
ASSERT(style().marginTrim().contains(marginTrimType));
auto isMarginParallelWithMainAxis = [this](MarginTrimType marginTrimType) {
if (isHorizontalFlow())
return marginTrimType == MarginTrimType::BlockStart || marginTrimType == MarginTrimType::BlockEnd;
return marginTrimType == MarginTrimType::InlineStart || marginTrimType == MarginTrimType::InlineEnd;
};
if (isMarginParallelWithMainAxis(marginTrimType))
return (marginTrimType == MarginTrimType::BlockStart || marginTrimType == MarginTrimType::InlineStart) ? m_marginTrimItems.m_itemsOnFirstFlexLine.contains(flexItem) : m_marginTrimItems.m_itemsOnLastFlexLine.contains(flexItem);
return (marginTrimType == MarginTrimType::BlockStart || marginTrimType == MarginTrimType::InlineStart) ? m_marginTrimItems.m_itemsAtFlexLineStart.contains(flexItem) : m_marginTrimItems.m_itemsAtFlexLineEnd.contains(flexItem);
}
bool RenderFlexibleBox::shouldTrimMainAxisMarginStart() const
{
if (isHorizontalFlow())
return style().marginTrim().contains(MarginTrimType::InlineStart);
return style().marginTrim().contains(MarginTrimType::BlockStart);
}
bool RenderFlexibleBox::shouldTrimMainAxisMarginEnd() const
{
if (isHorizontalFlow())
return style().marginTrim().contains(MarginTrimType::InlineEnd);
return style().marginTrim().contains(MarginTrimType::BlockEnd);
}
bool RenderFlexibleBox::shouldTrimCrossAxisMarginStart() const
{
if (isHorizontalFlow())
return style().marginTrim().contains(MarginTrimType::BlockStart);
return style().marginTrim().contains(MarginTrimType::InlineStart);
}
bool RenderFlexibleBox::shouldTrimCrossAxisMarginEnd() const
{
if (isHorizontalFlow())
return style().marginTrim().contains(MarginTrimType::BlockEnd);
return style().marginTrim().contains(MarginTrimType::InlineEnd);
}
void RenderFlexibleBox::trimMainAxisMarginStart(const FlexLayoutItem& flexLayoutItem)
{
auto horizontalFlow = isHorizontalFlow();
flexLayoutItem.mainAxisMargin -= horizontalFlow
? flexLayoutItem.renderer->marginStart(writingMode())
: flexLayoutItem.renderer->marginBefore(writingMode());
if (horizontalFlow)
setTrimmedMarginForChild(flexLayoutItem.renderer, MarginTrimType::InlineStart);
else
setTrimmedMarginForChild(flexLayoutItem.renderer, MarginTrimType::BlockStart);
m_marginTrimItems.m_itemsAtFlexLineStart.add(flexLayoutItem.renderer);
}
void RenderFlexibleBox::trimMainAxisMarginEnd(const FlexLayoutItem& flexLayoutItem)
{
auto horizontalFlow = isHorizontalFlow();
flexLayoutItem.mainAxisMargin -= horizontalFlow
? flexLayoutItem.renderer->marginEnd(writingMode())
: flexLayoutItem.renderer->marginAfter(writingMode());
if (horizontalFlow)
setTrimmedMarginForChild(flexLayoutItem.renderer, MarginTrimType::InlineEnd);
else
setTrimmedMarginForChild(flexLayoutItem.renderer, MarginTrimType::BlockEnd);
m_marginTrimItems.m_itemsAtFlexLineEnd.add(flexLayoutItem.renderer);
}
void RenderFlexibleBox::trimCrossAxisMarginStart(const FlexLayoutItem& flexLayoutItem)
{
if (isHorizontalFlow())
setTrimmedMarginForChild(flexLayoutItem.renderer, MarginTrimType::BlockStart);
else
setTrimmedMarginForChild(flexLayoutItem.renderer, MarginTrimType::InlineStart);
m_marginTrimItems.m_itemsOnFirstFlexLine.add(flexLayoutItem.renderer);
}
void RenderFlexibleBox::trimCrossAxisMarginEnd(const FlexLayoutItem& flexLayoutItem)
{
if (isHorizontalFlow())
setTrimmedMarginForChild(flexLayoutItem.renderer, MarginTrimType::BlockEnd);
else
setTrimmedMarginForChild(flexLayoutItem.renderer, MarginTrimType::InlineEnd);
m_marginTrimItems.m_itemsOnLastFlexLine.add(flexLayoutItem.renderer);
}
LayoutUnit RenderFlexibleBox::crossAxisScrollbarExtent() const
{
return isHorizontalFlow() ? horizontalScrollbarHeight() : verticalScrollbarWidth();
}
LayoutPoint RenderFlexibleBox::flowAwareLocationForFlexItem(const RenderBox& flexItem) const
{
return isHorizontalFlow() ? flexItem.location() : flexItem.location().transposedPoint();
}
Length RenderFlexibleBox::crossSizeLengthForFlexItem(RenderBox::SizeType sizeType, const RenderBox& flexItem) const
{
switch (sizeType) {
case RenderBox::SizeType::MinSize:
return isHorizontalFlow() ? flexItem.style().minHeight() : flexItem.style().minWidth();
case RenderBox::SizeType::MainOrPreferredSize:
return isHorizontalFlow() ? flexItem.style().height() : flexItem.style().width();
case RenderBox::SizeType::MaxSize:
return isHorizontalFlow() ? flexItem.style().maxHeight() : flexItem.style().maxWidth();
}
ASSERT_NOT_REACHED();
return { };
}
Length RenderFlexibleBox::mainSizeLengthForFlexItem(RenderBox::SizeType sizeType, const RenderBox& flexItem) const
{
switch (sizeType) {
case RenderBox::SizeType::MinSize:
return isHorizontalFlow() ? flexItem.style().minWidth() : flexItem.style().minHeight();
case RenderBox::SizeType::MainOrPreferredSize:
return isHorizontalFlow() ? flexItem.style().width() : flexItem.style().height();
case RenderBox::SizeType::MaxSize:
return isHorizontalFlow() ? flexItem.style().maxWidth() : flexItem.style().maxHeight();
}
ASSERT_NOT_REACHED();
return { };
}
// FIXME: computeMainSizeFromAspectRatioUsing may need to return an std::optional<LayoutUnit> in the future
// rather than returning indefinite sizes as 0/-1.
LayoutUnit RenderFlexibleBox::computeMainSizeFromAspectRatioUsing(const RenderBox& flexItem, Length crossSizeLength) const
{
ASSERT(flexItemHasAspectRatio(flexItem));
auto adjustForBoxSizing = [this] (const RenderBox& box, LayoutUnit value) -> LayoutUnit {
// We need to substract the border and padding extent from the cross axis.
// Furthermore, the sizing calculations that floor the content box size at zero when applying box-sizing are also ignored.
// https://drafts.csswg.org/css-flexbox/#algo-main-item.
if (box.style().boxSizing() == BoxSizing::BorderBox)
value -= isHorizontalFlow() ? box.verticalBorderAndPaddingExtent() : box.horizontalBorderAndPaddingExtent();
return value;
};
LayoutUnit crossSize;
// crossSize is border-box size if box-sizing is border-box, and content-box otherwise.
if (crossSizeLength.isFixed())
crossSize = LayoutUnit(crossSizeLength.value());
else if (crossSizeLength.isAuto()) {
ASSERT(flexItemCrossSizeShouldUseContainerCrossSize(flexItem));
crossSize = computeCrossSizeForFlexItemUsingContainerCrossSize(flexItem);
} else {
ASSERT(crossSizeLength.isPercentOrCalculated());
auto flexItemSize = mainAxisIsFlexItemInlineAxis(flexItem) ? flexItem.computePercentageLogicalHeight(crossSizeLength) : adjustBorderBoxLogicalWidthForBoxSizing(valueForLength(crossSizeLength, contentBoxWidth()), crossSizeLength.type());
if (!flexItemSize)
return 0_lu;
crossSize = flexItemSize.value();
}
auto flexItemIntrinsicSize = flexItem.intrinsicSize();
auto preferredAspectRatio = [&] {
if (flexItem.isRenderOrLegacyRenderSVGRoot())
return downcast<RenderReplaced>(flexItem).computeIntrinsicAspectRatio();
if (flexItem.style().aspectRatioType() == AspectRatioType::Ratio || (flexItem.style().aspectRatioType() == AspectRatioType::AutoAndRatio && flexItemIntrinsicSize.isEmpty()))
return flexItem.style().aspectRatioWidth() / flexItem.style().aspectRatioHeight();
if (auto* replacedElement = dynamicDowncast<RenderReplaced>(flexItem))
return replacedElement->computeIntrinsicAspectRatio();
ASSERT(flexItemIntrinsicSize.height());
return flexItemIntrinsicSize.width().toDouble() / flexItemIntrinsicSize.height().toDouble();
};
LayoutUnit borderAndPadding;
if (flexItem.style().aspectRatioType() == AspectRatioType::Ratio || (flexItem.style().aspectRatioType() == AspectRatioType::AutoAndRatio && flexItemIntrinsicSize.isEmpty())) {
if (flexItem.style().boxSizingForAspectRatio() == BoxSizing::ContentBox)
crossSize -= isHorizontalFlow() ? flexItem.verticalBorderAndPaddingExtent() : flexItem.horizontalBorderAndPaddingExtent();
else
borderAndPadding = isHorizontalFlow() ? flexItem.horizontalBorderAndPaddingExtent() : flexItem.verticalBorderAndPaddingExtent();
} else
crossSize = adjustForBoxSizing(flexItem, crossSize);
if (isHorizontalFlow())
return std::max(0_lu, LayoutUnit(crossSize * preferredAspectRatio()) - borderAndPadding);
return std::max(0_lu, LayoutUnit(crossSize / preferredAspectRatio()) - borderAndPadding);
}
void RenderFlexibleBox::setFlowAwareLocationForFlexItem(RenderBox& flexItem, const LayoutPoint& location)
{
if (isHorizontalFlow())
flexItem.setLocation(location);
else
flexItem.setLocation(location.transposedPoint());
}
bool RenderFlexibleBox::canComputePercentageFlexBasis(const RenderBox& flexItem, const Length& flexBasis, UpdatePercentageHeightDescendants updateDescendants)
{
if (!isColumnFlow() || m_hasDefiniteHeight == SizeDefiniteness::Definite)
return true;
if (m_hasDefiniteHeight == SizeDefiniteness::Indefinite)
return false;
auto isPercentResolveSuspended = view().frameView().layoutContext().isPercentHeightResolveDisabledFor(flexItem);
ASSERT(!isPercentResolveSuspended || is<RenderBlock>(flexItem));
bool definite = !isPercentResolveSuspended && flexItem.computePercentageLogicalHeight(flexBasis, updateDescendants).has_value();
if (m_inLayout && (isHorizontalWritingMode() == flexItem.isHorizontalWritingMode())) {
// We can reach this code even while we're not laying ourselves out, such
// as from mainSizeForPercentageResolution.
m_hasDefiniteHeight = definite ? SizeDefiniteness::Definite : SizeDefiniteness::Indefinite;
}
return definite;
}
bool RenderFlexibleBox::flexItemMainSizeIsDefinite(const RenderBox& flexItem, const Length& flexBasis)
{
if (flexBasis.isAuto() || flexBasis.isContent())
return false;
if (!mainAxisIsFlexItemInlineAxis(flexItem) && (flexBasis.isIntrinsic() || flexBasis.type() == LengthType::Intrinsic))
return false;
if (flexBasis.isPercentOrCalculated())
return canComputePercentageFlexBasis(flexItem, flexBasis, UpdatePercentageHeightDescendants::No);
return true;
}
bool RenderFlexibleBox::flexItemHasComputableAspectRatio(const RenderBox& flexItem) const
{
if (!flexItemHasAspectRatio(flexItem))
return false;
return flexItem.intrinsicSize().height() || flexItem.style().hasAspectRatio() || isSVGRootWithIntrinsicAspectRatio(flexItem);
}
bool RenderFlexibleBox::flexItemHasComputableAspectRatioAndCrossSizeIsConsideredDefinite(const RenderBox& flexItem)
{
return flexItemHasComputableAspectRatio(flexItem)
&& (flexItemCrossSizeIsDefinite(flexItem, crossSizeLengthForFlexItem(RenderBox::SizeType::MainOrPreferredSize, flexItem)) || flexItemCrossSizeShouldUseContainerCrossSize(flexItem));
}
bool RenderFlexibleBox::flexItemCrossSizeShouldUseContainerCrossSize(const RenderBox& flexItem) const
{
// 9.8 https://drafts.csswg.org/css-flexbox/#definite-sizes
// 1. If a single-line flex container has a definite cross size, the automatic preferred outer cross size of any
// stretched flex items is the flex container's inner cross size (clamped to the flex item's min and max cross size)
// and is considered definite.
if (!isMultiline() && alignmentForFlexItem(flexItem) == ItemPosition::Stretch && !hasAutoMarginsInCrossAxis(flexItem) && crossSizeLengthForFlexItem(RenderBox::SizeType::MainOrPreferredSize, flexItem).isAuto()) {
if (isColumnFlow())
return true;
// This must be kept in sync with computeMainSizeFromAspectRatioUsing().
auto& crossSize = isHorizontalFlow() ? style().height() : style().width();
return crossSize.isFixed() || (crossSize.isPercent() && availableLogicalHeightForPercentageComputation());
}
return false;
}
bool RenderFlexibleBox::flexItemCrossSizeIsDefinite(const RenderBox& flexItem, const Length& length)
{
if (length.isAuto())
return false;
if (length.isPercentOrCalculated()) {
if (!mainAxisIsFlexItemInlineAxis(flexItem) || m_hasDefiniteHeight == SizeDefiniteness::Definite)
return true;
if (m_hasDefiniteHeight == SizeDefiniteness::Indefinite)
return false;
bool definite = bool(flexItem.computePercentageLogicalHeight(length));
m_hasDefiniteHeight = definite ? SizeDefiniteness::Definite : SizeDefiniteness::Indefinite;
return definite;
}
// FIXME: Eventually we should support other types of sizes here.
// Requires updating computeMainSizeFromAspectRatioUsing.
return length.isFixed();
}
void RenderFlexibleBox::cacheFlexItemMainSize(const RenderBox& flexItem)
{
ASSERT(!flexItem.needsLayout());
ASSERT(!mainAxisIsFlexItemInlineAxis(flexItem));
auto mainSize = [&] {
auto flexBasis = flexBasisForFlexItem(flexItem);
if (flexBasis.isPercentOrCalculated() && !flexItemMainSizeIsDefinite(flexItem, flexBasis))
return cachedFlexItemIntrinsicContentLogicalHeight(flexItem) + flexItem.borderAndPaddingLogicalHeight() + flexItem.scrollbarLogicalHeight();
return flexItem.logicalHeight();
};
m_intrinsicSizeAlongMainAxis.set(flexItem, mainSize());
m_relaidOutFlexItems.add(flexItem);
}
void RenderFlexibleBox::clearCachedMainSizeForFlexItem(const RenderBox& flexItem)
{
m_intrinsicSizeAlongMainAxis.remove(flexItem);
}
// This is a RAII class that is used to temporarily set the flex basis as the child size in the main axis.
class ScopedFlexBasisAsFlexItemMainSize {
public:
ScopedFlexBasisAsFlexItemMainSize(RenderBox& flexItem, Length flexBasis, bool mainAxisIsInlineAxis)
: m_flexItem(flexItem)
, m_mainAxisIsInlineAxis(mainAxisIsInlineAxis)
{
if (flexBasis.isAuto())
return;
if (m_mainAxisIsInlineAxis)
m_flexItem.setOverridingBorderBoxLogicalWidthForFlexBasisComputation(flexBasis);
else
m_flexItem.setOverridingBorderBoxLogicalHeightForFlexBasisComputation(flexBasis);
m_didOverride = true;
}
~ScopedFlexBasisAsFlexItemMainSize()
{
if (!m_didOverride)
return;
if (m_mainAxisIsInlineAxis)
m_flexItem.clearOverridingLogicalWidthForFlexBasisComputation();
else
m_flexItem.clearOverridingLogicalHeightForFlexBasisComputation();
}
private:
RenderBox& m_flexItem;
bool m_mainAxisIsInlineAxis { true };
bool m_didOverride { false };
};
// https://drafts.csswg.org/css-flexbox/#algo-main-item
LayoutUnit RenderFlexibleBox::computeFlexBaseSizeForFlexItem(RenderBox& flexItem, LayoutUnit mainAxisBorderAndPadding, RelayoutChildren relayoutChildren)
{
Length flexBasis = flexBasisForFlexItem(flexItem);
ScopedFlexBasisAsFlexItemMainSize scoped(flexItem, flexBasis.isContent() ? Length(LengthType::MaxContent) : flexBasis, mainAxisIsFlexItemInlineAxis(flexItem));
// FIXME: While we are supposed to ignore min/max here, clients of maybeCacheFlexItemMainIntrinsicSize may expect min/max constrained size.
SetForScope<bool> computingBaseSizesScope(m_isComputingFlexBaseSizes, true);
maybeCacheFlexItemMainIntrinsicSize(flexItem, relayoutChildren);
// 9.2.3 A.
if (flexItemMainSizeIsDefinite(flexItem, flexBasis))
return std::max(0_lu, computeMainAxisExtentForFlexItem(flexItem, RenderBox::SizeType::MainOrPreferredSize, flexBasis).value());
// 9.2.3 B.
if (flexItemHasComputableAspectRatioAndCrossSizeIsConsideredDefinite(flexItem)) {
const Length& crossSizeLength = crossSizeLengthForFlexItem(RenderBox::SizeType::MainOrPreferredSize, flexItem);
return adjustFlexItemSizeForAspectRatioCrossAxisMinAndMax(flexItem, computeMainSizeFromAspectRatioUsing(flexItem, crossSizeLength));
}
// FIXME: 9.2.3 C.
// FIXME: 9.2.3 D.
// 9.2.3 E.
LayoutUnit mainAxisExtent;
if (!mainAxisIsFlexItemInlineAxis(flexItem)) {
ASSERT(!flexItem.needsLayout());
ASSERT(m_intrinsicSizeAlongMainAxis.contains(flexItem));
mainAxisExtent = m_intrinsicSizeAlongMainAxis.get(flexItem);
} else {
// We don't need to add scrollbarLogicalWidth here because the preferred
// width includes the scrollbar, even for overflow: auto.
mainAxisExtent = flexItem.maxPreferredLogicalWidth();
}
return mainAxisExtent - mainAxisBorderAndPadding;
}
void RenderFlexibleBox::performFlexLayout(RelayoutChildren relayoutChildren)
{
if (layoutUsingFlexFormattingContext())
return;
// Set up our master list of flex items. All of the rest of the algorithm
// should work off this list of a subset.
// FIXME: That second part is not yet true.
FlexLayoutItems allItems;
for (auto* flexItem = m_orderIterator.first(); flexItem; flexItem = m_orderIterator.next()) {
if (m_orderIterator.shouldSkipChild(*flexItem)) {
// Out-of-flow children are not flex items, so we skip them here.
if (flexItem->isOutOfFlowPositioned())
prepareFlexItemForPositionedLayout(*flexItem);
continue;
}
allItems.append(constructFlexLayoutItem(*flexItem, relayoutChildren));
// constructFlexItem() might set the override containing block height so any value cached for definiteness might be incorrect.
resetHasDefiniteHeight();
}
if (allItems.isEmpty()) {
if (hasLineIfEmpty()) {
auto minHeight = borderAndPaddingLogicalHeight() + lineHeight(true, isHorizontalWritingMode() ? HorizontalLine : VerticalLine, PositionOfInteriorLineBoxes) + scrollbarLogicalHeight();
if (height() < minHeight)
setLogicalHeight(minHeight);
}
updateLogicalHeight();
return;
}
FlexLineStates lineStates;
LayoutUnit sumFlexBaseSize;
double totalFlexGrow;
double totalFlexShrink;
double totalWeightedFlexShrink;
LayoutUnit sumHypotheticalMainSize;
const LayoutUnit lineBreakLength = mainAxisContentExtent(LayoutUnit::max());
LayoutUnit gapBetweenItems = computeGap(GapType::BetweenItems);
LayoutUnit gapBetweenLines = computeGap(GapType::BetweenLines);
FlexLayoutAlgorithm flexAlgorithm(*this, lineBreakLength, allItems, gapBetweenItems, gapBetweenLines);
LayoutUnit crossAxisOffset = flowAwareBorderBefore() + flowAwarePaddingBefore();
FlexLayoutItems lineItems;
size_t nextIndex = 0;
size_t numLines = 0;
InspectorInstrumentation::flexibleBoxRendererBeganLayout(*this);
while (flexAlgorithm.computeNextFlexLine(nextIndex, lineItems, sumFlexBaseSize, totalFlexGrow, totalFlexShrink, totalWeightedFlexShrink, sumHypotheticalMainSize)) {
++numLines;
InspectorInstrumentation::flexibleBoxRendererWrappedToNextLine(*this, nextIndex);
// Cross axis margins should only be trimmed if they are on the first/last flex line
auto shouldTrimCrossAxisStart = shouldTrimCrossAxisMarginStart() && !lineStates.size();
auto shouldTrimCrossAxisEnd = shouldTrimCrossAxisMarginEnd() && allItems.last().renderer.ptr() == lineItems.last().renderer.ptr();
if (shouldTrimCrossAxisStart || shouldTrimCrossAxisEnd) {
for (auto& flexLayoutItem : lineItems) {
if (shouldTrimCrossAxisStart)
trimCrossAxisMarginStart(flexLayoutItem);
if (shouldTrimCrossAxisEnd)
trimCrossAxisMarginEnd(flexLayoutItem);
}
}
LayoutUnit containerMainInnerSize = mainAxisContentExtent(sumHypotheticalMainSize);
// availableFreeSpace is the initial amount of free space in this flexbox.
// remainingFreeSpace starts out at the same value but as we place and lay
// out flex items we subtract from it. Note that both values can be
// negative.
LayoutUnit remainingFreeSpace = containerMainInnerSize - sumFlexBaseSize;
FlexSign flexSign = (sumHypotheticalMainSize < containerMainInnerSize) ? FlexSign::PositiveFlexibility : FlexSign::NegativeFlexibility;
freezeInflexibleItems(flexSign, lineItems, remainingFreeSpace, totalFlexGrow, totalFlexShrink, totalWeightedFlexShrink);
// The initial free space gets calculated after freezing inflexible items.
// https://drafts.csswg.org/css-flexbox/#resolve-flexible-lengths step 3
const LayoutUnit initialFreeSpace = remainingFreeSpace;
while (!resolveFlexibleLengths(flexSign, lineItems, initialFreeSpace, remainingFreeSpace, totalFlexGrow, totalFlexShrink, totalWeightedFlexShrink)) {
ASSERT(totalFlexGrow >= 0);
ASSERT(totalWeightedFlexShrink >= 0);
}
// Recalculate the remaining free space. The adjustment for flex factors
// between 0..1 means we can't just use remainingFreeSpace here.
remainingFreeSpace = containerMainInnerSize;
for (size_t i = 0; i < lineItems.size(); ++i) {
auto& flexLayoutItem = lineItems[i];
ASSERT(!flexLayoutItem.renderer->isOutOfFlowPositioned());
remainingFreeSpace -= flexLayoutItem.flexedMarginBoxSize();
}
remainingFreeSpace -= (lineItems.size() - 1) * gapBetweenItems;
// This will std::move lineItems into a newly-created LineState.
layoutAndPlaceFlexItems(crossAxisOffset, lineItems, remainingFreeSpace, relayoutChildren, lineStates, gapBetweenItems);
}
if (!lineStates.isEmpty()) {
auto isWrapReverse = style().flexWrap() == FlexWrap::Reverse;
auto firstLineItemsCountInOriginalOrder = lineStates.first().flexLayoutItems.size();
auto lastLineItemsCountInOriginalOrder = lineStates.first().flexLayoutItems.size();
m_numberOfFlexItemsOnFirstLine = !isWrapReverse ? firstLineItemsCountInOriginalOrder : lastLineItemsCountInOriginalOrder;
m_numberOfFlexItemsOnLastLine = !isWrapReverse ? lastLineItemsCountInOriginalOrder : firstLineItemsCountInOriginalOrder;
}
if (hasLineIfEmpty()) {
// Even if computeNextFlexLine returns true, the flexbox might not have
// a line because all our children might be out of flow positioned.
// Instead of just checking if we have a line, make sure the flexbox
// has at least a line's worth of height to cover this case.
LayoutUnit minHeight = borderAndPaddingLogicalHeight() + lineHeight(true, isHorizontalWritingMode() ? HorizontalLine : VerticalLine, PositionOfInteriorLineBoxes) + scrollbarLogicalHeight();
if (size().height() < minHeight)
setLogicalHeight(minHeight);
}
if (!isColumnFlow() && numLines > 1)
setLogicalHeight(logicalHeight() + computeGap(GapType::BetweenLines) * (numLines - 1));
updateLogicalHeight();
repositionLogicalHeightDependentFlexItems(lineStates, gapBetweenLines);
}
LayoutUnit RenderFlexibleBox::autoMarginOffsetInMainAxis(const FlexLayoutItems& flexLayoutItems, LayoutUnit& availableFreeSpace)
{
if (availableFreeSpace <= 0_lu)
return 0_lu;
int numberOfAutoMargins = 0;
bool isHorizontal = isHorizontalFlow();
for (auto& flexLayoutItem : flexLayoutItems) {
auto& flexItemStyle = flexLayoutItem.style();
ASSERT(!flexLayoutItem.renderer->isOutOfFlowPositioned());
if (isHorizontal) {
if (flexItemStyle.marginLeft().isAuto())
++numberOfAutoMargins;
if (flexItemStyle.marginRight().isAuto())
++numberOfAutoMargins;
} else {
if (flexItemStyle.marginTop().isAuto())
++numberOfAutoMargins;
if (flexItemStyle.marginBottom().isAuto())
++numberOfAutoMargins;
}
}
if (!numberOfAutoMargins)
return 0_lu;
LayoutUnit sizeOfAutoMargin = availableFreeSpace / numberOfAutoMargins;
availableFreeSpace = 0_lu;
return sizeOfAutoMargin;
}
void RenderFlexibleBox::updateAutoMarginsInMainAxis(RenderBox& flexItem, LayoutUnit autoMarginOffset)
{
ASSERT(autoMarginOffset >= 0_lu);
if (isHorizontalFlow()) {
if (flexItem.style().marginLeft().isAuto())
flexItem.setMarginLeft(autoMarginOffset);
if (flexItem.style().marginRight().isAuto())
flexItem.setMarginRight(autoMarginOffset);
} else {
if (flexItem.style().marginTop().isAuto())
flexItem.setMarginTop(autoMarginOffset);
if (flexItem.style().marginBottom().isAuto())
flexItem.setMarginBottom(autoMarginOffset);
}
}
bool RenderFlexibleBox::hasAutoMarginsInCrossAxis(const RenderBox& flexItem) const
{
if (isHorizontalFlow())
return flexItem.style().marginTop().isAuto() || flexItem.style().marginBottom().isAuto();
return flexItem.style().marginLeft().isAuto() || flexItem.style().marginRight().isAuto();
}
LayoutUnit RenderFlexibleBox::availableAlignmentSpaceForFlexItem(LayoutUnit lineCrossAxisExtent, const RenderBox& flexItem)
{
LayoutUnit flexItemCrossExtent = crossAxisMarginExtentForFlexItem(flexItem) + crossAxisExtentForFlexItem(flexItem);
return lineCrossAxisExtent - flexItemCrossExtent;
}
bool RenderFlexibleBox::updateAutoMarginsInCrossAxis(RenderBox& flexItem, LayoutUnit availableAlignmentSpace)
{
ASSERT(!flexItem.isOutOfFlowPositioned());
ASSERT(availableAlignmentSpace >= 0_lu);
bool isHorizontal = isHorizontalFlow();
Length topOrLeft = isHorizontal ? flexItem.style().marginTop() : flexItem.style().marginLeft();
Length bottomOrRight = isHorizontal ? flexItem.style().marginBottom() : flexItem.style().marginRight();
if (topOrLeft.isAuto() && bottomOrRight.isAuto()) {
adjustAlignmentForFlexItem(flexItem, availableAlignmentSpace / 2);
if (isHorizontal) {
flexItem.setMarginTop(availableAlignmentSpace / 2);
flexItem.setMarginBottom(availableAlignmentSpace / 2);
} else {
flexItem.setMarginLeft(availableAlignmentSpace / 2);
flexItem.setMarginRight(availableAlignmentSpace / 2);
}
return true;
}
bool shouldAdjustTopOrLeft = true;
if (isColumnFlow() && flexItem.writingMode().isInlineFlipped()) {
// For column flows, only make this adjustment if topOrLeft corresponds to
// the "before" margin, so that flipForRightToLeftColumn will do the right
// thing.
shouldAdjustTopOrLeft = false;
}
if (!isColumnFlow() && flexItem.writingMode().isBlockFlipped()) {
// If we are a flipped writing mode, we need to adjust the opposite side.
// This is only needed for row flows because this only affects the
// block-direction axis.
shouldAdjustTopOrLeft = false;
}
if (topOrLeft.isAuto()) {
if (shouldAdjustTopOrLeft)
adjustAlignmentForFlexItem(flexItem, availableAlignmentSpace);
if (isHorizontal)
flexItem.setMarginTop(availableAlignmentSpace);
else
flexItem.setMarginLeft(availableAlignmentSpace);
return true;
}
if (bottomOrRight.isAuto()) {
if (!shouldAdjustTopOrLeft)
adjustAlignmentForFlexItem(flexItem, availableAlignmentSpace);
if (isHorizontal)
flexItem.setMarginBottom(availableAlignmentSpace);
else
flexItem.setMarginRight(availableAlignmentSpace);
return true;
}
return false;
}
LayoutUnit RenderFlexibleBox::marginBoxAscentForFlexItem(const RenderBox& flexItem)
{
auto isHorizontalFlow = this->isHorizontalFlow();
auto direction = isHorizontalFlow ? HorizontalLine : VerticalLine;
if (!mainAxisIsFlexItemInlineAxis(flexItem))
return synthesizedBaseline(flexItem, style(), direction, BorderBox) + flowAwareMarginBeforeForFlexItem(flexItem);
auto ascent = alignmentForFlexItem(flexItem) == ItemPosition::LastBaseline ? flexItem.lastLineBaseline() : flexItem.firstLineBaseline();
if (!ascent)
return synthesizedBaseline(flexItem, style(), direction, BorderBox) + flowAwareMarginBeforeForFlexItem(flexItem);
if (!flexItem.writingMode().isBlockMatchingAny(writingMode())) {
// Baseline from flex item with opposite block direction needs to be resolved as if flex item had the same block direction.
// _____________________________ <- flex box top/left (e.g. writing-mode: vertical-rl)
// | __________________ |
// | | 20px | 80px |<-- flex item with vertical-lr (top is at visual left)
// | |<----->|<-------->| |
// | top baseline | |
// where computed baseline is 20px and resolved (as if flex item shares the block direction with flex box) is 80px.
ascent = flexItem.logicalHeight() - *ascent;
}
if (isHorizontalFlow ? flexItem.isScrollContainerY() : flexItem.isScrollContainerX())
return std::max(0_lu, std::min(*ascent, crossAxisExtentForFlexItem(flexItem))) + flowAwareMarginBeforeForFlexItem(flexItem);
return *ascent + flowAwareMarginBeforeForFlexItem(flexItem);;
}
LayoutUnit RenderFlexibleBox::computeFlexItemMarginValue(Length margin)
{
// When resolving the margins, we use the content size for resolving percent and calc (for percents in calc expressions) margins.
// Fortunately, percent margins are always computed with respect to the block's width, even for margin-top and margin-bottom.
LayoutUnit availableSize = contentBoxLogicalWidth();
return minimumValueForLength(margin, availableSize);
}
void RenderFlexibleBox::prepareOrderIteratorAndMargins()
{
OrderIteratorPopulator populator(m_orderIterator);
for (RenderBox* flexItem = firstChildBox(); flexItem; flexItem = flexItem->nextSiblingBox()) {
if (!populator.collectChild(*flexItem))
continue;
// Before running the flex algorithm, 'auto' has a margin of 0.
// Also, if we're not auto sizing, we don't do a layout that computes the start/end margins.
if (isHorizontalFlow()) {
flexItem->setMarginLeft(computeFlexItemMarginValue(flexItem->style().marginLeft()));
flexItem->setMarginRight(computeFlexItemMarginValue(flexItem->style().marginRight()));
} else {
flexItem->setMarginTop(computeFlexItemMarginValue(flexItem->style().marginTop()));
flexItem->setMarginBottom(computeFlexItemMarginValue(flexItem->style().marginBottom()));
}
}
}
std::pair<LayoutUnit, LayoutUnit> RenderFlexibleBox::computeFlexItemMinMaxSizes(RenderBox& flexItem)
{
Length max = mainSizeLengthForFlexItem(RenderBox::SizeType::MaxSize, flexItem);
std::optional<LayoutUnit> maxExtent = std::nullopt;
if (max.isSpecifiedOrIntrinsic())
maxExtent = computeMainAxisExtentForFlexItem(flexItem, RenderBox::SizeType::MaxSize, max);
Length min = mainSizeLengthForFlexItem(RenderBox::SizeType::MinSize, flexItem);
// Intrinsic sizes in child's block axis are handled by the min-size:auto code path.
if (min.isSpecified() || (min.isIntrinsic() && mainAxisIsFlexItemInlineAxis(flexItem))) {
auto minExtent = computeMainAxisExtentForFlexItem(flexItem, RenderBox::SizeType::MinSize, min).value_or(0_lu);
// We must never return a min size smaller than the min preferred size for tables.
if (flexItem.isRenderTable() && mainAxisIsFlexItemInlineAxis(flexItem))
minExtent = std::max(minExtent, flexItem.minPreferredLogicalWidth());
return { minExtent, maxExtent.value_or(LayoutUnit::max()) };
}
if (shouldApplyMinSizeAutoForFlexItem(flexItem)) {
// FIXME: If the min value is expected to be valid here, we need to come up with a non optional version of computeMainAxisExtentForFlexItem and
// ensure it's valid through the virtual calls of computeIntrinsicLogicalContentHeightUsing.
LayoutUnit contentSize;
Length flexItemCrossSizeLength = crossSizeLengthForFlexItem(RenderBox::SizeType::MainOrPreferredSize, flexItem);
bool canComputeSizeThroughAspectRatio = flexItem.isRenderReplaced() && flexItemHasComputableAspectRatio(flexItem) && flexItemCrossSizeIsDefinite(flexItem, flexItemCrossSizeLength);
if (canComputeSizeThroughAspectRatio)
contentSize = computeMainSizeFromAspectRatioUsing(flexItem, flexItemCrossSizeLength);
else
contentSize = computeMainAxisExtentForFlexItem(flexItem, RenderBox::SizeType::MinSize, Length(LengthType::MinContent)).value_or(0_lu);
if (flexItemHasAspectRatio(flexItem) && (!crossSizeLengthForFlexItem(RenderBox::SizeType::MinSize, flexItem).isAuto() || !crossSizeLengthForFlexItem(RenderBox::SizeType::MaxSize, flexItem).isAuto()))
contentSize = adjustFlexItemSizeForAspectRatioCrossAxisMinAndMax(flexItem, contentSize);
ASSERT(contentSize >= 0);
contentSize = std::min(contentSize, maxExtent.value_or(contentSize));
Length mainSize = mainSizeLengthForFlexItem(RenderBox::SizeType::MainOrPreferredSize, flexItem);
if (flexItemMainSizeIsDefinite(flexItem, mainSize)) {
LayoutUnit resolvedMainSize = computeMainAxisExtentForFlexItem(flexItem, RenderBox::SizeType::MainOrPreferredSize, mainSize).value_or(0);
ASSERT(resolvedMainSize >= 0);
LayoutUnit specifiedSize = std::min(resolvedMainSize, maxExtent.value_or(resolvedMainSize));
return { std::min(specifiedSize, contentSize), maxExtent.value_or(LayoutUnit::max()) };
}
if (flexItem.isRenderReplaced() && flexItemHasComputableAspectRatioAndCrossSizeIsConsideredDefinite(flexItem)) {
LayoutUnit transferredSize = computeMainSizeFromAspectRatioUsing(flexItem, flexItemCrossSizeLength);
transferredSize = adjustFlexItemSizeForAspectRatioCrossAxisMinAndMax(flexItem, transferredSize);
return { std::min(transferredSize, contentSize), maxExtent.value_or(LayoutUnit::max()) };
}
return { contentSize, maxExtent.value_or(LayoutUnit::max()) };
}
return { 0_lu, maxExtent.value_or(LayoutUnit::max()) };
}
bool RenderFlexibleBox::canUseFlexItemForPercentageResolution(const RenderBox& flexItem)
{
ASSERT(flexItem.isFlexItem());
auto canUseByLayoutPhase = [&] {
if (m_inSimplifiedLayout) {
// While in simplified layout, we should only re-compute overflow and/or re-position out-of-flow boxes, some renderers (e.g. RenderReplaced and subclasses)
// currently ignore this optimization and run regular layout.
return true;
}
if (m_inPostFlexUpdateScrollbarLayout) {
// Unfortunately we run layout on flex content _after_ performing flex layout to ensure scrollbars are up to date (see endAndCommitUpdateScrollInfoAfterLayoutTransaction/updateScrollInfoAfterLayout).
// We need to let this content run percent resolution as if we were still in flex item layout.
return true;
}
if (m_inFlexItemLayout) {
// While running flex _item_ layout, we may only resolve percentage against the flex item when it is orthogonal to the flex container.
return !mainAxisIsFlexItemInlineAxis(flexItem);
}
if (m_inCrossAxisLayout || m_inFlexItemIntrinsicWidthComputation)
return true;
// Let's decide based on style when we are outside of layout (i.e. relative percent position).
return !m_inLayout;
};
if (!canUseByLayoutPhase())
return false;
auto canUseByStyle = [&] {
if (mainAxisIsFlexItemInlineAxis(flexItem))
return alignmentForFlexItem(flexItem) == ItemPosition::Stretch;
if (flexItem.style().flexGrow() == RenderStyle::initialFlexGrow() && flexItem.style().flexShrink() == 0.0f && flexItemMainSizeIsDefinite(flexItem, flexBasisForFlexItem(flexItem)))
return true;
return canComputePercentageFlexBasis(flexItem, Length(0, LengthType::Percent), UpdatePercentageHeightDescendants::Yes);
};
return canUseByStyle();
}
// This method is only called whenever a descendant of a flex item wants to resolve a percentage in its
// block axis (logical height). The key here is that percentages should be generally resolved before the
// flex item is flexed, meaning that they shouldn't be recomputed once the flex item has been flexed. There
// are some exceptions though that are implemented here, like the case of fully inflexible items with
// definite flex-basis, or whenever the flex container has a definite main size. See
// https://drafts.csswg.org/css-flexbox/#definite-sizes for additional details.
std::optional<LayoutUnit> RenderFlexibleBox::usedFlexItemOverridingLogicalHeightForPercentageResolution(const RenderBox& flexItem)
{
return canUseFlexItemForPercentageResolution(flexItem) ? flexItem.overridingBorderBoxLogicalHeight() : std::nullopt;
}
LayoutUnit RenderFlexibleBox::adjustFlexItemSizeForAspectRatioCrossAxisMinAndMax(const RenderBox& flexItem, LayoutUnit flexItemSize)
{
Length crossMin = crossSizeLengthForFlexItem(RenderBox::SizeType::MinSize, flexItem);
Length crossMax = crossSizeLengthForFlexItem(RenderBox::SizeType::MaxSize, flexItem);
if (flexItemCrossSizeIsDefinite(flexItem, crossMax)) {
LayoutUnit maxValue = computeMainSizeFromAspectRatioUsing(flexItem, crossMax);
flexItemSize = std::min(maxValue, flexItemSize);
}
if (flexItemCrossSizeIsDefinite(flexItem, crossMin)) {
LayoutUnit minValue = computeMainSizeFromAspectRatioUsing(flexItem, crossMin);
flexItemSize = std::max(minValue, flexItemSize);
}
return flexItemSize;
}
void RenderFlexibleBox::maybeCacheFlexItemMainIntrinsicSize(RenderBox& flexItem, RelayoutChildren relayoutChildren)
{
if (!flexItemHasIntrinsicMainAxisSize(flexItem))
return;
// If this condition is true, then computeMainAxisExtentForFlexItem will call
// flexItem.intrinsicContentLogicalHeight() and flexItem.scrollbarLogicalHeight(),
// so if the child has intrinsic min/max/preferred size, run layout on it now to make sure
// its logical height and scroll bars are up to date.
updateBlockChildDirtyBitsBeforeLayout(relayoutChildren, flexItem);
// Don't resolve percentages in children. This is especially important for the min-height calculation,
// where we want percentages to be treated as auto. For flex-basis itself, this is not a problem because
// by definition we have an indefinite flex basis here and thus percentages should not resolve.
if (flexItem.needsLayout() || !m_intrinsicSizeAlongMainAxis.contains(flexItem)) {
auto percentResolveDisableScope = FlexPercentResolveDisabler { view().frameView().layoutContext(), flexItem };
flexItem.setChildNeedsLayout(MarkOnlyThis);
flexItem.layoutIfNeeded();
cacheFlexItemMainSize(flexItem);
}
}
FlexLayoutItem RenderFlexibleBox::constructFlexLayoutItem(RenderBox& flexItem, RelayoutChildren relayoutChildren)
{
auto everHadLayout = flexItem.everHadLayout();
flexItem.clearOverridingSize();
if (CheckedPtr flexibleBox = dynamicDowncast<RenderFlexibleBox>(flexItem))
flexibleBox->resetHasDefiniteHeight();
if (everHadLayout && flexItem.hasTrimmedMargin(std::optional<MarginTrimType> { }))
flexItem.clearTrimmedMarginsMarkings();
if (flexItem.needsPreferredWidthsRecalculation())
flexItem.setPreferredLogicalWidthsDirty(true, MarkingBehavior::MarkOnlyThis);
LayoutUnit borderAndPadding = isHorizontalFlow() ? flexItem.horizontalBorderAndPaddingExtent() : flexItem.verticalBorderAndPaddingExtent();
LayoutUnit innerFlexBaseSize = computeFlexBaseSizeForFlexItem(flexItem, borderAndPadding, relayoutChildren);
LayoutUnit margin = isHorizontalFlow() ? flexItem.horizontalMarginExtent() : flexItem.verticalMarginExtent();
return FlexLayoutItem(flexItem, innerFlexBaseSize, borderAndPadding, margin, computeFlexItemMinMaxSizes(flexItem), everHadLayout);
}
void RenderFlexibleBox::freezeViolations(Vector<FlexLayoutItem*>& violations, LayoutUnit& availableFreeSpace, double& totalFlexGrow, double& totalFlexShrink, double& totalWeightedFlexShrink)
{
for (size_t i = 0; i < violations.size(); ++i) {
ASSERT(!violations[i]->frozen);
auto& flexItemStyle = violations[i]->style();
LayoutUnit flexItemSize = violations[i]->flexedContentSize;
availableFreeSpace -= flexItemSize - violations[i]->flexBaseContentSize;
totalFlexGrow -= flexItemStyle.flexGrow();
totalFlexShrink -= flexItemStyle.flexShrink();
totalWeightedFlexShrink -= flexItemStyle.flexShrink() * violations[i]->flexBaseContentSize;
// totalWeightedFlexShrink can be negative when we exceed the precision of
// a double when we initially calcuate totalWeightedFlexShrink. We then
// subtract each child's weighted flex shrink with full precision, now
// leading to a negative result. See
// css3/flexbox/large-flex-shrink-assert.html
totalWeightedFlexShrink = std::max(totalWeightedFlexShrink, 0.0);
violations[i]->frozen = true;
}
}
void RenderFlexibleBox::freezeInflexibleItems(FlexSign flexSign, FlexLayoutItems& flexLayoutItems, LayoutUnit& remainingFreeSpace, double& totalFlexGrow, double& totalFlexShrink, double& totalWeightedFlexShrink)
{
// Per https://drafts.csswg.org/css-flexbox/#resolve-flexible-lengths step 2,
// we freeze all items with a flex factor of 0 as well as those with a min/max
// size violation.
Vector<FlexLayoutItem*> newInflexibleItems;
for (auto& flexLayoutItem : flexLayoutItems) {
ASSERT(!flexLayoutItem.renderer->isOutOfFlowPositioned());
ASSERT(!flexLayoutItem.frozen);
float flexFactor = (flexSign == FlexSign::PositiveFlexibility) ? flexLayoutItem.style().flexGrow() : flexLayoutItem.style().flexShrink();
if (!flexFactor || (flexSign == FlexSign::PositiveFlexibility && flexLayoutItem.flexBaseContentSize > flexLayoutItem.hypotheticalMainContentSize) || (flexSign == FlexSign::NegativeFlexibility && flexLayoutItem.flexBaseContentSize < flexLayoutItem.hypotheticalMainContentSize)) {
flexLayoutItem.flexedContentSize = flexLayoutItem.hypotheticalMainContentSize;
newInflexibleItems.append(&flexLayoutItem);
}
}
freezeViolations(newInflexibleItems, remainingFreeSpace, totalFlexGrow, totalFlexShrink, totalWeightedFlexShrink);
}
// Returns true if we successfully ran the algorithm and sized the flex items.
bool RenderFlexibleBox::resolveFlexibleLengths(FlexSign flexSign, FlexLayoutItems& flexLayoutItems, LayoutUnit initialFreeSpace, LayoutUnit& remainingFreeSpace, double& totalFlexGrow, double& totalFlexShrink, double& totalWeightedFlexShrink)
{
LayoutUnit totalViolation;
LayoutUnit usedFreeSpace;
Vector<FlexLayoutItem*> minViolations;
Vector<FlexLayoutItem*> maxViolations;
double sumFlexFactors = (flexSign == FlexSign::PositiveFlexibility) ? totalFlexGrow : totalFlexShrink;
if (sumFlexFactors > 0 && sumFlexFactors < 1) {
LayoutUnit fractional(initialFreeSpace * sumFlexFactors);
if (fractional.abs() < remainingFreeSpace.abs())
remainingFreeSpace = fractional;
}
for (auto& flexLayoutItem : flexLayoutItems) {
// This check also covers out-of-flow children.
if (flexLayoutItem.frozen)
continue;
auto& flexItemStyle = flexLayoutItem.style();
LayoutUnit flexItemSize = flexLayoutItem.flexBaseContentSize;
double extraSpace = 0;
if (remainingFreeSpace > 0 && totalFlexGrow > 0 && flexSign == FlexSign::PositiveFlexibility && std::isfinite(totalFlexGrow))
extraSpace = remainingFreeSpace * flexItemStyle.flexGrow() / totalFlexGrow;
else if (remainingFreeSpace < 0 && totalWeightedFlexShrink > 0 && flexSign == FlexSign::NegativeFlexibility && std::isfinite(totalWeightedFlexShrink) && flexItemStyle.flexShrink())
extraSpace = remainingFreeSpace * flexItemStyle.flexShrink() * flexLayoutItem.flexBaseContentSize / totalWeightedFlexShrink;
if (std::isfinite(extraSpace))
flexItemSize += LayoutUnit::fromFloatRound(extraSpace);
LayoutUnit adjustedFlexItemSize = flexLayoutItem.constrainSizeByMinMax(flexItemSize);
ASSERT(adjustedFlexItemSize >= 0);
flexLayoutItem.flexedContentSize = adjustedFlexItemSize;
usedFreeSpace += adjustedFlexItemSize - flexLayoutItem.flexBaseContentSize;
LayoutUnit violation = adjustedFlexItemSize - flexItemSize;
if (violation > 0)
minViolations.append(&flexLayoutItem);
else if (violation < 0)
maxViolations.append(&flexLayoutItem);
totalViolation += violation;
}
if (totalViolation)
freezeViolations(totalViolation < 0 ? maxViolations : minViolations, remainingFreeSpace, totalFlexGrow, totalFlexShrink, totalWeightedFlexShrink);
else
remainingFreeSpace -= usedFreeSpace;
return !totalViolation;
}
inline ContentPosition resolveLeftRightAlignment(ContentPosition position, const RenderStyle& style, bool isReversed)
{
if (position == ContentPosition::Left || position == ContentPosition::Right) {
auto leftRightAxisDirection = RenderFlexibleBox::leftRightAxisDirectionFromStyle(style);
position = (style.justifyContent().isEndward(leftRightAxisDirection, isReversed))
? ContentPosition::End : ContentPosition::Start;
}
return position;
}
static LayoutUnit initialJustifyContentOffset(const RenderStyle& style, LayoutUnit availableFreeSpace, unsigned numberOfFlexItems, bool isReversed)
{
ContentPosition justifyContent = style.resolvedJustifyContentPosition(contentAlignmentNormalBehavior());
ContentDistribution justifyContentDistribution = style.resolvedJustifyContentDistribution(contentAlignmentNormalBehavior());
if (availableFreeSpace < 0 && style.justifyContent().overflow() == OverflowAlignment::Safe) {
ASSERT(justifyContent != ContentPosition::Normal);
justifyContent = ContentPosition::Start;
}
// First of all resolve Left and Right so we could convert it to their equivalent properties handled bellow.
// If the property's axis is not parallel with either left<->right axis, this value behaves as start. Currently,
// the only case where the property's axis is not parallel with either left<->right axis is in a column flexbox.
// https: //www.w3.org/TR/css-align-3/#valdef-justify-content-left
justifyContent = resolveLeftRightAlignment(justifyContent, style, isReversed);
ASSERT(justifyContent != ContentPosition::Left);
ASSERT(justifyContent != ContentPosition::Right);
if (justifyContent == ContentPosition::FlexEnd
|| (justifyContent == ContentPosition::End && !isReversed)
|| (justifyContent == ContentPosition::Start && isReversed))
return availableFreeSpace;
if (justifyContent == ContentPosition::Center)
return availableFreeSpace / 2;
if (justifyContentDistribution == ContentDistribution::SpaceAround) {
if (!numberOfFlexItems)
return availableFreeSpace / 2;
if (availableFreeSpace > 0)
return availableFreeSpace / (2 * numberOfFlexItems);
return { };
}
if (justifyContentDistribution == ContentDistribution::SpaceEvenly) {
if (!numberOfFlexItems)
return availableFreeSpace / 2;
if (availableFreeSpace > 0)
return availableFreeSpace / (numberOfFlexItems + 1);
return { };
}
return { };
}
static LayoutUnit justifyContentSpaceBetweenFlexItems(LayoutUnit availableFreeSpace, ContentDistribution justifyContentDistribution, unsigned numberOfFlexItems)
{
if (availableFreeSpace > 0 && numberOfFlexItems > 1) {
if (justifyContentDistribution == ContentDistribution::SpaceBetween)
return availableFreeSpace / (numberOfFlexItems - 1);
if (justifyContentDistribution == ContentDistribution::SpaceAround)
return availableFreeSpace / numberOfFlexItems;
if (justifyContentDistribution == ContentDistribution::SpaceEvenly)
return availableFreeSpace / (numberOfFlexItems + 1);
}
return 0;
}
static LayoutUnit alignmentOffset(LayoutUnit availableFreeSpace, ItemPosition position, std::optional<LayoutUnit> ascent, std::optional<LayoutUnit> maxAscent, bool isWrapReverse)
{
switch (position) {
case ItemPosition::Legacy:
case ItemPosition::Auto:
case ItemPosition::Normal:
ASSERT_NOT_REACHED();
break;
case ItemPosition::Start:
case ItemPosition::End:
case ItemPosition::SelfStart:
case ItemPosition::SelfEnd:
case ItemPosition::Left:
case ItemPosition::Right:
ASSERT_NOT_REACHED("%u alignmentForFlexItem should have transformed this position value to something we handle below.", static_cast<uint8_t>(position));
break;
case ItemPosition::Stretch:
// Actual stretching must be handled by the caller. Since wrap-reverse
// flips cross start and cross end, stretch children should be aligned
// with the cross end. This matters because applyStretchAlignment
// doesn't always stretch or stretch fully (explicit cross size given, or
// stretching constrained by max-height/max-width). For flex-start and
// flex-end this is handled by alignmentForFlexItem().
if (isWrapReverse)
return availableFreeSpace;
break;
case ItemPosition::FlexStart:
break;
case ItemPosition::FlexEnd:
return availableFreeSpace;
case ItemPosition::Center:
case ItemPosition::AnchorCenter:
return availableFreeSpace / 2;
case ItemPosition::Baseline:
case ItemPosition::LastBaseline:
return maxAscent.value_or(0_lu) - ascent.value_or(0_lu);
}
return 0;
}
void RenderFlexibleBox::setOverridingMainSizeForFlexItem(RenderBox& flexItem, LayoutUnit preferredSize)
{
if (mainAxisIsFlexItemInlineAxis(flexItem))
flexItem.setOverridingBorderBoxLogicalWidth(preferredSize + flexItem.borderAndPaddingLogicalWidth());
else
flexItem.setOverridingBorderBoxLogicalHeight(preferredSize + flexItem.borderAndPaddingLogicalHeight());
}
LayoutUnit RenderFlexibleBox::staticMainAxisPositionForPositionedFlexItem(const RenderBox& flexItem)
{
auto flexItemMainExtent = mainAxisMarginExtentForFlexItem(flexItem) + mainAxisExtentForFlexItem(flexItem);
auto availableSpace = mainAxisContentExtent(contentBoxLogicalHeight()) - flexItemMainExtent;
auto isReverse = isColumnOrRowReverse();
LayoutUnit offset = initialJustifyContentOffset(style(), availableSpace, { }, isReverse);
if (isReverse)
offset = availableSpace - offset;
return offset;
}
LayoutUnit RenderFlexibleBox::staticCrossAxisPositionForPositionedFlexItem(const RenderBox& flexItem)
{
auto availableSpace = availableAlignmentSpaceForFlexItem(crossAxisContentExtent(), flexItem);
auto safety = overflowAlignmentForFlexItem(flexItem);
auto align = alignmentForFlexItem(flexItem);
if (availableSpace < 0 && safety == OverflowAlignment::Safe)
align = ItemPosition::FlexStart;
return alignmentOffset(availableSpace, align, std::nullopt, std::nullopt, style().flexWrap() == FlexWrap::Reverse);
}
LayoutUnit RenderFlexibleBox::staticInlinePositionForPositionedFlexItem(const RenderBox& flexItem)
{
return startOffsetForContent() + (isColumnFlow() ? staticCrossAxisPositionForPositionedFlexItem(flexItem) : staticMainAxisPositionForPositionedFlexItem(flexItem));
}
LayoutUnit RenderFlexibleBox::staticBlockPositionForPositionedFlexItem(const RenderBox& flexItem)
{
return borderAndPaddingBefore() + (isColumnFlow() ? staticMainAxisPositionForPositionedFlexItem(flexItem) : staticCrossAxisPositionForPositionedFlexItem(flexItem));
}
bool RenderFlexibleBox::setStaticPositionForPositionedLayout(const RenderBox& flexItem)
{
bool positionChanged = false;
auto* layer = flexItem.layer();
if (flexItem.style().hasStaticInlinePosition(writingMode().isHorizontal())) {
LayoutUnit inlinePosition = staticInlinePositionForPositionedFlexItem(flexItem);
if (layer->staticInlinePosition() != inlinePosition) {
layer->setStaticInlinePosition(inlinePosition);
positionChanged = true;
}
}
if (flexItem.style().hasStaticBlockPosition(writingMode().isHorizontal())) {
LayoutUnit blockPosition = staticBlockPositionForPositionedFlexItem(flexItem);
if (layer->staticBlockPosition() != blockPosition) {
layer->setStaticBlockPosition(blockPosition);
positionChanged = true;
}
}
return positionChanged;
}
// This refers to https://drafts.csswg.org/css-flexbox-1/#definite-sizes, section 1).
LayoutUnit RenderFlexibleBox::computeCrossSizeForFlexItemUsingContainerCrossSize(const RenderBox& flexItem) const
{
if (isColumnFlow())
return contentBoxLogicalWidth();
// Keep this sync'ed with flexItemCrossSizeShouldUseContainerCrossSize().
auto definiteSizeValue = [&] {
// Let's compute the definite size value for the flex item (value that we can resolve without running layout).
auto isHorizontal = isHorizontalFlow();
auto size = isHorizontal ? style().height() : style().width();
ASSERT(size.isFixed() || (size.isPercent() && availableLogicalHeightForPercentageComputation()));
auto definiteValue = LayoutUnit { size.value() };
if (size.isPercent())
definiteValue = availableLogicalHeightForPercentageComputation().value_or(0_lu);
auto maximumSize = isHorizontal ? style().maxHeight() : style().maxWidth();
if (maximumSize.isFixed())
definiteValue = std::min(definiteValue, LayoutUnit { maximumSize.value() });
auto minimumSize = isHorizontal ? style().minHeight() : style().minWidth();
if (minimumSize.isFixed())
definiteValue = std::max(definiteValue, LayoutUnit { minimumSize.value() });
return definiteValue;
};
return std::max(0_lu, definiteSizeValue() - crossAxisMarginExtentForFlexItem(flexItem));
}
void RenderFlexibleBox::prepareFlexItemForPositionedLayout(RenderBox& flexItem)
{
ASSERT(flexItem.isOutOfFlowPositioned());
flexItem.containingBlock()->insertPositionedObject(flexItem);
auto* layer = flexItem.layer();
LayoutUnit staticInlinePosition = flowAwareBorderStart() + flowAwarePaddingStart();
if (layer->staticInlinePosition() != staticInlinePosition) {
layer->setStaticInlinePosition(staticInlinePosition);
if (flexItem.style().hasStaticInlinePosition(writingMode().isHorizontal()))
flexItem.setChildNeedsLayout(MarkOnlyThis);
}
LayoutUnit staticBlockPosition = flowAwareBorderBefore() + flowAwarePaddingBefore();
if (layer->staticBlockPosition() != staticBlockPosition) {
layer->setStaticBlockPosition(staticBlockPosition);
if (flexItem.style().hasStaticBlockPosition(writingMode().isHorizontal()))
flexItem.setChildNeedsLayout(MarkOnlyThis);
}
}
inline OverflowAlignment RenderFlexibleBox::overflowAlignmentForFlexItem(const RenderBox& flexItem) const
{
return flexItem.style().resolvedAlignSelf(&style(), selfAlignmentNormalBehavior()).overflow();
}
ItemPosition RenderFlexibleBox::alignmentForFlexItem(const RenderBox& flexItem) const
{
ItemPosition align = flexItem.style().resolvedAlignSelf(&style(), selfAlignmentNormalBehavior()).position();
ASSERT(align != ItemPosition::Auto && align != ItemPosition::Normal);
// Left and Right are only for justify-*.
ASSERT(align != ItemPosition::Left && align != ItemPosition::Right);
// We can safely return here because start/end are not affected by a reversed flex-wrap because the
// alignment container is the flex line, and in a wrap reversed flex container the start and end within
// a flex line are still the same. Contrary to this flex-start/flex-end depend on the flex container
// start/end edges which are flipped in the case of wrap-reverse.
if (align == ItemPosition::Start)
return ItemPosition::FlexStart;
if (align == ItemPosition::End)
return ItemPosition::FlexEnd;
if (align == ItemPosition::SelfStart || align == ItemPosition::SelfEnd) {
bool hasSameDirection = isHorizontalFlow()
? writingMode().isAnyTopToBottom() == flexItem.writingMode().isAnyTopToBottom()
: writingMode().isAnyLeftToRight() == flexItem.writingMode().isAnyLeftToRight();
return hasSameDirection == (align == ItemPosition::SelfStart)
? ItemPosition::FlexStart : ItemPosition::FlexEnd;
}
if (style().flexWrap() == FlexWrap::Reverse) {
if (align == ItemPosition::FlexStart)
align = ItemPosition::FlexEnd;
else if (align == ItemPosition::FlexEnd)
align = ItemPosition::FlexStart;
}
return align;
}
void RenderFlexibleBox::resetAutoMarginsAndLogicalTopInCrossAxis(RenderBox& flexItem)
{
if (hasAutoMarginsInCrossAxis(flexItem)) {
flexItem.updateLogicalHeight();
if (isHorizontalFlow()) {
if (flexItem.style().marginTop().isAuto())
flexItem.setMarginTop(0_lu);
if (flexItem.style().marginBottom().isAuto())
flexItem.setMarginBottom(0_lu);
} else {
if (flexItem.style().marginLeft().isAuto())
flexItem.setMarginLeft(0_lu);
if (flexItem.style().marginRight().isAuto())
flexItem.setMarginRight(0_lu);
}
}
}
bool RenderFlexibleBox::needToStretchFlexItemLogicalHeight(const RenderBox& flexItem) const
{
// This function is a little bit magical. It relies on the fact that blocks
// intrinsically "stretch" themselves in their inline axis, i.e. a <div> has
// an implicit width: 100%. So the child will automatically stretch if our
// cross axis is the child's inline axis. That's the case if:
// - We are horizontal and the child is in vertical writing mode
// - We are vertical and the child is in horizontal writing mode
// Otherwise, we need to stretch if the cross axis size is auto.
if (alignmentForFlexItem(flexItem) != ItemPosition::Stretch)
return false;
if (isHorizontalFlow() != flexItem.isHorizontalWritingMode())
return false;
// Aspect ratio is properly handled by RenderReplaced during layout.
if (flexItem.isRenderReplaced() && flexItemHasAspectRatio(flexItem))
return false;
return flexItem.style().logicalHeight().isAuto();
}
bool RenderFlexibleBox::flexItemHasIntrinsicMainAxisSize(const RenderBox& flexItem)
{
if (mainAxisIsFlexItemInlineAxis(flexItem))
return false;
Length flexBasis = flexBasisForFlexItem(flexItem);
Length minSize = mainSizeLengthForFlexItem(RenderBox::SizeType::MinSize, flexItem);
Length maxSize = mainSizeLengthForFlexItem(RenderBox::SizeType::MaxSize, flexItem);
// FIXME: we must run flexItemMainSizeIsDefinite() because it might end up calling computePercentageLogicalHeight()
// which has some side effects like calling addPercentHeightDescendant() for example so it is not possible to skip
// the call for example by moving it to the end of the conditional expression. This is error-prone and we should
// refactor computePercentageLogicalHeight() at some point so that it only computes stuff without those side effects.
if (!flexItemMainSizeIsDefinite(flexItem, flexBasis) || minSize.isIntrinsic() || maxSize.isIntrinsic())
return true;
if (shouldApplyMinSizeAutoForFlexItem(flexItem))
return true;
return false;
}
Overflow RenderFlexibleBox::mainAxisOverflowForFlexItem(const RenderBox& flexItem) const
{
if (isHorizontalFlow())
return flexItem.style().overflowX();
return flexItem.style().overflowY();
}
Overflow RenderFlexibleBox::crossAxisOverflowForFlexItem(const RenderBox& flexItem) const
{
if (isHorizontalFlow())
return flexItem.style().overflowY();
return flexItem.style().overflowX();
}
bool RenderFlexibleBox::flexItemHasPercentHeightDescendants(const RenderBox& renderer) const
{
// FIXME: This function can be removed soon after webkit.org/b/204318 is fixed. Evaluate whether the
// skipContainingBlockForPercentHeightCalculation() check below should be moved to the caller in that case.
CheckedPtr renderBlock = dynamicDowncast<RenderBlock>(renderer);
if (!renderBlock)
return false;
// FlexibleBoxImpl's like RenderButton might wrap their children in anonymous blocks. Those anonymous blocks are
// skipped for percentage height calculations in RenderBox::computePercentageLogicalHeight() and thus
// addPercentHeightDescendant() is never called for them. This means that this method would always wrongly
// return false for a child of a <button> with a percentage height.
if (hasPercentHeightDescendants() && skipContainingBlockForPercentHeightCalculation(renderer, isHorizontalWritingMode() != renderer.isHorizontalWritingMode())) {
for (auto& descendant : *percentHeightDescendants()) {
if (renderBlock->isContainingBlockAncestorFor(descendant))
return true;
}
}
if (!renderBlock->hasPercentHeightDescendants())
return false;
auto* percentHeightDescendants = renderBlock->percentHeightDescendants();
if (!percentHeightDescendants)
return false;
for (auto& descendant : *percentHeightDescendants) {
bool hasOutOfFlowAncestor = false;
for (auto* ancestor = descendant.containingBlock(); ancestor && ancestor != renderBlock.get(); ancestor = ancestor->containingBlock()) {
if (ancestor->isOutOfFlowPositioned()) {
hasOutOfFlowAncestor = true;
break;
}
}
if (!hasOutOfFlowAncestor)
return true;
}
return false;
}
static LayoutUnit contentAlignmentStartOverflow(LayoutUnit availableFreeSpace, ContentPosition position, ContentDistribution distribution, OverflowAlignment safety, bool isReverse)
{
if (availableFreeSpace >= 0 || safety == OverflowAlignment::Safe)
return 0_lu;
if (distribution == ContentDistribution::SpaceAround
|| distribution == ContentDistribution::SpaceEvenly)
return -availableFreeSpace / 2;
switch (position) {
case ContentPosition::Start:
case ContentPosition::Baseline:
case ContentPosition::LastBaseline:
return 0_lu;
case ContentPosition::FlexStart:
return isReverse ? -availableFreeSpace : 0_lu;
case ContentPosition::Center:
return -availableFreeSpace / 2;
case ContentPosition::End:
return -availableFreeSpace;
case ContentPosition::FlexEnd:
return isReverse ? 0_lu : -availableFreeSpace;
default:
ASSERT((distribution == ContentDistribution::Default && position == ContentPosition::Normal) // Normal alignment.
|| distribution == ContentDistribution::Stretch
|| distribution == ContentDistribution::SpaceBetween);
return isReverse ? -availableFreeSpace : 0_lu;
}
}
void RenderFlexibleBox::layoutAndPlaceFlexItems(LayoutUnit& crossAxisOffset, FlexLayoutItems& flexLayoutItems, LayoutUnit availableFreeSpace, RelayoutChildren relayoutChildren, FlexLineStates& lineStates, LayoutUnit gapBetweenItems)
{
LayoutUnit autoMarginOffset = autoMarginOffsetInMainAxis(flexLayoutItems, availableFreeSpace);
LayoutUnit mainAxisOffset = flowAwareBorderStart() + flowAwarePaddingStart();
mainAxisOffset += initialJustifyContentOffset(style(), availableFreeSpace, flexLayoutItems.size(), isColumnOrRowReverse());
if (style().flexDirection() == FlexDirection::RowReverse)
mainAxisOffset += isHorizontalFlow() ? verticalScrollbarWidth() : horizontalScrollbarHeight();
if (availableFreeSpace < 0) {
ContentPosition position = style().resolvedJustifyContentPosition(contentAlignmentNormalBehavior());
ContentDistribution distribution = style().resolvedJustifyContentDistribution(contentAlignmentNormalBehavior());
OverflowAlignment safety = style().justifyContent().overflow();
position = resolveLeftRightAlignment(position, style(), isColumnOrRowReverse());
LayoutUnit overflow = contentAlignmentStartOverflow(availableFreeSpace, position, distribution, safety, isColumnOrRowReverse());
m_justifyContentStartOverflow = std::max(m_justifyContentStartOverflow, overflow);
}
LayoutUnit totalMainExtent = mainAxisExtent();
LayoutUnit maxFlexItemCrossAxisExtent;
LayoutUnit maxAscent;
LayoutUnit maxDescent;
LayoutUnit lastBaselineMaxAscent;
std::optional<BaselineAlignmentState> baselineAlignmentState;
ContentDistribution distribution = style().resolvedJustifyContentDistribution(contentAlignmentNormalBehavior());
bool shouldFlipMainAxis = !isColumnFlow() && !isLeftToRightFlow();
auto flexLayoutScope = SetForScope(m_inFlexItemLayout, true);
for (size_t i = 0; i < flexLayoutItems.size(); ++i) {
auto& flexLayoutItem = flexLayoutItems[i];
auto& flexItem = flexLayoutItem.renderer.get();
ASSERT(!flexLayoutItem.renderer->isOutOfFlowPositioned());
setOverridingMainSizeForFlexItem(flexItem, flexLayoutItem.flexedContentSize);
// The flexed content size and the override size include the scrollbar
// width, so we need to compare to the size including the scrollbar.
// FIXME: Should it include the scrollbar?
if (flexLayoutItem.flexedContentSize != mainAxisContentExtentForFlexItemIncludingScrollbar(flexItem))
flexItem.setChildNeedsLayout(MarkOnlyThis);
else {
// To avoid double applying margin changes in
// updateAutoMarginsInCrossAxis, we reset the margins here.
resetAutoMarginsAndLogicalTopInCrossAxis(flexItem);
}
// We may have already forced relayout for orthogonal flowing children in
// computeInnerFlexBaseSizeForFlexItem.
bool forceFlexItemRelayout = relayoutChildren == RelayoutChildren::Yes && !m_relaidOutFlexItems.contains(flexItem);
if (!forceFlexItemRelayout && flexItemHasPercentHeightDescendants(flexItem)) {
// Have to force another relayout even though the child is sized
// correctly, because its descendants are not sized correctly yet. Our
// previous layout of the child was done without an override height set.
// So, redo it here.
forceFlexItemRelayout = true;
}
updateFlexItemDirtyBitsBeforeLayout(forceFlexItemRelayout, flexItem);
if (!flexItem.needsLayout())
flexItem.markForPaginationRelayoutIfNeeded();
if (flexItem.needsLayout())
m_relaidOutFlexItems.add(flexItem);
flexItem.layoutIfNeeded();
if (!flexLayoutItem.everHadLayout && flexItem.checkForRepaintDuringLayout()) {
flexItem.repaint();
flexItem.repaintOverhangingFloats(true);
}
updateAutoMarginsInMainAxis(flexItem, autoMarginOffset);
LayoutUnit flexItemCrossAxisMarginBoxExtent;
auto alignment = alignmentForFlexItem(flexItem);
if ((alignment == ItemPosition::Baseline || alignment == ItemPosition::LastBaseline) && !hasAutoMarginsInCrossAxis(flexItem)) {
LayoutUnit ascent = marginBoxAscentForFlexItem(flexItem);
LayoutUnit descent = (crossAxisMarginExtentForFlexItem(flexItem) + crossAxisExtentForFlexItem(flexItem)) - ascent;
maxDescent = std::max(maxDescent, descent);
if (baselineAlignmentState)
baselineAlignmentState->updateSharedGroup(flexItem, alignment, ascent);
else
baselineAlignmentState = { flexItem, alignment, ascent };
if (alignment == ItemPosition::Baseline) {
maxAscent = std::max(maxAscent, ascent);
flexItemCrossAxisMarginBoxExtent = maxAscent + maxDescent;
} else {
lastBaselineMaxAscent = std::max(lastBaselineMaxAscent, ascent);
flexItemCrossAxisMarginBoxExtent = lastBaselineMaxAscent + maxDescent;
}
} else
flexItemCrossAxisMarginBoxExtent = crossAxisIntrinsicExtentForFlexItem(flexItem) + crossAxisMarginExtentForFlexItem(flexItem);
if (!isColumnFlow())
setLogicalHeight(std::max(logicalHeight(), crossAxisOffset + flowAwareBorderAfter() + flowAwarePaddingAfter() + flexItemCrossAxisMarginBoxExtent + crossAxisScrollbarExtent()));
maxFlexItemCrossAxisExtent = std::max(maxFlexItemCrossAxisExtent, flexItemCrossAxisMarginBoxExtent);
mainAxisOffset += flowAwareMarginStartForFlexItem(flexItem);
LayoutUnit flexItemMainExtent = mainAxisExtentForFlexItem(flexItem);
// In an RTL column situation, this will apply the margin-right/margin-end
// on the left. This will be fixed later in flipForRightToLeftColumn.
LayoutPoint location(shouldFlipMainAxis ? totalMainExtent - mainAxisOffset - flexItemMainExtent : mainAxisOffset, crossAxisOffset + flowAwareMarginBeforeForFlexItem(flexItem));
setFlowAwareLocationForFlexItem(flexItem, location);
mainAxisOffset += flexItemMainExtent + flowAwareMarginEndForFlexItem(flexItem);
if (i != flexLayoutItems.size() - 1) {
// The last item does not get extra space added.
mainAxisOffset += justifyContentSpaceBetweenFlexItems(availableFreeSpace, distribution, flexLayoutItems.size()) + gapBetweenItems;
}
// FIXME: Deal with pagination.
}
if (isColumnFlow())
setLogicalHeight(std::max(logicalHeight(), mainAxisOffset + flowAwareBorderEnd() + flowAwarePaddingEnd() + scrollbarLogicalHeight()));
if (style().flexDirection() == FlexDirection::ColumnReverse) {
// We have to do an extra pass for column-reverse to reposition the flex
// items since the start depends on the height of the flexbox, which we
// only know after we've positioned all the flex items.
updateLogicalHeight();
layoutColumnReverse(flexLayoutItems, crossAxisOffset, availableFreeSpace, gapBetweenItems);
}
lineStates.append(LineState(crossAxisOffset, maxFlexItemCrossAxisExtent, baselineAlignmentState, WTFMove(flexLayoutItems)));
crossAxisOffset += maxFlexItemCrossAxisExtent;
}
void RenderFlexibleBox::layoutColumnReverse(const FlexLayoutItems& flexLayoutItems, LayoutUnit crossAxisOffset, LayoutUnit availableFreeSpace, LayoutUnit gapBetweenItems)
{
// This is similar to the logic in layoutAndPlaceFlexItems, except we place
// the children starting from the end of the flexbox. We also don't need to
// layout anything since we're just moving the children to a new position.
LayoutUnit mainAxisOffset = logicalHeight() - flowAwareBorderEnd() - flowAwarePaddingEnd();
mainAxisOffset -= initialJustifyContentOffset(style(), availableFreeSpace, flexLayoutItems.size(), isColumnOrRowReverse());
mainAxisOffset -= isHorizontalFlow() ? verticalScrollbarWidth() : horizontalScrollbarHeight();
ContentDistribution distribution = style().resolvedJustifyContentDistribution(contentAlignmentNormalBehavior());
for (size_t i = 0; i < flexLayoutItems.size(); ++i) {
auto& flexItem = flexLayoutItems[i].renderer;
ASSERT(!flexItem->isOutOfFlowPositioned());
mainAxisOffset -= mainAxisExtentForFlexItem(flexItem) + flowAwareMarginEndForFlexItem(flexItem);
setFlowAwareLocationForFlexItem(flexItem, LayoutPoint(mainAxisOffset, crossAxisOffset + flowAwareMarginBeforeForFlexItem(flexItem)));
mainAxisOffset -= flowAwareMarginStartForFlexItem(flexItem);
if (i != flexLayoutItems.size() - 1) {
// The last item does not get extra space added.
mainAxisOffset -= justifyContentSpaceBetweenFlexItems(availableFreeSpace, distribution, flexLayoutItems.size()) + gapBetweenItems;
}
}
}
static LayoutUnit initialAlignContentOffset(LayoutUnit availableFreeSpace, ContentPosition alignContent, ContentDistribution alignContentDistribution, OverflowAlignment safety, unsigned numberOfLines, bool isReversed)
{
if (availableFreeSpace < 0 && safety == OverflowAlignment::Safe) {
ASSERT(alignContent != ContentPosition::Normal);
alignContent = ContentPosition::Start;
}
if (alignContent == ContentPosition::FlexEnd
|| (alignContent == ContentPosition::End && !isReversed)
|| (alignContent == ContentPosition::Start && isReversed))
return availableFreeSpace;
if (alignContent == ContentPosition::Center)
return availableFreeSpace / 2;
if (alignContentDistribution == ContentDistribution::SpaceAround) {
if (availableFreeSpace > 0 && numberOfLines)
return availableFreeSpace / (2 * numberOfLines);
if (availableFreeSpace < 0)
return availableFreeSpace / 2;
}
if (alignContentDistribution == ContentDistribution::SpaceEvenly) {
if (availableFreeSpace > 0)
return availableFreeSpace / (numberOfLines + 1);
// Fallback to 'center'
return availableFreeSpace / 2;
}
return 0_lu;
}
static LayoutUnit alignContentSpaceBetweenFlexItems(LayoutUnit availableFreeSpace, ContentDistribution alignContentDistribution, unsigned numberOfLines)
{
if (availableFreeSpace > 0 && numberOfLines > 1) {
if (alignContentDistribution == ContentDistribution::SpaceBetween)
return availableFreeSpace / (numberOfLines - 1);
if (alignContentDistribution == ContentDistribution::SpaceAround || alignContentDistribution == ContentDistribution::Stretch)
return availableFreeSpace / numberOfLines;
if (alignContentDistribution == ContentDistribution::SpaceEvenly)
return availableFreeSpace / (numberOfLines + 1);
}
return 0_lu;
}
void RenderFlexibleBox::alignFlexLines(FlexLineStates& lineStates, LayoutUnit gapBetweenLines)
{
if (lineStates.isEmpty() || !isMultiline())
return;
ContentPosition position = style().resolvedAlignContentPosition(contentAlignmentNormalBehavior());
ContentDistribution distribution = style().resolvedAlignContentDistribution(contentAlignmentNormalBehavior());
OverflowAlignment safety = style().alignContent().overflow();
bool isWrapReverse = style().flexWrap() == FlexWrap::Reverse;
if (position == ContentPosition::FlexStart && !gapBetweenLines && safety != OverflowAlignment::Safe && !isWrapReverse)
return;
size_t numLines = lineStates.size();
LayoutUnit availableCrossAxisSpace = crossAxisContentExtent() - (numLines - 1) * gapBetweenLines;
for (size_t i = 0; i < numLines; ++i)
availableCrossAxisSpace -= lineStates[i].crossAxisExtent;
m_alignContentStartOverflow = contentAlignmentStartOverflow(availableCrossAxisSpace, position, distribution, safety, isWrapReverse);
LayoutUnit lineOffset = initialAlignContentOffset(availableCrossAxisSpace, position, distribution, safety, numLines, isWrapReverse);
for (unsigned lineNumber = 0; lineNumber < numLines; ++lineNumber) {
LineState& lineState = lineStates[lineNumber];
lineState.crossAxisOffset += lineOffset;
for (auto& flexLayoutItem : lineState.flexLayoutItems)
adjustAlignmentForFlexItem(flexLayoutItem.renderer, lineOffset);
if (distribution == ContentDistribution::Stretch && availableCrossAxisSpace > 0)
lineStates[lineNumber].crossAxisExtent += availableCrossAxisSpace / static_cast<unsigned>(numLines);
lineOffset += alignContentSpaceBetweenFlexItems(availableCrossAxisSpace, distribution, numLines) + gapBetweenLines;
}
}
void RenderFlexibleBox::adjustAlignmentForFlexItem(RenderBox& flexItem, LayoutUnit delta)
{
ASSERT(!flexItem.isOutOfFlowPositioned());
setFlowAwareLocationForFlexItem(flexItem, flowAwareLocationForFlexItem(flexItem) + LayoutSize(0_lu, delta));
}
void RenderFlexibleBox::alignFlexItems(FlexLineStates& lineStates)
{
for (LineState& lineState : lineStates) {
LayoutUnit lineCrossAxisExtent = lineState.crossAxisExtent;
auto baselineAlignmentState = lineState.baselineAlignmentState;
if (lineState.baselineAlignmentState)
performBaselineAlignment(lineState);
for (auto& flexLayoutItem : lineState.flexLayoutItems) {
ASSERT(!flexLayoutItem.renderer->isOutOfFlowPositioned());
auto safety = overflowAlignmentForFlexItem(flexLayoutItem.renderer);
auto position = alignmentForFlexItem(flexLayoutItem.renderer);
if (updateAutoMarginsInCrossAxis(flexLayoutItem.renderer, std::max(0_lu, availableAlignmentSpaceForFlexItem(lineCrossAxisExtent, flexLayoutItem.renderer))) || position == ItemPosition::Baseline || position == ItemPosition::LastBaseline)
continue;
if (position == ItemPosition::Stretch)
applyStretchAlignmentToFlexItem(flexLayoutItem.renderer, lineCrossAxisExtent);
LayoutUnit availableSpace = availableAlignmentSpaceForFlexItem(lineCrossAxisExtent, flexLayoutItem.renderer);
if (availableSpace < 0 && safety == OverflowAlignment::Safe)
position = ItemPosition::FlexStart; // See Start == FlexStart assumption in alignmentForFlexItem().
LayoutUnit offset = alignmentOffset(availableSpace, position, std::nullopt, std::nullopt, style().flexWrap() == FlexWrap::Reverse);
adjustAlignmentForFlexItem(flexLayoutItem.renderer, offset);
}
}
}
void RenderFlexibleBox::performBaselineAlignment(LineState& lineState)
{
ASSERT(lineState.baselineAlignmentState);
auto lineCrossAxisExtent = lineState.crossAxisExtent;
bool containerHasWrapReverse = style().flexWrap() == FlexWrap::Reverse;
auto flexItemWritingModeForBaselineAlignment = [&](const RenderBox& flexItem) {
if (mainAxisIsFlexItemInlineAxis(flexItem))
return flexItem.style().writingMode();
// css-align-3: 9.1. Determining the Baselines of a Box
// In general, the writing mode of the box, shape, or other object being aligned is used to determine
// the line-under and line-over edges for synthesis. However, when that writing mode’s block flow direction
// is parallel to the axis of the alignment context, an axis-compatible writing mode must be assumed:
// If the box establishing the alignment context has a block flow direction that is orthogonal to the
// axis of the alignment context, use its writing mode.
if (style().isRowFlexDirection())
return style().writingMode();
// Otherwise:
//
// If the box’s own writing mode is vertical, assume horizontal-tb.
// If the box’s own writing mode is horizontal, assume vertical-lr if
// direction is ltr and vertical-rl if direction is rtl.
WritingMode hypotheticalWritingMode;
if (!flexItem.isHorizontalWritingMode())
return hypotheticalWritingMode;
else
hypotheticalWritingMode.setWritingMode(writingMode().isBidiLTR() ? StyleWritingMode::VerticalLr : StyleWritingMode::VerticalRl);
return hypotheticalWritingMode;
};
auto shouldAdjustItemTowardsCrossAxisEnd = [&](const FlowDirection& flexItemBlockFlowDirection, ItemPosition alignment) {
ASSERT(alignment == ItemPosition::Baseline || alignment == ItemPosition::LastBaseline);
// The direction in which we are aligning (i.e. direction of the cross axis) must be parallel with the direction of the flex item's used writing mode
ASSERT_IMPLIES(crossAxisDirection() == RenderFlexibleBox::Direction::TopToBottom || crossAxisDirection() == RenderFlexibleBox::Direction::BottomToTop, flexItemBlockFlowDirection == RenderFlexibleBox::Direction::TopToBottom || flexItemBlockFlowDirection == RenderFlexibleBox::Direction::BottomToTop);
ASSERT_IMPLIES(crossAxisDirection() == RenderFlexibleBox::Direction::LeftToRight || crossAxisDirection() == RenderFlexibleBox::Direction::RightToLeft, flexItemBlockFlowDirection == RenderFlexibleBox::Direction::LeftToRight || flexItemBlockFlowDirection == RenderFlexibleBox::Direction::RightToLeft);
// For first baseline aligned items, if its block direction is the opposite of
// the cross axis direction, then that means its fallback alignment (safe self-start)
// is in the direction of the end of the cross axis
//
// For last baseline aligned items, if its block direction is in the same direction as
// the cross axis direction, then that means its fallback alignment (safe self-end) is
// in the direction of the end of the cross axis
if (alignment == ItemPosition::Baseline)
return crossAxisDirection() != flexItemBlockFlowDirection;
return crossAxisDirection() == flexItemBlockFlowDirection;
};
for (auto& baselineSharingGroup : lineState.baselineAlignmentState.value().sharedGroups()) {
LayoutUnit minMarginAfterBaseline = LayoutUnit::max();
for (auto& flexItem : baselineSharingGroup) {
auto position = alignmentForFlexItem(flexItem);
ASSERT(position == ItemPosition::Baseline || position == ItemPosition::LastBaseline);
auto offset = alignmentOffset(availableAlignmentSpaceForFlexItem(lineCrossAxisExtent, flexItem), position, marginBoxAscentForFlexItem(flexItem), baselineSharingGroup.maxAscent(), containerHasWrapReverse);
adjustAlignmentForFlexItem(flexItem, offset);
if (shouldAdjustItemTowardsCrossAxisEnd(flexItemWritingModeForBaselineAlignment(flexItem).blockDirection(), position))
minMarginAfterBaseline = std::min(minMarginAfterBaseline, availableAlignmentSpaceForFlexItem(lineCrossAxisExtent, flexItem) - offset);
}
// css-align-3 9.3 part 3:
// Position the aligned baseline-sharing group within the alignment container according to its
// fallback alignment. The fallback alignment of a baseline-sharing group is the fallback alignment
// of its items as resolved to physical directions.
if (minMarginAfterBaseline) {
for (auto& flexItem : baselineSharingGroup) {
if (shouldAdjustItemTowardsCrossAxisEnd(flexItemWritingModeForBaselineAlignment(flexItem).blockDirection(), alignmentForFlexItem(flexItem)) && !hasAutoMarginsInCrossAxis(flexItem))
adjustAlignmentForFlexItem(flexItem, minMarginAfterBaseline);
}
}
}
}
void RenderFlexibleBox::applyStretchAlignmentToFlexItem(RenderBox& flexItem, LayoutUnit lineCrossAxisExtent)
{
if (mainAxisIsFlexItemInlineAxis(flexItem) && flexItem.style().logicalHeight().isAuto()) {
LayoutUnit stretchedLogicalHeight = std::max(flexItem.borderAndPaddingLogicalHeight(),
lineCrossAxisExtent - crossAxisMarginExtentForFlexItem(flexItem));
ASSERT(!flexItem.needsLayout());
LayoutUnit desiredLogicalHeight = flexItem.constrainLogicalHeightByMinMax(stretchedLogicalHeight, cachedFlexItemIntrinsicContentLogicalHeight(flexItem));
// FIXME: Can avoid laying out here in some cases. See https://webkit.org/b/87905.
bool flexItemNeedsRelayout = desiredLogicalHeight != flexItem.logicalHeight();
if (auto* block = dynamicDowncast<RenderBlock>(flexItem); block && block->hasPercentHeightDescendants() && m_relaidOutFlexItems.contains(flexItem)) {
// Have to force another relayout even though the child is sized
// correctly, because its descendants are not sized correctly yet. Our
// previous layout of the child was done without an override height set.
// So, redo it here.
flexItemNeedsRelayout = true;
}
if (flexItemNeedsRelayout || !flexItem.overridingBorderBoxLogicalHeight())
flexItem.setOverridingBorderBoxLogicalHeight(desiredLogicalHeight);
if (flexItemNeedsRelayout) {
SetForScope resetFlexItemLogicalHeight(m_shouldResetFlexItemLogicalHeightBeforeLayout, true);
// We cache the child's intrinsic content logical height to avoid it being
// reset to the stretched height.
// FIXME: This is fragile. RenderBoxes should be smart enough to
// determine their intrinsic content logical height correctly even when
// there's an overrideHeight.
LayoutUnit flexItemIntrinsicContentLogicalHeight = cachedFlexItemIntrinsicContentLogicalHeight(flexItem);
flexItem.setChildNeedsLayout(MarkOnlyThis);
// Don't use layoutChildIfNeeded to avoid setting cross axis cached size twice.
flexItem.layoutIfNeeded();
setCachedFlexItemIntrinsicContentLogicalHeight(flexItem, flexItemIntrinsicContentLogicalHeight);
}
} else if (!mainAxisIsFlexItemInlineAxis(flexItem) && flexItem.style().logicalWidth().isAuto()) {
LayoutUnit flexItemWidth = std::max(0_lu, lineCrossAxisExtent - crossAxisMarginExtentForFlexItem(flexItem));
flexItemWidth = flexItem.constrainLogicalWidthByMinMax(flexItemWidth, crossAxisContentExtent(), *this);
if (flexItemWidth != flexItem.logicalWidth()) {
flexItem.setOverridingBorderBoxLogicalWidth(flexItemWidth);
flexItem.setChildNeedsLayout(MarkOnlyThis);
flexItem.layoutIfNeeded();
}
}
}
void RenderFlexibleBox::flipForRightToLeftColumn(const FlexLineStates& lineStates)
{
if (writingMode().isLogicalLeftInlineStart() || !isColumnFlow())
return;
LayoutUnit crossExtent = crossAxisExtent();
for (size_t lineNumber = 0; lineNumber < lineStates.size(); ++lineNumber) {
const LineState& lineState = lineStates[lineNumber];
for (auto& flexLayoutItem : lineState.flexLayoutItems) {
ASSERT(!flexLayoutItem.renderer->isOutOfFlowPositioned());
LayoutPoint location = flowAwareLocationForFlexItem(flexLayoutItem.renderer);
// For vertical flows, setFlowAwareLocationForFlexItem will transpose x and
// y, so using the y axis for a column cross axis extent is correct.
location.setY(crossExtent - crossAxisExtentForFlexItem(flexLayoutItem.renderer) - location.y());
if (!isHorizontalWritingMode())
location.move(LayoutSize(0, -horizontalScrollbarHeight()));
setFlowAwareLocationForFlexItem(flexLayoutItem.renderer, location);
}
}
}
void RenderFlexibleBox::flipForWrapReverse(const FlexLineStates& lineStates, LayoutUnit crossAxisStartEdge)
{
LayoutUnit contentExtent = crossAxisContentExtent();
for (size_t lineNumber = 0; lineNumber < lineStates.size(); ++lineNumber) {
const LineState& lineState = lineStates[lineNumber];
for (auto& flexLayoutItem : lineState.flexLayoutItems) {
LayoutUnit lineCrossAxisExtent = lineStates[lineNumber].crossAxisExtent;
LayoutUnit originalOffset = lineStates[lineNumber].crossAxisOffset - crossAxisStartEdge;
LayoutUnit newOffset = contentExtent - originalOffset - lineCrossAxisExtent;
adjustAlignmentForFlexItem(flexLayoutItem.renderer, newOffset - originalOffset);
}
}
}
std::optional<TextDirection> RenderFlexibleBox::leftRightAxisDirectionFromStyle(const RenderStyle& style)
{
if (!style.isColumnFlexDirection()) // Prioritize text direction.
return style.writingMode().bidiDirection();
if (style.writingMode().isVertical()) { // Fall back to block direction if possible.
return style.writingMode().isBlockLeftToRight()
? TextDirection::LTR
: TextDirection::RTL;
}
return std::nullopt;
}
LayoutOptionalOutsets RenderFlexibleBox::allowedLayoutOverflow() const
{
LayoutOptionalOutsets allowance = RenderBox::allowedLayoutOverflow();
bool isColumnar = style().isColumnFlexDirection();
if (isHorizontalWritingMode()) {
allowance.top() = isColumnar ? m_justifyContentStartOverflow : m_alignContentStartOverflow;
if (writingMode().isInlineLeftToRight())
allowance.left() = isColumnar ? m_alignContentStartOverflow : m_justifyContentStartOverflow;
else
allowance.right() = isColumnar ? m_alignContentStartOverflow : m_justifyContentStartOverflow;
} else {
allowance.left() = isColumnar ? m_justifyContentStartOverflow : m_alignContentStartOverflow;
if (writingMode().isInlineTopToBottom())
allowance.top() = isColumnar ? m_alignContentStartOverflow : m_justifyContentStartOverflow;
else
allowance.bottom() = isColumnar ? m_alignContentStartOverflow : m_justifyContentStartOverflow;
}
return allowance;
}
LayoutUnit RenderFlexibleBox::computeGap(RenderFlexibleBox::GapType gapType) const
{
// row-gap is used for gaps between flex items in column flows or for gaps between lines in row flows.
bool usesRowGap = (gapType == GapType::BetweenItems) == isColumnFlow();
auto& gapLength = usesRowGap ? style().rowGap() : style().columnGap();
if (LIKELY(gapLength.isNormal()))
return { };
auto availableSize = usesRowGap ? availableLogicalHeightForPercentageComputation().value_or(0_lu) : contentBoxLogicalWidth();
return minimumValueForLength(gapLength.length(), availableSize);
}
bool RenderFlexibleBox::layoutUsingFlexFormattingContext()
{
if (m_hasFlexFormattingContextLayout && !*m_hasFlexFormattingContextLayout) {
// FIXME: Avoid continous content checking on (potentially) unsupported content. This ensures no pref impact on cases like resize etc.
// Remove when canUseForFlexLayout becomes less expensive.
return false;
}
m_hasFlexFormattingContextLayout = LayoutIntegration::canUseForFlexLayout(*this);
if (!*m_hasFlexFormattingContextLayout)
return false;
auto flexLayout = LayoutIntegration::FlexLayout { *this };
flexLayout.updateFormattingContexGeometries();
flexLayout.layout();
setLogicalHeight(std::max(logicalHeight(), borderAndPaddingLogicalHeight() + flexLayout.contentBoxLogicalHeight()));
updateLogicalHeight();
return true;
}
const RenderBox* RenderFlexibleBox::firstBaselineCandidateOnLine(OrderIterator flexItemIterator, ItemPosition baselinePosition, size_t numberOfItemsOnLine) const
{
// Note that "first" here means in iterator order and not logical flex order (caller can pass in reversed order).
ASSERT(baselinePosition == ItemPosition::Baseline || baselinePosition == ItemPosition::LastBaseline);
size_t index = 0;
const RenderBox* baselineFlexItem = nullptr;
for (auto* flexItem = flexItemIterator.first(); flexItem; flexItem = flexItemIterator.next()) {
if (flexItemIterator.shouldSkipChild(*flexItem))
continue;
if (alignmentForFlexItem(*flexItem) == baselinePosition && mainAxisIsFlexItemInlineAxis(*flexItem) && !hasAutoMarginsInCrossAxis(*flexItem))
return flexItem;
if (!baselineFlexItem)
baselineFlexItem = flexItem;
if (++index == numberOfItemsOnLine)
return baselineFlexItem;
}
return nullptr;
}
const RenderBox* RenderFlexibleBox::lastBaselineCandidateOnLine(OrderIterator flexItemIterator, ItemPosition baselinePosition, size_t numberOfItemsOnLine) const
{
// Note that "last" here means in iterator order and not logical flex order (caller can pass in reversed order).
ASSERT(baselinePosition == ItemPosition::Baseline || baselinePosition == ItemPosition::LastBaseline);
size_t index = 0;
RenderBox* baselineFlexItem = nullptr;
for (auto* flexItem = flexItemIterator.first(); flexItem; flexItem = flexItemIterator.next()) {
if (flexItemIterator.shouldSkipChild(*flexItem))
continue;
if (alignmentForFlexItem(*flexItem) == baselinePosition && mainAxisIsFlexItemInlineAxis(*flexItem) && !hasAutoMarginsInCrossAxis(*flexItem))
baselineFlexItem = flexItem;
if (++index == numberOfItemsOnLine)
return baselineFlexItem ? baselineFlexItem : flexItem;
}
return nullptr;
}
const RenderBox* RenderFlexibleBox::flexItemForFirstBaseline() const
{
// Looking for baseline flex candidate on visually first line.
auto useLastLine = style().flexWrap() == FlexWrap::Reverse;
auto useLastItem = style().flexDirection() == FlexDirection::RowReverse || style().flexDirection() == FlexDirection::ColumnReverse;
if (!useLastLine) {
if (!useLastItem) {
// Logically (and visually) first item on logically (and visually) first line.
return firstBaselineCandidateOnLine(m_orderIterator, ItemPosition::Baseline, m_numberOfFlexItemsOnFirstLine);
}
// Logically last (but visually first) item on logically (and visually) first line.
return lastBaselineCandidateOnLine(m_orderIterator, ItemPosition::Baseline, m_numberOfFlexItemsOnFirstLine);
}
if (!useLastItem) {
// Logically (and visually) first item on logically last (but visually first) line.
return lastBaselineCandidateOnLine(m_orderIterator.reverse(), ItemPosition::Baseline, m_numberOfFlexItemsOnLastLine);
}
// Logically last (but visually first) item on logically last (but visually first) line.
return firstBaselineCandidateOnLine(m_orderIterator.reverse(), ItemPosition::Baseline, m_numberOfFlexItemsOnLastLine);
}
const RenderBox* RenderFlexibleBox::flexItemForLastBaseline() const
{
// Looking for baseline flex candidate on visually last line.
auto useLastLine = style().flexWrap() == FlexWrap::Reverse;
auto useLastItem = style().flexDirection() == FlexDirection::RowReverse || style().flexDirection() == FlexDirection::ColumnReverse;
if (!useLastLine) {
if (!useLastItem) {
// Logically (and visually) last item on logically (and visually) last line.
return firstBaselineCandidateOnLine(m_orderIterator.reverse(), ItemPosition::LastBaseline, m_numberOfFlexItemsOnLastLine);
}
// Logically first (but visually last) item on logically (and visually) last line.
return lastBaselineCandidateOnLine(m_orderIterator.reverse(), ItemPosition::LastBaseline, m_numberOfFlexItemsOnLastLine);
}
if (!useLastItem) {
// Logically (and visually) last item on logically first (but visually last) line.
return lastBaselineCandidateOnLine(m_orderIterator, ItemPosition::LastBaseline, m_numberOfFlexItemsOnFirstLine);
}
// Logically first (but visually last) item on logically last (but visually first) line.
return firstBaselineCandidateOnLine(m_orderIterator, ItemPosition::LastBaseline, m_numberOfFlexItemsOnFirstLine);
}
}
|