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 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200
|
/*
* Copyright (C) 1999 Lars Knoll (knoll@kde.org)
* (C) 1999 Antti Koivisto (koivisto@kde.org)
* (C) 2001 Peter Kelly (pmk@post.com)
* (C) 2001 Dirk Mueller (mueller@kde.org)
* (C) 2007 David Smith (catfish.man@gmail.com)
* Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2012, 2013 Apple Inc.
* All rights reserved.
* (C) 2007 Eric Seidel (eric@webkit.org)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "third_party/blink/renderer/core/dom/element.h"
#include <memory>
#include "third_party/blink/public/platform/web_scroll_into_view_params.h"
#include "third_party/blink/renderer/bindings/core/v8/dictionary.h"
#include "third_party/blink/renderer/bindings/core/v8/scroll_into_view_options_or_boolean.h"
#include "third_party/blink/renderer/bindings/core/v8/string_or_trusted_html.h"
#include "third_party/blink/renderer/bindings/core/v8/string_or_trusted_script_url.h"
#include "third_party/blink/renderer/bindings/core/v8/usv_string_or_trusted_url.h"
#include "third_party/blink/renderer/core/accessibility/ax_context.h"
#include "third_party/blink/renderer/core/accessibility/ax_object_cache.h"
#include "third_party/blink/renderer/core/animation/css/css_animations.h"
#include "third_party/blink/renderer/core/aom/computed_accessible_node.h"
#include "third_party/blink/renderer/core/css/css_identifier_value.h"
#include "third_party/blink/renderer/core/css/css_primitive_value.h"
#include "third_party/blink/renderer/core/css/css_property_value_set.h"
#include "third_party/blink/renderer/core/css/css_selector_watch.h"
#include "third_party/blink/renderer/core/css/css_style_sheet.h"
#include "third_party/blink/renderer/core/css/css_value.h"
#include "third_party/blink/renderer/core/css/parser/css_parser.h"
#include "third_party/blink/renderer/core/css/property_set_css_style_declaration.h"
#include "third_party/blink/renderer/core/css/resolver/selector_filter_parent_scope.h"
#include "third_party/blink/renderer/core/css/resolver/style_resolver.h"
#include "third_party/blink/renderer/core/css/resolver/style_resolver_stats.h"
#include "third_party/blink/renderer/core/css/selector_query.h"
#include "third_party/blink/renderer/core/css/style_change_reason.h"
#include "third_party/blink/renderer/core/css/style_engine.h"
#include "third_party/blink/renderer/core/css_value_keywords.h"
#include "third_party/blink/renderer/core/dom/attr.h"
#include "third_party/blink/renderer/core/dom/dataset_dom_string_map.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/dom_token_list.h"
#include "third_party/blink/renderer/core/dom/element_data_cache.h"
#include "third_party/blink/renderer/core/dom/element_rare_data.h"
#include "third_party/blink/renderer/core/dom/element_traversal.h"
#include "third_party/blink/renderer/core/dom/events/event_dispatch_forbidden_scope.h"
#include "third_party/blink/renderer/core/dom/events/event_dispatcher.h"
#include "third_party/blink/renderer/core/dom/first_letter_pseudo_element.h"
#include "third_party/blink/renderer/core/dom/layout_tree_builder.h"
#include "third_party/blink/renderer/core/dom/mutation_observer_interest_group.h"
#include "third_party/blink/renderer/core/dom/mutation_record.h"
#include "third_party/blink/renderer/core/dom/named_node_map.h"
#include "third_party/blink/renderer/core/dom/node_computed_style.h"
#include "third_party/blink/renderer/core/dom/presentation_attribute_style.h"
#include "third_party/blink/renderer/core/dom/pseudo_element.h"
#include "third_party/blink/renderer/core/dom/scriptable_document_parser.h"
#include "third_party/blink/renderer/core/dom/shadow_root.h"
#include "third_party/blink/renderer/core/dom/shadow_root_init.h"
#include "third_party/blink/renderer/core/dom/shadow_root_v0.h"
#include "third_party/blink/renderer/core/dom/slot_assignment.h"
#include "third_party/blink/renderer/core/dom/space_split_string.h"
#include "third_party/blink/renderer/core/dom/text.h"
#include "third_party/blink/renderer/core/dom/v0_insertion_point.h"
#include "third_party/blink/renderer/core/dom/whitespace_attacher.h"
#include "third_party/blink/renderer/core/editing/editing_utilities.h"
#include "third_party/blink/renderer/core/editing/ephemeral_range.h"
#include "third_party/blink/renderer/core/editing/frame_selection.h"
#include "third_party/blink/renderer/core/editing/iterators/text_iterator.h"
#include "third_party/blink/renderer/core/editing/selection_template.h"
#include "third_party/blink/renderer/core/editing/serializers/serialization.h"
#include "third_party/blink/renderer/core/editing/set_selection_options.h"
#include "third_party/blink/renderer/core/editing/visible_selection.h"
#include "third_party/blink/renderer/core/events/focus_event.h"
#include "third_party/blink/renderer/core/frame/csp/content_security_policy.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/local_frame_view.h"
#include "third_party/blink/renderer/core/frame/scroll_into_view_options.h"
#include "third_party/blink/renderer/core/frame/scroll_to_options.h"
#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/frame/visual_viewport.h"
#include "third_party/blink/renderer/core/fullscreen/fullscreen.h"
#include "third_party/blink/renderer/core/geometry/dom_rect.h"
#include "third_party/blink/renderer/core/geometry/dom_rect_list.h"
#include "third_party/blink/renderer/core/html/canvas/html_canvas_element.h"
#include "third_party/blink/renderer/core/html/custom/custom_element.h"
#include "third_party/blink/renderer/core/html/custom/custom_element_registry.h"
#include "third_party/blink/renderer/core/html/custom/v0_custom_element.h"
#include "third_party/blink/renderer/core/html/custom/v0_custom_element_registration_context.h"
#include "third_party/blink/renderer/core/html/forms/html_form_controls_collection.h"
#include "third_party/blink/renderer/core/html/forms/html_options_collection.h"
#include "third_party/blink/renderer/core/html/html_collection.h"
#include "third_party/blink/renderer/core/html/html_document.h"
#include "third_party/blink/renderer/core/html/html_element.h"
#include "third_party/blink/renderer/core/html/html_frame_element_base.h"
#include "third_party/blink/renderer/core/html/html_frame_owner_element.h"
#include "third_party/blink/renderer/core/html/html_plugin_element.h"
#include "third_party/blink/renderer/core/html/html_slot_element.h"
#include "third_party/blink/renderer/core/html/html_table_rows_collection.h"
#include "third_party/blink/renderer/core/html/html_template_element.h"
#include "third_party/blink/renderer/core/html/parser/html_parser_idioms.h"
#include "third_party/blink/renderer/core/html/parser/nesting_level_incrementer.h"
#include "third_party/blink/renderer/core/input/event_handler.h"
#include "third_party/blink/renderer/core/intersection_observer/element_intersection_observer_data.h"
#include "third_party/blink/renderer/core/invisible_dom/activate_invisible_event.h"
#include "third_party/blink/renderer/core/layout/adjust_for_absolute_zoom.h"
#include "third_party/blink/renderer/core/layout/layout_text_fragment.h"
#include "third_party/blink/renderer/core/layout/layout_view.h"
#include "third_party/blink/renderer/core/loader/document_loader.h"
#include "third_party/blink/renderer/core/page/chrome_client.h"
#include "third_party/blink/renderer/core/page/focus_controller.h"
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/core/page/pointer_lock_controller.h"
#include "third_party/blink/renderer/core/page/scrolling/root_scroller_controller.h"
#include "third_party/blink/renderer/core/page/scrolling/root_scroller_util.h"
#include "third_party/blink/renderer/core/page/scrolling/scroll_customization_callbacks.h"
#include "third_party/blink/renderer/core/page/scrolling/scroll_state.h"
#include "third_party/blink/renderer/core/page/scrolling/scroll_state_callback.h"
#include "third_party/blink/renderer/core/page/scrolling/snap_coordinator.h"
#include "third_party/blink/renderer/core/page/scrolling/top_document_root_scroller_controller.h"
#include "third_party/blink/renderer/core/page/spatial_navigation.h"
#include "third_party/blink/renderer/core/paint/paint_layer.h"
#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
#include "third_party/blink/renderer/core/probe/core_probes.h"
#include "third_party/blink/renderer/core/resize_observer/resize_observation.h"
#include "third_party/blink/renderer/core/scroll/scrollable_area.h"
#include "third_party/blink/renderer/core/scroll/smooth_scroll_sequencer.h"
#include "third_party/blink/renderer/core/svg/svg_a_element.h"
#include "third_party/blink/renderer/core/svg/svg_element.h"
#include "third_party/blink/renderer/core/svg_names.h"
#include "third_party/blink/renderer/core/trustedtypes/trusted_html.h"
#include "third_party/blink/renderer/core/trustedtypes/trusted_script_url.h"
#include "third_party/blink/renderer/core/trustedtypes/trusted_url.h"
#include "third_party/blink/renderer/core/xml_names.h"
#include "third_party/blink/renderer/platform/bindings/dom_data_store.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/bindings/v8_dom_activity_logger.h"
#include "third_party/blink/renderer/platform/bindings/v8_dom_wrapper.h"
#include "third_party/blink/renderer/platform/bindings/v8_per_context_data.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/wtf/bit_vector.h"
#include "third_party/blink/renderer/platform/wtf/hash_functions.h"
#include "third_party/blink/renderer/platform/wtf/text/cstring.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
#include "third_party/blink/renderer/platform/wtf/text/text_position.h"
namespace blink {
namespace {
// We need to retain the scroll customization callbacks until the element
// they're associated with is destroyed. It would be simplest if the callbacks
// could be stored in ElementRareData, but we can't afford the space increase.
// Instead, keep the scroll customization callbacks here. The other option would
// be to store these callbacks on the Page or document, but that necessitates a
// bunch more logic for transferring the callbacks between Pages when elements
// are moved around.
ScrollCustomizationCallbacks& GetScrollCustomizationCallbacks() {
DEFINE_STATIC_LOCAL(ScrollCustomizationCallbacks,
scroll_customization_callbacks,
(new ScrollCustomizationCallbacks));
return scroll_customization_callbacks;
}
} // namespace
using namespace HTMLNames;
using namespace XMLNames;
enum class ClassStringContent { kEmpty, kWhiteSpaceOnly, kHasClasses };
Element* Element::Create(const QualifiedName& tag_name, Document* document) {
return new Element(tag_name, document, kCreateElement);
}
Element::Element(const QualifiedName& tag_name,
Document* document,
ConstructionType type)
: ContainerNode(document, type), tag_name_(tag_name) {}
Element::~Element() {
DCHECK(NeedsAttach());
}
inline ElementRareData* Element::GetElementRareData() const {
DCHECK(HasRareData());
return static_cast<ElementRareData*>(RareData());
}
inline ElementRareData& Element::EnsureElementRareData() {
return static_cast<ElementRareData&>(EnsureRareData());
}
bool Element::HasElementFlagInternal(ElementFlags mask) const {
return GetElementRareData()->HasElementFlag(mask);
}
void Element::SetElementFlag(ElementFlags mask, bool value) {
if (!HasRareData() && !value)
return;
EnsureElementRareData().SetElementFlag(mask, value);
}
void Element::ClearElementFlag(ElementFlags mask) {
if (!HasRareData())
return;
GetElementRareData()->ClearElementFlag(mask);
}
void Element::ClearTabIndexExplicitlyIfNeeded() {
if (HasRareData())
GetElementRareData()->ClearTabIndexExplicitly();
}
void Element::SetTabIndexExplicitly() {
EnsureElementRareData().SetTabIndexExplicitly();
}
void Element::setTabIndex(int value) {
SetIntegralAttribute(tabindexAttr, value);
}
int Element::tabIndex() const {
return HasElementFlag(ElementFlags::kTabIndexWasSetExplicitly)
? GetIntegralAttribute(tabindexAttr)
: 0;
}
bool Element::IsFocusableStyle() const {
// Elements in canvas fallback content are not rendered, but they are allowed
// to be focusable as long as their canvas is displayed and visible.
if (IsInCanvasSubtree()) {
const HTMLCanvasElement* canvas =
Traversal<HTMLCanvasElement>::FirstAncestorOrSelf(*this);
DCHECK(canvas);
return canvas->GetLayoutObject() &&
canvas->GetLayoutObject()->Style()->Visibility() ==
EVisibility::kVisible;
}
// FIXME: Even if we are not visible, we might have a child that is visible.
// Hyatt wants to fix that some day with a "has visible content" flag or the
// like.
return GetLayoutObject() &&
GetLayoutObject()->Style()->Visibility() == EVisibility::kVisible;
}
Node* Element::Clone(Document& factory, CloneChildrenFlag flag) const {
return flag == CloneChildrenFlag::kClone ? CloneWithChildren(&factory)
: CloneWithoutChildren(&factory);
}
Element* Element::CloneWithChildren(Document* nullable_factory) const {
Element* clone = CloneWithoutAttributesAndChildren(
nullable_factory ? *nullable_factory : GetDocument());
// This will catch HTML elements in the wrong namespace that are not correctly
// copied. This is a sanity check as HTML overloads some of the DOM methods.
DCHECK_EQ(IsHTMLElement(), clone->IsHTMLElement());
clone->CloneAttributesFrom(*this);
clone->CloneNonAttributePropertiesFrom(*this, CloneChildrenFlag::kClone);
clone->CloneChildNodesFrom(*this);
return clone;
}
Element* Element::CloneWithoutChildren(Document* nullable_factory) const {
Element* clone = CloneWithoutAttributesAndChildren(
nullable_factory ? *nullable_factory : GetDocument());
// This will catch HTML elements in the wrong namespace that are not correctly
// copied. This is a sanity check as HTML overloads some of the DOM methods.
DCHECK_EQ(IsHTMLElement(), clone->IsHTMLElement());
clone->CloneAttributesFrom(*this);
clone->CloneNonAttributePropertiesFrom(*this, CloneChildrenFlag::kSkip);
return clone;
}
Element* Element::CloneWithoutAttributesAndChildren(Document& factory) const {
return factory.CreateElement(TagQName(), CreateElementFlags::ByCloneNode(),
IsValue());
}
Attr* Element::DetachAttribute(size_t index) {
DCHECK(GetElementData());
const Attribute& attribute = GetElementData()->Attributes().at(index);
Attr* attr_node = AttrIfExists(attribute.GetName());
if (attr_node) {
DetachAttrNodeAtIndex(attr_node, index);
} else {
attr_node =
Attr::Create(GetDocument(), attribute.GetName(), attribute.Value());
RemoveAttributeInternal(index, kNotInSynchronizationOfLazyAttribute);
}
return attr_node;
}
void Element::DetachAttrNodeAtIndex(Attr* attr, size_t index) {
DCHECK(attr);
DCHECK(GetElementData());
const Attribute& attribute = GetElementData()->Attributes().at(index);
DCHECK(attribute.GetName() == attr->GetQualifiedName());
DetachAttrNodeFromElementWithValue(attr, attribute.Value());
RemoveAttributeInternal(index, kNotInSynchronizationOfLazyAttribute);
}
void Element::removeAttribute(const QualifiedName& name) {
if (!GetElementData())
return;
size_t index = GetElementData()->Attributes().FindIndex(name);
if (index == kNotFound)
return;
RemoveAttributeInternal(index, kNotInSynchronizationOfLazyAttribute);
}
void Element::SetBooleanAttribute(const QualifiedName& name, bool value) {
if (value)
setAttribute(name, g_empty_atom);
else
removeAttribute(name);
}
NamedNodeMap* Element::attributesForBindings() const {
ElementRareData& rare_data =
const_cast<Element*>(this)->EnsureElementRareData();
if (NamedNodeMap* attribute_map = rare_data.AttributeMap())
return attribute_map;
rare_data.SetAttributeMap(NamedNodeMap::Create(const_cast<Element*>(this)));
return rare_data.AttributeMap();
}
Vector<AtomicString> Element::getAttributeNames() const {
Vector<AtomicString> attributesVector;
if (!hasAttributes())
return attributesVector;
AttributeCollection attributes = element_data_->Attributes();
attributesVector.ReserveInitialCapacity(attributes.size());
for (const Attribute& attr : attributes)
attributesVector.UncheckedAppend(attr.GetName().ToString());
return attributesVector;
}
ElementAnimations* Element::GetElementAnimations() const {
if (HasRareData())
return GetElementRareData()->GetElementAnimations();
return nullptr;
}
ElementAnimations& Element::EnsureElementAnimations() {
ElementRareData& rare_data = EnsureElementRareData();
if (!rare_data.GetElementAnimations())
rare_data.SetElementAnimations(new ElementAnimations());
return *rare_data.GetElementAnimations();
}
bool Element::HasAnimations() const {
if (!HasRareData())
return false;
ElementAnimations* element_animations =
GetElementRareData()->GetElementAnimations();
return element_animations && !element_animations->IsEmpty();
}
Node::NodeType Element::getNodeType() const {
return kElementNode;
}
bool Element::hasAttribute(const QualifiedName& name) const {
return hasAttributeNS(name.NamespaceURI(), name.LocalName());
}
void Element::SynchronizeAllAttributes() const {
if (!GetElementData())
return;
// NOTE: anyAttributeMatches in SelectorChecker.cpp
// currently assumes that all lazy attributes have a null namespace.
// If that ever changes we'll need to fix that code.
if (GetElementData()->style_attribute_is_dirty_) {
DCHECK(IsStyledElement());
SynchronizeStyleAttributeInternal();
}
if (GetElementData()->animated_svg_attributes_are_dirty_)
ToSVGElement(this)->SynchronizeAnimatedSVGAttribute(AnyQName());
}
inline void Element::SynchronizeAttribute(const QualifiedName& name) const {
if (!GetElementData())
return;
if (UNLIKELY(name == styleAttr &&
GetElementData()->style_attribute_is_dirty_)) {
DCHECK(IsStyledElement());
SynchronizeStyleAttributeInternal();
return;
}
if (UNLIKELY(GetElementData()->animated_svg_attributes_are_dirty_)) {
// See comment in the AtomicString version of SynchronizeAttribute()
// also.
ToSVGElement(this)->SynchronizeAnimatedSVGAttribute(name);
}
}
void Element::SynchronizeAttribute(const AtomicString& local_name) const {
// This version of synchronizeAttribute() is streamlined for the case where
// you don't have a full QualifiedName, e.g when called from DOM API.
if (!GetElementData())
return;
if (GetElementData()->style_attribute_is_dirty_ &&
LowercaseIfNecessary(local_name) == styleAttr.LocalName()) {
DCHECK(IsStyledElement());
SynchronizeStyleAttributeInternal();
return;
}
if (GetElementData()->animated_svg_attributes_are_dirty_) {
// We're not passing a namespace argument on purpose. SVGNames::*Attr are
// defined w/o namespaces as well.
// FIXME: this code is called regardless of whether name is an
// animated SVG Attribute. It would seem we should only call this method
// if SVGElement::isAnimatableAttribute is true, but the list of
// animatable attributes in isAnimatableAttribute does not suffice to
// pass all layout tests. Also, m_animatedSVGAttributesAreDirty stays
// dirty unless synchronizeAnimatedSVGAttribute is called with
// anyQName(). This means that even if Element::synchronizeAttribute()
// is called on all attributes, m_animatedSVGAttributesAreDirty remains
// true.
ToSVGElement(this)->SynchronizeAnimatedSVGAttribute(
QualifiedName(g_null_atom, local_name, g_null_atom));
}
}
const AtomicString& Element::getAttribute(const QualifiedName& name) const {
if (!GetElementData())
return g_null_atom;
SynchronizeAttribute(name);
if (const Attribute* attribute = GetElementData()->Attributes().Find(name))
return attribute->Value();
return g_null_atom;
}
AtomicString Element::LowercaseIfNecessary(const AtomicString& name) const {
return IsHTMLElement() && GetDocument().IsHTMLDocument() ? name.LowerASCII()
: name;
}
const AtomicString& Element::nonce() const {
return HasRareData() ? GetElementRareData()->GetNonce() : g_empty_atom;
}
void Element::setNonce(const AtomicString& nonce) {
EnsureElementRareData().SetNonce(nonce);
}
void Element::scrollIntoView(ScrollIntoViewOptionsOrBoolean arg) {
ScrollIntoViewOptions options;
if (arg.IsBoolean()) {
if (arg.GetAsBoolean())
options.setBlock("start");
else
options.setBlock("end");
options.setInlinePosition("nearest");
} else if (arg.IsScrollIntoViewOptions()) {
options = arg.GetAsScrollIntoViewOptions();
if (!RuntimeEnabledFeatures::CSSOMSmoothScrollEnabled() &&
options.behavior() == "smooth") {
options.setBehavior("instant");
}
}
scrollIntoViewWithOptions(options);
}
void Element::scrollIntoView(bool align_to_top) {
ScrollIntoViewOptionsOrBoolean arg;
arg.SetBoolean(align_to_top);
scrollIntoView(arg);
}
static ScrollAlignment ToPhysicalAlignment(const ScrollIntoViewOptions& options,
ScrollOrientation axis,
bool is_horizontal_writing_mode,
bool is_flipped_blocks_mode) {
String alignment =
((axis == kHorizontalScroll && is_horizontal_writing_mode) ||
(axis == kVerticalScroll && !is_horizontal_writing_mode))
? options.inlinePosition()
: options.block();
if (alignment == "center")
return ScrollAlignment::kAlignCenterAlways;
if (alignment == "nearest")
return ScrollAlignment::kAlignToEdgeIfNeeded;
if (alignment == "start") {
return (axis == kHorizontalScroll)
? is_flipped_blocks_mode ? ScrollAlignment::kAlignRightAlways
: ScrollAlignment::kAlignLeftAlways
: ScrollAlignment::kAlignTopAlways;
}
if (alignment == "end") {
return (axis == kHorizontalScroll)
? is_flipped_blocks_mode ? ScrollAlignment::kAlignLeftAlways
: ScrollAlignment::kAlignRightAlways
: ScrollAlignment::kAlignBottomAlways;
}
// Default values
if (is_horizontal_writing_mode) {
return (axis == kHorizontalScroll) ? ScrollAlignment::kAlignToEdgeIfNeeded
: ScrollAlignment::kAlignTopAlways;
}
return (axis == kHorizontalScroll) ? ScrollAlignment::kAlignLeftAlways
: ScrollAlignment::kAlignToEdgeIfNeeded;
}
void Element::scrollIntoViewWithOptions(const ScrollIntoViewOptions& options) {
GetDocument().EnsurePaintLocationDataValidForNode(this);
ScrollIntoViewNoVisualUpdate(options);
}
void Element::ScrollIntoViewNoVisualUpdate(
const ScrollIntoViewOptions& options) {
if (!GetLayoutObject() || !GetDocument().GetPage())
return;
// TODO(810510): Move this logic inside "ScrollableArea::SetScrollOffset" and
// rely on ScrollType to detect js scrolls and set the flag. This requires
// adding new scroll type to enable this.
if (GetDocument().Loader())
GetDocument().Loader()->GetInitialScrollState().was_scrolled_by_js = true;
ScrollBehavior behavior = (options.behavior() == "smooth")
? kScrollBehaviorSmooth
: kScrollBehaviorAuto;
bool is_horizontal_writing_mode =
GetComputedStyle()->IsHorizontalWritingMode();
bool is_flipped_blocks_mode =
GetComputedStyle()->IsFlippedBlocksWritingMode();
ScrollAlignment align_x =
ToPhysicalAlignment(options, kHorizontalScroll,
is_horizontal_writing_mode, is_flipped_blocks_mode);
ScrollAlignment align_y =
ToPhysicalAlignment(options, kVerticalScroll, is_horizontal_writing_mode,
is_flipped_blocks_mode);
LayoutRect bounds = BoundingBoxForScrollIntoView();
GetLayoutObject()->ScrollRectToVisible(
bounds, {align_x, align_y, kProgrammaticScroll, false, behavior});
GetDocument().SetSequentialFocusNavigationStartingPoint(this);
}
void Element::scrollIntoViewIfNeeded(bool center_if_needed) {
GetDocument().EnsurePaintLocationDataValidForNode(this);
if (!GetLayoutObject())
return;
// TODO(810510): Move this logic inside "ScrollableArea::SetScrollOffset" and
// rely on ScrollType to detect js scrolls and set the flag. This requires
// adding new scroll type to enable this.
if (GetDocument().Loader())
GetDocument().Loader()->GetInitialScrollState().was_scrolled_by_js = true;
LayoutRect bounds = BoundingBoxForScrollIntoView();
if (center_if_needed) {
GetLayoutObject()->ScrollRectToVisible(
bounds,
{ScrollAlignment::kAlignCenterIfNeeded,
ScrollAlignment::kAlignCenterIfNeeded, kProgrammaticScroll, false});
} else {
GetLayoutObject()->ScrollRectToVisible(
bounds,
{ScrollAlignment::kAlignToEdgeIfNeeded,
ScrollAlignment::kAlignToEdgeIfNeeded, kProgrammaticScroll, false});
}
}
void Element::setDistributeScroll(V8ScrollStateCallback* scroll_state_callback,
const String& native_scroll_behavior) {
GetScrollCustomizationCallbacks().SetDistributeScroll(
this, ScrollStateCallbackV8Impl::Create(scroll_state_callback,
native_scroll_behavior));
}
void Element::setApplyScroll(V8ScrollStateCallback* scroll_state_callback,
const String& native_scroll_behavior) {
SetApplyScroll(ScrollStateCallbackV8Impl::Create(scroll_state_callback,
native_scroll_behavior));
}
void Element::SetApplyScroll(ScrollStateCallback* scroll_state_callback) {
GetScrollCustomizationCallbacks().SetApplyScroll(this, scroll_state_callback);
}
void Element::RemoveApplyScroll() {
GetScrollCustomizationCallbacks().RemoveApplyScroll(this);
}
ScrollStateCallback* Element::GetApplyScroll() {
return GetScrollCustomizationCallbacks().GetApplyScroll(this);
}
void Element::NativeDistributeScroll(ScrollState& scroll_state) {
if (scroll_state.FullyConsumed())
return;
scroll_state.distributeToScrollChainDescendant();
// The scroll doesn't propagate, and we're currently scrolling an element
// other than this one, prevent the scroll from propagating to this element.
if (scroll_state.DeltaConsumedForScrollSequence() &&
scroll_state.CurrentNativeScrollingElement() != this) {
return;
}
const double delta_x = scroll_state.deltaX();
const double delta_y = scroll_state.deltaY();
CallApplyScroll(scroll_state);
if (delta_x != scroll_state.deltaX() || delta_y != scroll_state.deltaY())
scroll_state.SetCurrentNativeScrollingElement(this);
}
void Element::CallDistributeScroll(ScrollState& scroll_state) {
TRACE_EVENT0("input", "Element::CallDistributeScroll");
ScrollStateCallback* callback =
GetScrollCustomizationCallbacks().GetDistributeScroll(this);
// TODO(bokan): Need to add tests before we allow calling custom callbacks
// for non-touch modalities. For now, just call into the native callback but
// allow the viewport scroll callback so we don't disable overscroll.
// crbug.com/623079.
bool disable_custom_callbacks = !scroll_state.isDirectManipulation() &&
!GetDocument()
.GetPage()
->GlobalRootScrollerController()
.IsViewportScrollCallback(callback);
disable_custom_callbacks |=
!RootScrollerUtil::IsGlobal(this) &&
RuntimeEnabledFeatures::ScrollCustomizationEnabled() &&
!GetScrollCustomizationCallbacks().InScrollPhase(this);
if (!callback || disable_custom_callbacks) {
NativeDistributeScroll(scroll_state);
return;
}
if (callback->NativeScrollBehavior() !=
WebNativeScrollBehavior::kPerformAfterNativeScroll)
callback->Invoke(&scroll_state);
if (callback->NativeScrollBehavior() !=
WebNativeScrollBehavior::kDisableNativeScroll)
NativeDistributeScroll(scroll_state);
if (callback->NativeScrollBehavior() ==
WebNativeScrollBehavior::kPerformAfterNativeScroll)
callback->Invoke(&scroll_state);
}
void Element::NativeApplyScroll(ScrollState& scroll_state) {
// All elements in the scroll chain should be boxes.
DCHECK(!GetLayoutObject() || GetLayoutObject()->IsBox());
if (scroll_state.FullyConsumed())
return;
FloatSize delta(scroll_state.deltaX(), scroll_state.deltaY());
if (delta.IsZero())
return;
// TODO(esprehn): This should use
// updateStyleAndLayoutIgnorePendingStylesheetsForNode.
GetDocument().UpdateStyleAndLayoutIgnorePendingStylesheets();
LayoutBox* box_to_scroll = nullptr;
if (this == GetDocument().documentElement())
box_to_scroll = GetDocument().GetLayoutView();
else if (GetLayoutObject())
box_to_scroll = ToLayoutBox(GetLayoutObject());
if (!box_to_scroll)
return;
ScrollableArea* scrollable_area =
box_to_scroll->EnclosingBox()->GetScrollableArea();
if (!scrollable_area)
return;
ScrollResult result = scrollable_area->UserScroll(
ScrollGranularity(static_cast<int>(scroll_state.deltaGranularity())),
delta);
if (!result.DidScroll())
return;
// FIXME: Native scrollers should only consume the scroll they
// apply. See crbug.com/457765.
scroll_state.ConsumeDeltaNative(delta.Width(), delta.Height());
// We need to setCurrentNativeScrollingElement in both the
// distributeScroll and applyScroll default implementations so
// that if JS overrides one of these methods, but not the
// other, this bookkeeping remains accurate.
scroll_state.SetCurrentNativeScrollingElement(this);
};
void Element::CallApplyScroll(ScrollState& scroll_state) {
TRACE_EVENT0("input", "Element::CallApplyScroll");
// Hits ASSERTs when trying to determine whether we need to scroll on main
// or CC. http://crbug.com/625676.
DisableCompositingQueryAsserts disabler;
if (!GetDocument().GetPage()) {
// We should always have a Page if we're scrolling. See
// crbug.com/689074 for details.
return;
}
ScrollStateCallback* callback =
GetScrollCustomizationCallbacks().GetApplyScroll(this);
// TODO(bokan): Need to add tests before we allow calling custom callbacks
// for non-touch modalities. For now, just call into the native callback but
// allow the viewport scroll callback so we don't disable overscroll.
// crbug.com/623079.
bool disable_custom_callbacks = !scroll_state.isDirectManipulation() &&
!GetDocument()
.GetPage()
->GlobalRootScrollerController()
.IsViewportScrollCallback(callback);
disable_custom_callbacks |=
!RootScrollerUtil::IsGlobal(this) &&
RuntimeEnabledFeatures::ScrollCustomizationEnabled() &&
!GetScrollCustomizationCallbacks().InScrollPhase(this);
if (!callback || disable_custom_callbacks) {
NativeApplyScroll(scroll_state);
return;
}
if (callback->NativeScrollBehavior() !=
WebNativeScrollBehavior::kPerformAfterNativeScroll)
callback->Invoke(&scroll_state);
if (callback->NativeScrollBehavior() !=
WebNativeScrollBehavior::kDisableNativeScroll)
NativeApplyScroll(scroll_state);
if (callback->NativeScrollBehavior() ==
WebNativeScrollBehavior::kPerformAfterNativeScroll)
callback->Invoke(&scroll_state);
}
int Element::OffsetLeft() {
GetDocument().EnsurePaintLocationDataValidForNode(this);
if (LayoutBoxModelObject* layout_object = GetLayoutBoxModelObject())
return AdjustForAbsoluteZoom::AdjustLayoutUnit(
LayoutUnit(
layout_object->PixelSnappedOffsetLeft(OffsetParent())),
layout_object->StyleRef())
.Round();
return 0;
}
int Element::OffsetTop() {
GetDocument().EnsurePaintLocationDataValidForNode(this);
if (LayoutBoxModelObject* layout_object = GetLayoutBoxModelObject())
return AdjustForAbsoluteZoom::AdjustLayoutUnit(
LayoutUnit(layout_object->PixelSnappedOffsetTop(OffsetParent())),
layout_object->StyleRef())
.Round();
return 0;
}
int Element::OffsetWidth() {
GetDocument().EnsurePaintLocationDataValidForNode(this);
if (LayoutBoxModelObject* layout_object = GetLayoutBoxModelObject())
return AdjustForAbsoluteZoom::AdjustLayoutUnit(
LayoutUnit(
layout_object->PixelSnappedOffsetWidth(OffsetParent())),
layout_object->StyleRef())
.Round();
return 0;
}
int Element::OffsetHeight() {
GetDocument().EnsurePaintLocationDataValidForNode(this);
if (LayoutBoxModelObject* layout_object = GetLayoutBoxModelObject())
return AdjustForAbsoluteZoom::AdjustLayoutUnit(
LayoutUnit(
layout_object->PixelSnappedOffsetHeight(OffsetParent())),
layout_object->StyleRef())
.Round();
return 0;
}
Element* Element::OffsetParent() {
GetDocument().UpdateStyleAndLayoutIgnorePendingStylesheetsForNode(this);
LayoutObject* layout_object = GetLayoutObject();
return layout_object ? layout_object->OffsetParent() : nullptr;
}
int Element::clientLeft() {
GetDocument().UpdateStyleAndLayoutIgnorePendingStylesheetsForNode(this);
if (LayoutBox* layout_object = GetLayoutBox())
return AdjustForAbsoluteZoom::AdjustLayoutUnit(layout_object->ClientLeft(),
layout_object->StyleRef())
.Round();
return 0;
}
int Element::clientTop() {
GetDocument().UpdateStyleAndLayoutIgnorePendingStylesheetsForNode(this);
if (LayoutBox* layout_object = GetLayoutBox())
return AdjustForAbsoluteZoom::AdjustLayoutUnit(layout_object->ClientTop(),
layout_object->StyleRef())
.Round();
return 0;
}
int Element::clientWidth() {
// When in strict mode, clientWidth for the document element should return the
// width of the containing frame.
// When in quirks mode, clientWidth for the body element should return the
// width of the containing frame.
bool in_quirks_mode = GetDocument().InQuirksMode();
if ((!in_quirks_mode && GetDocument().documentElement() == this) ||
(in_quirks_mode && IsHTMLElement() && GetDocument().body() == this)) {
auto* layout_view = GetDocument().GetLayoutView();
if (layout_view) {
if (!RuntimeEnabledFeatures::OverlayScrollbarsEnabled() ||
!GetDocument().GetFrame()->IsLocalRoot())
GetDocument().UpdateStyleAndLayoutIgnorePendingStylesheetsForNode(this);
if (GetDocument().GetPage()->GetSettings().GetForceZeroLayoutHeight())
return AdjustForAbsoluteZoom::AdjustLayoutUnit(
layout_view->OverflowClipRect(LayoutPoint()).Width(),
layout_view->StyleRef())
.Round();
return AdjustForAbsoluteZoom::AdjustLayoutUnit(
LayoutUnit(layout_view->GetLayoutSize().Width()),
layout_view->StyleRef())
.Round();
}
}
GetDocument().UpdateStyleAndLayoutIgnorePendingStylesheetsForNode(this);
if (LayoutBox* layout_object = GetLayoutBox())
return AdjustForAbsoluteZoom::AdjustLayoutUnit(
LayoutUnit(layout_object->PixelSnappedClientWidth()),
layout_object->StyleRef())
.Round();
return 0;
}
int Element::clientHeight() {
// When in strict mode, clientHeight for the document element should return
// the height of the containing frame.
// When in quirks mode, clientHeight for the body element should return the
// height of the containing frame.
bool in_quirks_mode = GetDocument().InQuirksMode();
if ((!in_quirks_mode && GetDocument().documentElement() == this) ||
(in_quirks_mode && IsHTMLElement() && GetDocument().body() == this)) {
auto* layout_view = GetDocument().GetLayoutView();
if (layout_view) {
if (!RuntimeEnabledFeatures::OverlayScrollbarsEnabled() ||
!GetDocument().GetFrame()->IsLocalRoot())
GetDocument().UpdateStyleAndLayoutIgnorePendingStylesheetsForNode(this);
if (GetDocument().GetPage()->GetSettings().GetForceZeroLayoutHeight())
return AdjustForAbsoluteZoom::AdjustLayoutUnit(
layout_view->OverflowClipRect(LayoutPoint()).Height(),
layout_view->StyleRef())
.Round();
return AdjustForAbsoluteZoom::AdjustLayoutUnit(
LayoutUnit(layout_view->GetLayoutSize().Height()),
layout_view->StyleRef())
.Round();
}
}
GetDocument().UpdateStyleAndLayoutIgnorePendingStylesheetsForNode(this);
if (LayoutBox* layout_object = GetLayoutBox())
return AdjustForAbsoluteZoom::AdjustLayoutUnit(
LayoutUnit(layout_object->PixelSnappedClientHeight()),
layout_object->StyleRef())
.Round();
return 0;
}
double Element::scrollLeft() {
if (!InActiveDocument())
return 0;
GetDocument().UpdateStyleAndLayoutIgnorePendingStylesheetsForNode(this);
if (GetDocument().ScrollingElementNoLayout() == this) {
if (GetDocument().domWindow())
return GetDocument().domWindow()->scrollX();
return 0;
}
if (LayoutBox* box = GetLayoutBox()) {
return AdjustForAbsoluteZoom::AdjustScroll(box->ScrollLeft(), *box);
}
return 0;
}
double Element::scrollTop() {
if (!InActiveDocument())
return 0;
GetDocument().UpdateStyleAndLayoutIgnorePendingStylesheetsForNode(this);
if (GetDocument().ScrollingElementNoLayout() == this) {
if (GetDocument().domWindow())
return GetDocument().domWindow()->scrollY();
return 0;
}
if (LayoutBox* box = GetLayoutBox()) {
return AdjustForAbsoluteZoom::AdjustScroll(box->ScrollTop(), *box);
}
return 0;
}
void Element::setScrollLeft(double new_left) {
if (!InActiveDocument())
return;
GetDocument().UpdateStyleAndLayoutIgnorePendingStylesheetsForNode(this);
new_left = ScrollableArea::NormalizeNonFiniteScroll(new_left);
if (GetDocument().ScrollingElementNoLayout() == this) {
if (LocalDOMWindow* window = GetDocument().domWindow()) {
ScrollToOptions options;
options.setLeft(new_left);
window->scrollTo(options);
}
} else {
LayoutBox* box = GetLayoutBox();
if (!box)
return;
FloatPoint end_point(new_left * box->Style()->EffectiveZoom(),
box->ScrollTop().ToFloat());
if (RuntimeEnabledFeatures::CSSScrollSnapPointsEnabled()) {
end_point = GetDocument()
.GetSnapCoordinator()
->GetSnapPositionForPoint(*box, end_point, true, false)
.value_or(end_point);
}
box->SetScrollLeft(LayoutUnit::FromFloatRound(end_point.X()));
}
}
void Element::setScrollTop(double new_top) {
if (!InActiveDocument())
return;
GetDocument().UpdateStyleAndLayoutIgnorePendingStylesheetsForNode(this);
new_top = ScrollableArea::NormalizeNonFiniteScroll(new_top);
if (GetDocument().ScrollingElementNoLayout() == this) {
if (LocalDOMWindow* window = GetDocument().domWindow()) {
ScrollToOptions options;
options.setTop(new_top);
window->scrollTo(options);
}
} else {
LayoutBox* box = GetLayoutBox();
if (!box)
return;
FloatPoint end_point(box->ScrollLeft().ToFloat(),
new_top * box->Style()->EffectiveZoom());
if (RuntimeEnabledFeatures::CSSScrollSnapPointsEnabled()) {
end_point = GetDocument()
.GetSnapCoordinator()
->GetSnapPositionForPoint(*box, end_point, false, true)
.value_or(end_point);
}
box->SetScrollTop(LayoutUnit::FromFloatRound(end_point.Y()));
}
}
int Element::scrollWidth() {
if (!InActiveDocument())
return 0;
GetDocument().UpdateStyleAndLayoutIgnorePendingStylesheetsForNode(this);
if (GetDocument().ScrollingElementNoLayout() == this) {
if (GetDocument().View()) {
return AdjustForAbsoluteZoom::AdjustInt(
GetDocument().View()->LayoutViewport()->ContentsSize().Width(),
GetDocument().GetFrame()->PageZoomFactor());
}
return 0;
}
if (LayoutBox* box = GetLayoutBox()) {
return AdjustForAbsoluteZoom::AdjustInt(box->PixelSnappedScrollWidth(),
box);
}
return 0;
}
int Element::scrollHeight() {
if (!InActiveDocument())
return 0;
GetDocument().UpdateStyleAndLayoutIgnorePendingStylesheetsForNode(this);
if (GetDocument().ScrollingElementNoLayout() == this) {
if (GetDocument().View()) {
return AdjustForAbsoluteZoom::AdjustInt(
GetDocument().View()->LayoutViewport()->ContentsSize().Height(),
GetDocument().GetFrame()->PageZoomFactor());
}
return 0;
}
if (LayoutBox* box = GetLayoutBox()) {
return AdjustForAbsoluteZoom::AdjustInt(box->PixelSnappedScrollHeight(),
box);
}
return 0;
}
void Element::scrollBy(double x, double y) {
ScrollToOptions scroll_to_options;
scroll_to_options.setLeft(x);
scroll_to_options.setTop(y);
scrollBy(scroll_to_options);
}
void Element::scrollBy(const ScrollToOptions& scroll_to_options) {
if (!InActiveDocument())
return;
// FIXME: This should be removed once scroll updates are processed only after
// the compositing update. See http://crbug.com/420741.
GetDocument().UpdateStyleAndLayoutIgnorePendingStylesheetsForNode(this);
if (GetDocument().ScrollingElementNoLayout() == this) {
ScrollFrameBy(scroll_to_options);
} else {
ScrollLayoutBoxBy(scroll_to_options);
}
}
void Element::scrollTo(double x, double y) {
ScrollToOptions scroll_to_options;
scroll_to_options.setLeft(x);
scroll_to_options.setTop(y);
scrollTo(scroll_to_options);
}
void Element::scrollTo(const ScrollToOptions& scroll_to_options) {
if (!InActiveDocument())
return;
// FIXME: This should be removed once scroll updates are processed only after
// the compositing update. See http://crbug.com/420741.
GetDocument().UpdateStyleAndLayoutIgnorePendingStylesheetsForNode(this);
if (GetDocument().ScrollingElementNoLayout() == this) {
ScrollFrameTo(scroll_to_options);
} else {
ScrollLayoutBoxTo(scroll_to_options);
}
}
void Element::ScrollLayoutBoxBy(const ScrollToOptions& scroll_to_options) {
double left =
scroll_to_options.hasLeft()
? ScrollableArea::NormalizeNonFiniteScroll(scroll_to_options.left())
: 0.0;
double top =
scroll_to_options.hasTop()
? ScrollableArea::NormalizeNonFiniteScroll(scroll_to_options.top())
: 0.0;
ScrollBehavior scroll_behavior = kScrollBehaviorAuto;
ScrollableArea::ScrollBehaviorFromString(scroll_to_options.behavior(),
scroll_behavior);
LayoutBox* box = GetLayoutBox();
if (box) {
float current_scaled_left = box->ScrollLeft().ToFloat();
float current_scaled_top = box->ScrollTop().ToFloat();
float new_scaled_left =
left * box->Style()->EffectiveZoom() + current_scaled_left;
float new_scaled_top =
top * box->Style()->EffectiveZoom() + current_scaled_top;
FloatPoint new_scaled_position(new_scaled_left, new_scaled_top);
if (RuntimeEnabledFeatures::CSSScrollSnapPointsEnabled()) {
new_scaled_position =
GetDocument()
.GetSnapCoordinator()
->GetSnapPositionForPoint(*box, new_scaled_position,
scroll_to_options.hasLeft(),
scroll_to_options.hasTop())
.value_or(new_scaled_position);
}
box->ScrollToPosition(new_scaled_position, scroll_behavior);
}
}
void Element::ScrollLayoutBoxTo(const ScrollToOptions& scroll_to_options) {
ScrollBehavior scroll_behavior = kScrollBehaviorAuto;
ScrollableArea::ScrollBehaviorFromString(scroll_to_options.behavior(),
scroll_behavior);
LayoutBox* box = GetLayoutBox();
if (box) {
float scaled_left = box->ScrollLeft().ToFloat();
float scaled_top = box->ScrollTop().ToFloat();
if (scroll_to_options.hasLeft())
scaled_left =
ScrollableArea::NormalizeNonFiniteScroll(scroll_to_options.left()) *
box->Style()->EffectiveZoom();
if (scroll_to_options.hasTop())
scaled_top =
ScrollableArea::NormalizeNonFiniteScroll(scroll_to_options.top()) *
box->Style()->EffectiveZoom();
FloatPoint new_scaled_position(scaled_left, scaled_top);
if (RuntimeEnabledFeatures::CSSScrollSnapPointsEnabled()) {
new_scaled_position =
GetDocument()
.GetSnapCoordinator()
->GetSnapPositionForPoint(*box, new_scaled_position,
scroll_to_options.hasLeft(),
scroll_to_options.hasTop())
.value_or(new_scaled_position);
}
box->ScrollToPosition(new_scaled_position, scroll_behavior);
}
}
void Element::ScrollFrameBy(const ScrollToOptions& scroll_to_options) {
double left =
scroll_to_options.hasLeft()
? ScrollableArea::NormalizeNonFiniteScroll(scroll_to_options.left())
: 0.0;
double top =
scroll_to_options.hasTop()
? ScrollableArea::NormalizeNonFiniteScroll(scroll_to_options.top())
: 0.0;
ScrollBehavior scroll_behavior = kScrollBehaviorAuto;
ScrollableArea::ScrollBehaviorFromString(scroll_to_options.behavior(),
scroll_behavior);
LocalFrame* frame = GetDocument().GetFrame();
if (!frame || !frame->View() || !GetDocument().GetPage())
return;
ScrollableArea* viewport = frame->View()->LayoutViewport();
if (!viewport)
return;
// TODO(810510): Move this logic inside "ScrollableArea::SetScrollOffset" and
// rely on ScrollType to detect js scrolls and set the flag. This requires
// adding new scroll type to enable this. if (GetDocument().Loader())
GetDocument().Loader()->GetInitialScrollState().was_scrolled_by_js = true;
float new_scaled_left =
left * frame->PageZoomFactor() + viewport->GetScrollOffset().Width();
float new_scaled_top =
top * frame->PageZoomFactor() + viewport->GetScrollOffset().Height();
FloatPoint new_scaled_position = viewport->ScrollOffsetToPosition(
ScrollOffset(new_scaled_left, new_scaled_top));
if (RuntimeEnabledFeatures::CSSScrollSnapPointsEnabled()) {
new_scaled_position =
GetDocument()
.GetSnapCoordinator()
->GetSnapPositionForPoint(
*GetDocument().GetLayoutView(), new_scaled_position,
scroll_to_options.hasLeft(), scroll_to_options.hasTop())
.value_or(new_scaled_position);
}
viewport->SetScrollOffset(
viewport->ScrollPositionToOffset(new_scaled_position),
kProgrammaticScroll, scroll_behavior);
}
void Element::ScrollFrameTo(const ScrollToOptions& scroll_to_options) {
ScrollBehavior scroll_behavior = kScrollBehaviorAuto;
ScrollableArea::ScrollBehaviorFromString(scroll_to_options.behavior(),
scroll_behavior);
LocalFrame* frame = GetDocument().GetFrame();
if (!frame || !frame->View() || !GetDocument().GetPage())
return;
ScrollableArea* viewport = frame->View()->LayoutViewport();
if (!viewport)
return;
// TODO(810510): Move this logic inside "ScrollableArea::SetScrollOffset" and
// rely on ScrollType to detect js scrolls and set the flag. This requires
// adding new scroll type to enable this.
if (GetDocument().Loader())
GetDocument().Loader()->GetInitialScrollState().was_scrolled_by_js = true;
float scaled_left = viewport->GetScrollOffset().Width();
float scaled_top = viewport->GetScrollOffset().Height();
if (scroll_to_options.hasLeft())
scaled_left =
ScrollableArea::NormalizeNonFiniteScroll(scroll_to_options.left()) *
frame->PageZoomFactor();
if (scroll_to_options.hasTop())
scaled_top =
ScrollableArea::NormalizeNonFiniteScroll(scroll_to_options.top()) *
frame->PageZoomFactor();
FloatPoint new_scaled_position =
viewport->ScrollOffsetToPosition(ScrollOffset(scaled_left, scaled_top));
if (RuntimeEnabledFeatures::CSSScrollSnapPointsEnabled()) {
new_scaled_position =
GetDocument()
.GetSnapCoordinator()
->GetSnapPositionForPoint(
*GetDocument().GetLayoutView(), new_scaled_position,
scroll_to_options.hasLeft(), scroll_to_options.hasTop())
.value_or(new_scaled_position);
}
viewport->SetScrollOffset(
viewport->ScrollPositionToOffset(new_scaled_position),
kProgrammaticScroll, scroll_behavior);
}
bool Element::HasNonEmptyLayoutSize() const {
GetDocument().UpdateStyleAndLayoutIgnorePendingStylesheets();
if (LayoutBoxModelObject* box = GetLayoutBoxModelObject())
return box->HasNonEmptyLayoutSize();
return false;
}
IntRect Element::BoundsInViewport() const {
GetDocument().EnsurePaintLocationDataValidForNode(this);
LocalFrameView* view = GetDocument().View();
if (!view)
return IntRect();
Vector<FloatQuad> quads;
// TODO(pdr): Unify the quad/bounds code with Element::ClientQuads.
// Foreign objects need to convert between SVG and HTML coordinate spaces and
// cannot use LocalToAbsoluteQuad directly with ObjectBoundingBox which is
// SVG coordinates and not HTML coordinates. Instead, use the AbsoluteQuads
// codepath below.
if (IsSVGElement() && GetLayoutObject() &&
!GetLayoutObject()->IsSVGForeignObject()) {
// Get the bounding rectangle from the SVG model.
// TODO(pdr): This should include stroke.
if (ToSVGElement(this)->IsSVGGraphicsElement())
quads.push_back(GetLayoutObject()->LocalToAbsoluteQuad(
GetLayoutObject()->ObjectBoundingBox()));
} else {
// Get the bounding rectangle from the box model.
if (GetLayoutBoxModelObject())
GetLayoutBoxModelObject()->AbsoluteQuads(quads);
}
if (quads.IsEmpty())
return IntRect();
IntRect result = quads[0].EnclosingBoundingBox();
for (size_t i = 1; i < quads.size(); ++i)
result.Unite(quads[i].EnclosingBoundingBox());
return view->FrameToViewport(result);
}
IntRect Element::VisibleBoundsInVisualViewport() const {
if (!GetLayoutObject() || !GetDocument().GetPage() ||
!GetDocument().GetFrame())
return IntRect();
// We don't use absoluteBoundingBoxRect() because it can return an IntRect
// larger the actual size by 1px. crbug.com/470503
LayoutRect rect(
RoundedIntRect(GetLayoutObject()->AbsoluteBoundingBoxFloatRect()));
LayoutRect frame_clip_rect =
GetDocument().View()->GetLayoutView()->ClippingRect(LayoutPoint());
rect.Intersect(frame_clip_rect);
// MapToVisualRectInAncestorSpace, called with a null ancestor argument,
// returns the viewport-visible rect in the local frame root's coordinates,
// accounting for clips and transformed in embedding containers. This
// includes clips that might be applied by out-of-process frame ancestors.
GetDocument().View()->GetLayoutView()->MapToVisualRectInAncestorSpace(
nullptr, rect, kUseTransforms | kTraverseDocumentBoundaries,
kDefaultVisualRectFlags);
IntRect visible_rect = PixelSnappedIntRect(rect);
// If the rect is in the coordinates of the main frame, then it should
// also be clipped to the viewport to account for page scale. For OOPIFs,
// local frame root -> viewport coordinate conversion is done in the
// browser process.
if (GetDocument().GetFrame()->LocalFrameRoot().IsMainFrame()) {
IntSize viewport_size = GetDocument().GetPage()->GetVisualViewport().Size();
visible_rect =
GetDocument().GetPage()->GetVisualViewport().RootFrameToViewport(
visible_rect);
visible_rect.Intersect(IntRect(IntPoint(), viewport_size));
}
return visible_rect;
}
void Element::ClientQuads(Vector<FloatQuad>& quads) {
GetDocument().EnsurePaintLocationDataValidForNode(this);
LayoutObject* element_layout_object = GetLayoutObject();
if (!element_layout_object)
return;
// Foreign objects need to convert between SVG and HTML coordinate spaces and
// cannot use LocalToAbsoluteQuad directly with ObjectBoundingBox which is
// SVG coordinates and not HTML coordinates. Instead, use the AbsoluteQuads
// codepath below.
if (IsSVGElement() && !element_layout_object->IsSVGRoot() &&
!element_layout_object->IsSVGForeignObject()) {
// Get the bounding rectangle from the SVG model.
// TODO(pdr): ObjectBoundingBox does not include stroke and the spec is not
// clear (see: https://github.com/w3c/svgwg/issues/339, crbug.com/529734).
// If stroke is desired, we can update this to use AbsoluteQuads, below.
if (ToSVGElement(this)->IsSVGGraphicsElement())
quads.push_back(element_layout_object->LocalToAbsoluteQuad(
element_layout_object->ObjectBoundingBox()));
return;
}
// FIXME: Handle table/inline-table with a caption.
if (element_layout_object->IsBoxModelObject() ||
element_layout_object->IsBR())
element_layout_object->AbsoluteQuads(quads, kUseTransforms);
}
DOMRectList* Element::getClientRects() {
Vector<FloatQuad> quads;
ClientQuads(quads);
if (quads.IsEmpty())
return DOMRectList::Create();
LayoutObject* element_layout_object = GetLayoutObject();
DCHECK(element_layout_object);
GetDocument().AdjustFloatQuadsForScrollAndAbsoluteZoom(
quads, *element_layout_object);
return DOMRectList::Create(quads);
}
DOMRect* Element::getBoundingClientRect() {
Vector<FloatQuad> quads;
ClientQuads(quads);
if (quads.IsEmpty())
return DOMRect::Create();
FloatRect result = quads[0].BoundingBox();
for (size_t i = 1; i < quads.size(); ++i)
result.Unite(quads[i].BoundingBox());
LayoutObject* element_layout_object = GetLayoutObject();
DCHECK(element_layout_object);
GetDocument().AdjustFloatRectForScrollAndAbsoluteZoom(result,
*element_layout_object);
return DOMRect::FromFloatRect(result);
}
const AtomicString& Element::computedRole() {
Document& document = GetDocument();
if (!document.IsActive())
return g_null_atom;
document.UpdateStyleAndLayoutIgnorePendingStylesheetsForNode(this);
AXContext ax_context(document);
return ax_context.GetAXObjectCache().ComputedRoleForNode(this);
}
String Element::computedName() {
Document& document = GetDocument();
if (!document.IsActive())
return String();
document.UpdateStyleAndLayoutIgnorePendingStylesheetsForNode(this);
AXContext ax_context(document);
return ax_context.GetAXObjectCache().ComputedNameForNode(this);
}
AccessibleNode* Element::ExistingAccessibleNode() const {
if (!RuntimeEnabledFeatures::AccessibilityObjectModelEnabled())
return nullptr;
if (!HasRareData())
return nullptr;
return GetElementRareData()->GetAccessibleNode();
}
AccessibleNode* Element::accessibleNode() {
if (!RuntimeEnabledFeatures::AccessibilityObjectModelEnabled())
return nullptr;
ElementRareData& rare_data = EnsureElementRareData();
return rare_data.EnsureAccessibleNode(this);
}
const AtomicString& Element::invisible() const {
return FastGetAttribute(invisibleAttr);
}
void Element::setInvisible(const AtomicString& value) {
setAttribute(invisibleAttr, value);
}
void Element::DispatchActivateInvisibleEventIfNeeded() {
if (!RuntimeEnabledFeatures::InvisibleDOMEnabled())
return;
// Traverse all inclusive flat-tree ancestor and send activateinvisible
// on the ones that have the invisible attribute. Default event handler
// will remove invisible attribute of all invisible element if the event is
// not canceled, making this element and all ancestors visible again.
// We're saving them and the retargeted activated element as DOM structure
// may change due to event handlers.
HeapVector<Member<Element>> invisible_ancestors;
HeapVector<Member<Element>> activated_elements;
for (Node& ancestor : FlatTreeTraversal::InclusiveAncestorsOf(*this)) {
if (ancestor.IsElementNode() && ToElement(ancestor).invisible()) {
invisible_ancestors.push_back(ToElement(ancestor));
activated_elements.push_back(ancestor.GetTreeScope().Retarget(*this));
}
}
auto* activated_element_iterator = activated_elements.begin();
for (Element* ancestor : invisible_ancestors) {
DCHECK(activated_element_iterator != activated_elements.end());
ancestor->DispatchEvent(
*ActivateInvisibleEvent::Create(*activated_element_iterator));
++activated_element_iterator;
}
}
void Element::InvisibleAttributeChanged() {
SetNeedsStyleRecalc(
kLocalStyleChange,
StyleChangeReasonForTracing::Create(StyleChangeReason::kInvisibleChange));
}
void Element::DefaultEventHandler(Event& event) {
if (RuntimeEnabledFeatures::InvisibleDOMEnabled() &&
event.type() == EventTypeNames::activateinvisible &&
event.target() == this) {
removeAttribute(invisibleAttr);
event.SetDefaultHandled();
return;
}
ContainerNode::DefaultEventHandler(event);
}
bool Element::toggleAttribute(const AtomicString& qualified_name,
ExceptionState& exception_state) {
// https://dom.spec.whatwg.org/#dom-element-toggleattribute
// 1. If qualifiedName does not match the Name production in XML, then throw
// an "InvalidCharacterError" DOMException.
if (!Document::IsValidName(qualified_name)) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidCharacterError,
"'" + qualified_name + "' is not a valid attribute name.");
return false;
}
// 2. If the context object is in the HTML namespace and its node document is
// an HTML document, then set qualifiedName to qualifiedName in ASCII
// lowercase.
AtomicString lower_case_name = LowercaseIfNecessary(qualified_name);
// 3. Let attribute be the first attribute in the context object’s attribute
// list whose qualified name is qualifiedName, and null otherwise.
// 4. If attribute is null, then
if (!getAttribute(lower_case_name)) {
// 4. 1. If force is not given or is true, create an attribute whose local
// name is qualifiedName, value is the empty string, and node document is
// the context object’s node document, then append this attribute to the
// context object, and then return true.
setAttribute(lower_case_name, g_empty_atom);
return true;
}
// 5. Otherwise, if force is not given or is false, remove an attribute given
// qualifiedName and the context object, and then return false.
removeAttribute(lower_case_name);
return false;
}
bool Element::toggleAttribute(const AtomicString& qualified_name,
bool force,
ExceptionState& exception_state) {
// https://dom.spec.whatwg.org/#dom-element-toggleattribute
// 1. If qualifiedName does not match the Name production in XML, then throw
// an "InvalidCharacterError" DOMException.
if (!Document::IsValidName(qualified_name)) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidCharacterError,
"'" + qualified_name + "' is not a valid attribute name.");
return false;
}
// 2. If the context object is in the HTML namespace and its node document is
// an HTML document, then set qualifiedName to qualifiedName in ASCII
// lowercase.
AtomicString lower_case_name = LowercaseIfNecessary(qualified_name);
// 3. Let attribute be the first attribute in the context object’s attribute
// list whose qualified name is qualifiedName, and null otherwise.
// 4. If attribute is null, then
if (!getAttribute(lower_case_name)) {
// 4. 1. If force is not given or is true, create an attribute whose local
// name is qualifiedName, value is the empty string, and node document is
// the context object’s node document, then append this attribute to the
// context object, and then return true.
if (force) {
setAttribute(lower_case_name, g_empty_atom);
return true;
}
// 4. 2. Return false.
return false;
}
// 5. Otherwise, if force is not given or is false, remove an attribute given
// qualifiedName and the context object, and then return false.
if (!force) {
removeAttribute(lower_case_name);
return false;
}
// 6. Return true.
return true;
}
const AtomicString& Element::getAttribute(
const AtomicString& local_name) const {
if (!GetElementData())
return g_null_atom;
SynchronizeAttribute(local_name);
if (const Attribute* attribute =
GetElementData()->Attributes().Find(LowercaseIfNecessary(local_name)))
return attribute->Value();
return g_null_atom;
}
const AtomicString& Element::getAttributeNS(
const AtomicString& namespace_uri,
const AtomicString& local_name) const {
return getAttribute(QualifiedName(g_null_atom, local_name, namespace_uri));
}
void Element::setAttribute(const AtomicString& local_name,
const AtomicString& value,
ExceptionState& exception_state) {
if (!Document::IsValidName(local_name)) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidCharacterError,
"'" + local_name + "' is not a valid attribute name.");
return;
}
SynchronizeAttribute(local_name);
AtomicString case_adjusted_local_name = LowercaseIfNecessary(local_name);
if (!GetElementData()) {
SetAttributeInternal(
kNotFound,
QualifiedName(g_null_atom, case_adjusted_local_name, g_null_atom),
value, kNotInSynchronizationOfLazyAttribute);
return;
}
AttributeCollection attributes = GetElementData()->Attributes();
size_t index = attributes.FindIndex(case_adjusted_local_name);
const QualifiedName& q_name =
index != kNotFound
? attributes[index].GetName()
: QualifiedName(g_null_atom, case_adjusted_local_name, g_null_atom);
SetAttributeInternal(index, q_name, value,
kNotInSynchronizationOfLazyAttribute);
}
void Element::setAttribute(const AtomicString& name,
const AtomicString& value) {
setAttribute(name, value, ASSERT_NO_EXCEPTION);
}
void Element::setAttribute(const QualifiedName& name,
const AtomicString& value) {
SynchronizeAttribute(name);
size_t index = GetElementData()
? GetElementData()->Attributes().FindIndex(name)
: kNotFound;
SetAttributeInternal(index, name, value,
kNotInSynchronizationOfLazyAttribute);
}
void Element::SetSynchronizedLazyAttribute(const QualifiedName& name,
const AtomicString& value) {
size_t index = GetElementData()
? GetElementData()->Attributes().FindIndex(name)
: kNotFound;
SetAttributeInternal(index, name, value, kInSynchronizationOfLazyAttribute);
}
void Element::setAttribute(const QualifiedName& name,
const StringOrTrustedHTML& stringOrHTML,
ExceptionState& exception_state) {
String valueString =
TrustedHTML::GetString(stringOrHTML, &GetDocument(), exception_state);
if (!exception_state.HadException()) {
setAttribute(name, AtomicString(valueString));
}
}
void Element::setAttribute(const QualifiedName& name,
const StringOrTrustedScriptURL& stringOrURL,
ExceptionState& exception_state) {
DCHECK(stringOrURL.IsString() ||
RuntimeEnabledFeatures::TrustedDOMTypesEnabled());
if (stringOrURL.IsString() && GetDocument().RequireTrustedTypes()) {
exception_state.ThrowTypeError(
"This document requires `TrustedScriptURL` assignment.");
return;
}
String valueString = stringOrURL.IsString()
? stringOrURL.GetAsString()
: stringOrURL.GetAsTrustedScriptURL()->toString();
setAttribute(name, AtomicString(valueString));
}
void Element::setAttribute(const QualifiedName& name,
const USVStringOrTrustedURL& stringOrURL,
ExceptionState& exception_state) {
String url =
TrustedURL::GetString(stringOrURL, &GetDocument(), exception_state);
if (!exception_state.HadException()) {
setAttribute(name, AtomicString(url));
}
}
ALWAYS_INLINE void Element::SetAttributeInternal(
size_t index,
const QualifiedName& name,
const AtomicString& new_value,
SynchronizationOfLazyAttribute in_synchronization_of_lazy_attribute) {
if (new_value.IsNull()) {
if (index != kNotFound)
RemoveAttributeInternal(index, in_synchronization_of_lazy_attribute);
return;
}
if (index == kNotFound) {
AppendAttributeInternal(name, new_value,
in_synchronization_of_lazy_attribute);
return;
}
const Attribute& existing_attribute =
GetElementData()->Attributes().at(index);
AtomicString existing_attribute_value = existing_attribute.Value();
QualifiedName existing_attribute_name = existing_attribute.GetName();
if (!in_synchronization_of_lazy_attribute)
WillModifyAttribute(existing_attribute_name, existing_attribute_value,
new_value);
if (new_value != existing_attribute_value)
EnsureUniqueElementData().Attributes().at(index).SetValue(new_value);
if (!in_synchronization_of_lazy_attribute)
DidModifyAttribute(existing_attribute_name, existing_attribute_value,
new_value);
}
static inline AtomicString MakeIdForStyleResolution(const AtomicString& value,
bool in_quirks_mode) {
if (in_quirks_mode)
return value.LowerASCII();
return value;
}
DISABLE_CFI_PERF
void Element::AttributeChanged(const AttributeModificationParams& params) {
const QualifiedName& name = params.name;
if (ShadowRoot* parent_shadow_root =
ShadowRootWhereNodeCanBeDistributedForV0(*this)) {
if (ShouldInvalidateDistributionWhenAttributeChanged(
*parent_shadow_root, name, params.new_value))
parent_shadow_root->SetNeedsDistributionRecalc();
}
if (name == HTMLNames::slotAttr && params.old_value != params.new_value) {
if (ShadowRoot* root = V1ShadowRootOfParent())
root->DidChangeHostChildSlotName(params.old_value, params.new_value);
}
ParseAttribute(params);
GetDocument().IncDOMTreeVersion();
if (name == HTMLNames::idAttr) {
AtomicString old_id = GetElementData()->IdForStyleResolution();
AtomicString new_id = MakeIdForStyleResolution(
params.new_value, GetDocument().InQuirksMode());
if (new_id != old_id) {
GetElementData()->SetIdForStyleResolution(new_id);
GetDocument().GetStyleEngine().IdChangedForElement(old_id, new_id, *this);
}
} else if (name == classAttr) {
ClassAttributeChanged(params.new_value);
if (HasRareData() && GetElementRareData()->GetClassList()) {
GetElementRareData()->GetClassList()->DidUpdateAttributeValue(
params.old_value, params.new_value);
}
} else if (name == HTMLNames::nameAttr) {
SetHasName(!params.new_value.IsNull());
} else if (name == HTMLNames::partAttr) {
if (RuntimeEnabledFeatures::CSSPartPseudoElementEnabled()) {
EnsureElementRareData().SetPart(params.new_value);
GetDocument().GetStyleEngine().PartChangedForElement(*this);
}
} else if (name == HTMLNames::partmapAttr) {
if (RuntimeEnabledFeatures::CSSPartPseudoElementEnabled()) {
EnsureElementRareData().SetPartNamesMap(params.new_value);
GetDocument().GetStyleEngine().PartmapChangedForElement(*this);
}
} else if (IsStyledElement()) {
if (name == styleAttr) {
StyleAttributeChanged(params.new_value, params.reason);
} else if (IsPresentationAttribute(name)) {
GetElementData()->presentation_attribute_style_is_dirty_ = true;
SetNeedsStyleRecalc(kLocalStyleChange,
StyleChangeReasonForTracing::FromAttribute(name));
} else if (RuntimeEnabledFeatures::InvisibleDOMEnabled() &&
name == HTMLNames::invisibleAttr &&
params.old_value.IsNull() != params.new_value.IsNull()) {
InvisibleAttributeChanged();
}
}
InvalidateNodeListCachesInAncestors(&name, this, nullptr);
if (isConnected()) {
if (AXObjectCache* cache = GetDocument().ExistingAXObjectCache()) {
if (params.old_value != params.new_value)
cache->HandleAttributeChanged(name, this);
}
}
if (params.reason == AttributeModificationReason::kDirectly &&
name == tabindexAttr && AdjustedFocusedElementInTreeScope() == this) {
// The attribute change may cause supportsFocus() to return false
// for the element which had focus.
//
// TODO(tkent): We should avoid updating style. We'd like to check only
// DOM-level focusability here.
GetDocument().UpdateStyleAndLayoutTreeForNode(this);
if (!SupportsFocus())
blur();
}
}
bool Element::HasLegalLinkAttribute(const QualifiedName&) const {
return false;
}
const QualifiedName& Element::SubResourceAttributeName() const {
return QualifiedName::Null();
}
template <typename CharacterType>
static inline ClassStringContent ClassStringHasClassName(
const CharacterType* characters,
unsigned length) {
DCHECK_GT(length, 0u);
unsigned i = 0;
do {
if (IsNotHTMLSpace<CharacterType>(characters[i]))
break;
++i;
} while (i < length);
if (i == length && length >= 1)
return ClassStringContent::kWhiteSpaceOnly;
return ClassStringContent::kHasClasses;
}
static inline ClassStringContent ClassStringHasClassName(
const AtomicString& new_class_string) {
unsigned length = new_class_string.length();
if (!length)
return ClassStringContent::kEmpty;
if (new_class_string.Is8Bit())
return ClassStringHasClassName(new_class_string.Characters8(), length);
return ClassStringHasClassName(new_class_string.Characters16(), length);
}
void Element::ClassAttributeChanged(const AtomicString& new_class_string) {
DCHECK(GetElementData());
ClassStringContent class_string_content_type =
ClassStringHasClassName(new_class_string);
const bool should_fold_case = GetDocument().InQuirksMode();
if (class_string_content_type == ClassStringContent::kHasClasses) {
const SpaceSplitString old_classes = GetElementData()->ClassNames();
GetElementData()->SetClass(new_class_string, should_fold_case);
const SpaceSplitString& new_classes = GetElementData()->ClassNames();
GetDocument().GetStyleEngine().ClassChangedForElement(old_classes,
new_classes, *this);
} else {
const SpaceSplitString& old_classes = GetElementData()->ClassNames();
GetDocument().GetStyleEngine().ClassChangedForElement(old_classes, *this);
if (class_string_content_type == ClassStringContent::kWhiteSpaceOnly)
GetElementData()->SetClass(new_class_string, should_fold_case);
else
GetElementData()->ClearClass();
}
}
bool Element::ShouldInvalidateDistributionWhenAttributeChanged(
ShadowRoot& shadow_root,
const QualifiedName& name,
const AtomicString& new_value) {
if (shadow_root.IsV1())
return false;
const SelectRuleFeatureSet& feature_set =
shadow_root.V0().EnsureSelectFeatureSet();
if (name == HTMLNames::idAttr) {
AtomicString old_id = GetElementData()->IdForStyleResolution();
AtomicString new_id =
MakeIdForStyleResolution(new_value, GetDocument().InQuirksMode());
if (new_id != old_id) {
if (!old_id.IsEmpty() && feature_set.HasSelectorForId(old_id))
return true;
if (!new_id.IsEmpty() && feature_set.HasSelectorForId(new_id))
return true;
}
}
if (name == HTMLNames::classAttr) {
const AtomicString& new_class_string = new_value;
if (ClassStringHasClassName(new_class_string) ==
ClassStringContent::kHasClasses) {
const SpaceSplitString& old_classes = GetElementData()->ClassNames();
const SpaceSplitString new_classes(GetDocument().InQuirksMode()
? new_class_string.LowerASCII()
: new_class_string);
if (feature_set.CheckSelectorsForClassChange(old_classes, new_classes))
return true;
} else {
const SpaceSplitString& old_classes = GetElementData()->ClassNames();
if (feature_set.CheckSelectorsForClassChange(old_classes))
return true;
}
}
return feature_set.HasSelectorForAttribute(name.LocalName());
}
// Returns true if the given attribute is an event handler.
// We consider an event handler any attribute that begins with "on".
// It is a simple solution that has the advantage of not requiring any
// code or configuration change if a new event handler is defined.
static inline bool IsEventHandlerAttribute(const Attribute& attribute) {
return attribute.GetName().NamespaceURI().IsNull() &&
attribute.GetName().LocalName().StartsWith("on");
}
bool Element::AttributeValueIsJavaScriptURL(const Attribute& attribute) {
return ProtocolIsJavaScript(
StripLeadingAndTrailingHTMLSpaces(attribute.Value()));
}
bool Element::IsJavaScriptURLAttribute(const Attribute& attribute) const {
return IsURLAttribute(attribute) && AttributeValueIsJavaScriptURL(attribute);
}
bool Element::IsScriptingAttribute(const Attribute& attribute) const {
return IsEventHandlerAttribute(attribute) ||
IsJavaScriptURLAttribute(attribute) ||
IsHTMLContentAttribute(attribute) ||
IsSVGAnimationAttributeSettingJavaScriptURL(attribute);
}
void Element::StripScriptingAttributes(
Vector<Attribute>& attribute_vector) const {
size_t destination = 0;
for (size_t source = 0; source < attribute_vector.size(); ++source) {
if (IsScriptingAttribute(attribute_vector[source]))
continue;
if (source != destination)
attribute_vector[destination] = attribute_vector[source];
++destination;
}
attribute_vector.Shrink(destination);
}
void Element::ParserSetAttributes(const Vector<Attribute>& attribute_vector) {
DCHECK(!isConnected());
DCHECK(!parentNode());
DCHECK(!element_data_);
if (!attribute_vector.IsEmpty()) {
if (GetDocument().GetElementDataCache())
element_data_ =
GetDocument()
.GetElementDataCache()
->CachedShareableElementDataWithAttributes(attribute_vector);
else
element_data_ =
ShareableElementData::CreateWithAttributes(attribute_vector);
}
ParserDidSetAttributes();
// Use attributeVector instead of m_elementData because attributeChanged might
// modify m_elementData.
for (const auto& attribute : attribute_vector) {
AttributeChanged(AttributeModificationParams(
attribute.GetName(), g_null_atom, attribute.Value(),
AttributeModificationReason::kByParser));
}
}
bool Element::HasEquivalentAttributes(const Element* other) const {
SynchronizeAllAttributes();
other->SynchronizeAllAttributes();
if (GetElementData() == other->GetElementData())
return true;
if (GetElementData())
return GetElementData()->IsEquivalent(other->GetElementData());
if (other->GetElementData())
return other->GetElementData()->IsEquivalent(GetElementData());
return true;
}
String Element::nodeName() const {
return tag_name_.ToString();
}
AtomicString Element::LocalNameForSelectorMatching() const {
if (IsHTMLElement() || !GetDocument().IsHTMLDocument())
return localName();
return localName().DeprecatedLower();
}
const AtomicString& Element::LocateNamespacePrefix(
const AtomicString& namespace_to_locate) const {
if (!prefix().IsNull() && namespaceURI() == namespace_to_locate)
return prefix();
AttributeCollection attributes = Attributes();
for (const Attribute& attr : attributes) {
if (attr.Prefix() == g_xmlns_atom && attr.Value() == namespace_to_locate)
return attr.LocalName();
}
if (Element* parent = parentElement())
return parent->LocateNamespacePrefix(namespace_to_locate);
return g_null_atom;
}
const AtomicString Element::ImageSourceURL() const {
return getAttribute(srcAttr);
}
bool Element::LayoutObjectIsNeeded(const ComputedStyle& style) const {
return style.Display() != EDisplay::kNone &&
style.Display() != EDisplay::kContents;
}
LayoutObject* Element::CreateLayoutObject(const ComputedStyle& style) {
return LayoutObject::CreateObject(this, style);
}
Node::InsertionNotificationRequest Element::InsertedInto(
ContainerNode& insertion_point) {
// need to do superclass processing first so isConnected() is true
// by the time we reach updateId
ContainerNode::InsertedInto(insertion_point);
DCHECK(!HasRareData() || !GetElementRareData()->HasPseudoElements());
if (!insertion_point.IsInTreeScope())
return kInsertionDone;
if (HasRareData()) {
ElementRareData* rare_data = GetElementRareData();
if (rare_data->IntersectionObserverData())
rare_data->IntersectionObserverData()->ActivateValidIntersectionObservers(
*this);
}
if (isConnected()) {
if (GetCustomElementState() == CustomElementState::kCustom)
CustomElement::EnqueueConnectedCallback(this);
else if (IsUpgradedV0CustomElement())
V0CustomElement::DidAttach(this, GetDocument());
else if (GetCustomElementState() == CustomElementState::kUndefined)
CustomElement::TryToUpgrade(this);
}
TreeScope& scope = insertion_point.GetTreeScope();
if (scope != GetTreeScope())
return kInsertionDone;
const AtomicString& id_value = GetIdAttribute();
if (!id_value.IsNull())
UpdateId(scope, g_null_atom, id_value);
const AtomicString& name_value = GetNameAttribute();
if (!name_value.IsNull())
UpdateName(g_null_atom, name_value);
if (parentElement() && parentElement()->IsInCanvasSubtree())
SetIsInCanvasSubtree(true);
return kInsertionDone;
}
void Element::RemovedFrom(ContainerNode& insertion_point) {
bool was_in_document = insertion_point.isConnected();
if (HasRareData()) {
// If we detached the layout tree with LazyReattachIfAttached, we might not
// have cleared the pseudo elements if we remove the element before calling
// AttachLayoutTree again. We don't clear pseudo elements on
// DetachLayoutTree() if we intend to attach again to avoid recreating the
// pseudo elements.
GetElementRareData()->ClearPseudoElements();
}
if (Fullscreen::IsFullscreenElement(*this)) {
SetContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(false);
if (insertion_point.IsElementNode()) {
ToElement(insertion_point).SetContainsFullScreenElement(false);
ToElement(insertion_point)
.SetContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(
false);
}
}
if (GetDocument().GetPage())
GetDocument().GetPage()->GetPointerLockController().ElementRemoved(this);
SetSavedLayerScrollOffset(ScrollOffset());
if (insertion_point.IsInTreeScope() && GetTreeScope() == GetDocument()) {
const AtomicString& id_value = GetIdAttribute();
if (!id_value.IsNull())
UpdateId(insertion_point.GetTreeScope(), id_value, g_null_atom);
const AtomicString& name_value = GetNameAttribute();
if (!name_value.IsNull())
UpdateName(name_value, g_null_atom);
}
ContainerNode::RemovedFrom(insertion_point);
if (was_in_document) {
if (this == GetDocument().CssTarget())
GetDocument().SetCSSTarget(nullptr);
if (GetCustomElementState() == CustomElementState::kCustom)
CustomElement::EnqueueDisconnectedCallback(this);
else if (IsUpgradedV0CustomElement())
V0CustomElement::DidDetach(this, insertion_point.GetDocument());
if (NeedsStyleInvalidation()) {
GetDocument()
.GetStyleEngine()
.GetPendingNodeInvalidations()
.ClearInvalidation(*this);
}
}
GetDocument().GetRootScrollerController().ElementRemoved(*this);
if (IsInTopLayer()) {
Fullscreen::ElementRemoved(*this);
GetDocument().RemoveFromTopLayer(this);
}
ClearElementFlag(ElementFlags::kIsInCanvasSubtree);
if (HasRareData()) {
ElementRareData* data = GetElementRareData();
data->ClearRestyleFlags();
if (ElementAnimations* element_animations = data->GetElementAnimations())
element_animations->CssAnimations().Cancel();
if (data->IntersectionObserverData())
data->IntersectionObserverData()->DeactivateAllIntersectionObservers(
*this);
}
if (GetDocument().GetFrame())
GetDocument().GetFrame()->GetEventHandler().ElementRemoved(this);
}
void Element::AttachLayoutTree(AttachContext& context) {
DCHECK(GetDocument().InStyleRecalc());
if (HasRareData() && NeedsAttach() && !IsPseudoElement()) {
// We have already been through detach when doing an attach, but we may have
// done a getComputedStyle() in between storing the ComputedStyle on rare
// data if the detach was a LazyReattachIfAttached().
//
// We do not clear it for pseudo elements because we store the original
// style in rare data for display:contents when the ComputedStyle used for
// the LayoutObject is an inline only inheriting properties from the element
// parent.
ElementRareData* data = GetElementRareData();
data->ClearComputedStyle();
}
if (CanParticipateInFlatTree()) {
LayoutTreeBuilderForElement builder(*this, GetNonAttachedStyle());
builder.CreateLayoutObjectIfNeeded();
if (ComputedStyle* style = builder.ResolvedStyle()) {
if (!GetLayoutObject() && ShouldStoreNonLayoutObjectComputedStyle(*style))
StoreNonLayoutObjectComputedStyle(style);
}
}
if (HasRareData() && !GetLayoutObject() &&
!GetElementRareData()->GetComputedStyle()) {
ElementRareData* rare_data = GetElementRareData();
if (ElementAnimations* element_animations =
rare_data->GetElementAnimations()) {
element_animations->CssAnimations().Cancel();
element_animations->SetAnimationStyleChange(false);
}
rare_data->ClearPseudoElements();
}
AttachContext children_context(context);
LayoutObject* layout_object = GetLayoutObject();
if (layout_object)
children_context.previous_in_flow = nullptr;
children_context.use_previous_in_flow = true;
ClearNeedsReattachLayoutTree();
AttachPseudoElement(kPseudoIdBefore, children_context);
// When a shadow root exists, it does the work of attaching the children.
if (ShadowRoot* shadow_root = GetShadowRoot()) {
if (shadow_root->NeedsAttach())
shadow_root->AttachLayoutTree(children_context);
}
ContainerNode::AttachLayoutTree(children_context);
SetNonAttachedStyle(nullptr);
AddCallbackSelectors();
AttachPseudoElement(kPseudoIdAfter, children_context);
AttachPseudoElement(kPseudoIdBackdrop, children_context);
UpdateFirstLetterPseudoElement(StyleUpdatePhase::kAttachLayoutTree);
AttachPseudoElement(kPseudoIdFirstLetter, children_context);
if (layout_object) {
if (!layout_object->IsFloatingOrOutOfFlowPositioned())
context.previous_in_flow = layout_object;
} else {
context.previous_in_flow = children_context.previous_in_flow;
}
}
void Element::DetachLayoutTree(const AttachContext& context) {
HTMLFrameOwnerElement::PluginDisposeSuspendScope suspend_plugin_dispose;
CancelFocusAppearanceUpdate();
RemoveCallbackSelectors();
if (HasRareData()) {
ElementRareData* data = GetElementRareData();
if (!context.performing_reattach)
data->ClearPseudoElements();
// attachLayoutTree() will clear the computed style for us when inside
// recalcStyle.
if (!GetDocument().InStyleRecalc())
data->ClearComputedStyle();
if (ElementAnimations* element_animations = data->GetElementAnimations()) {
if (context.performing_reattach) {
// FIXME: We call detach from within style recalc, so compositingState
// is not up to date.
// https://code.google.com/p/chromium/issues/detail?id=339847
DisableCompositingQueryAsserts disabler;
// FIXME: restart compositor animations rather than pull back to the
// main thread
element_animations->RestartAnimationOnCompositor();
} else {
element_animations->CssAnimations().Cancel();
element_animations->SetAnimationStyleChange(false);
}
element_animations->ClearBaseComputedStyle();
}
DetachPseudoElement(kPseudoIdBefore, context);
if (ShadowRoot* shadow_root = data->GetShadowRoot())
shadow_root->DetachLayoutTree(context);
}
ContainerNode::DetachLayoutTree(context);
DetachPseudoElement(kPseudoIdAfter, context);
DetachPseudoElement(kPseudoIdBackdrop, context);
DetachPseudoElement(kPseudoIdFirstLetter, context);
if (!context.performing_reattach && IsUserActionElement()) {
if (IsHovered())
GetDocument().HoveredElementDetached(*this);
if (InActiveChain())
GetDocument().ActiveChainNodeDetached(*this);
GetDocument().UserActionElements().DidDetach(*this);
}
if (context.clear_invalidation) {
GetDocument()
.GetStyleEngine()
.GetPendingNodeInvalidations()
.ClearInvalidation(*this);
}
SetNeedsResizeObserverUpdate();
DCHECK(NeedsAttach());
}
scoped_refptr<ComputedStyle> Element::StyleForLayoutObject() {
DCHECK(GetDocument().InStyleRecalc());
// FIXME: Instead of clearing updates that may have been added from calls to
// StyleForElement outside RecalcStyle, we should just never set them if we're
// not inside RecalcStyle.
if (ElementAnimations* element_animations = GetElementAnimations())
element_animations->CssAnimations().ClearPendingUpdate();
scoped_refptr<ComputedStyle> style = HasCustomStyleCallbacks()
? CustomStyleForLayoutObject()
: OriginalStyleForLayoutObject();
if (!style) {
DCHECK(IsPseudoElement());
return nullptr;
}
// StyleForElement() might add active animations so we need to get it again.
if (ElementAnimations* element_animations = GetElementAnimations()) {
element_animations->CssAnimations().MaybeApplyPendingUpdate(this);
element_animations->UpdateAnimationFlags(*style);
}
if (style->HasTransform()) {
if (const CSSPropertyValueSet* inline_style = InlineStyle()) {
style->SetHasInlineTransform(
inline_style->HasProperty(CSSPropertyTransform) ||
inline_style->HasProperty(CSSPropertyTranslate) ||
inline_style->HasProperty(CSSPropertyRotate) ||
inline_style->HasProperty(CSSPropertyScale));
}
}
style->UpdateIsStackingContext(this == GetDocument().documentElement(),
IsInTopLayer(),
IsSVGForeignObjectElement(*this));
return style;
}
scoped_refptr<ComputedStyle> Element::OriginalStyleForLayoutObject() {
DCHECK(GetDocument().InStyleRecalc());
return GetDocument().EnsureStyleResolver().StyleForElement(this);
}
bool Element::ShouldCallRecalcStyleForChildren(StyleRecalcChange change) {
if (change != kReattach)
return change >= kUpdatePseudoElements || ChildNeedsStyleRecalc();
if (!ChildrenCanHaveStyle())
return false;
if (const ComputedStyle* new_style = GetNonAttachedStyle()) {
return LayoutObjectIsNeeded(*new_style) ||
ShouldStoreNonLayoutObjectComputedStyle(*new_style);
}
return !CanParticipateInFlatTree();
}
void Element::RecalcStyle(StyleRecalcChange change) {
DCHECK(GetDocument().InStyleRecalc());
DCHECK(!GetDocument().Lifecycle().InDetach());
// If we are re-attaching in a Shadow DOM v0 tree, we recalc down to the
// distributed nodes to propagate kReattach down the flat tree (See
// V0InsertionPoint::DidRecalcStyle). That means we may have a shadow-
// including parent (V0InsertionPoint) with dirty recalc bit in the case where
// fallback content has been redistributed to a different insertion point.
// This will not happen for Shadow DOM v1 because we walk assigned nodes and
// slots themselves are assigned and part of the flat tree.
DCHECK(
!ParentOrShadowHostNode()->NeedsStyleRecalc() ||
(ParentOrShadowHostNode()->IsV0InsertionPoint() && change == kReattach));
DCHECK(InActiveDocument());
if (HasCustomStyleCallbacks())
WillRecalcStyle(change);
if (change >= kIndependentInherit || NeedsStyleRecalc()) {
if (HasRareData()) {
ElementRareData* data = GetElementRareData();
if (change != kIndependentInherit) {
// We keep the old computed style around for display: contents, option
// and optgroup. This way we can call stylePropagationDiff accurately.
//
// We could clear it always, but we'd have more expensive restyles for
// children.
//
// Note that we can't just keep stored other kind of non-layout object
// computed style (like the one that gets set when getComputedStyle is
// called on a display: none element), because that is a sizable memory
// hit.
//
// Also, we don't want to leave a stale computed style, which may happen
// if we don't end up calling recalcOwnStyle because there's no parent
// style.
const ComputedStyle* non_layout_style = NonLayoutObjectComputedStyle();
if (!non_layout_style ||
!ShouldStoreNonLayoutObjectComputedStyle(*non_layout_style) ||
!ParentComputedStyle()) {
data->ClearComputedStyle();
}
}
if (change >= kIndependentInherit) {
if (ElementAnimations* element_animations =
data->GetElementAnimations())
element_animations->SetAnimationStyleChange(false);
}
}
if (ParentComputedStyle()) {
change = RecalcOwnStyle(change);
} else if (!CanParticipateInFlatTree()) {
// Recalculate style for Shadow DOM v0 <content> insertion point.
// It does not take style since it's not part of the flat tree, but we
// need to traverse into fallback children for reattach.
if (NeedsAttach())
change = kReattach;
if (change == kReattach)
SetNeedsReattachLayoutTree();
else if (GetStyleChangeType() == kSubtreeStyleChange)
change = kForce;
}
// Needed because the RebuildLayoutTree code needs to see what the
// StyleChangeType() was on reattach roots. See Node::ReattachLayoutTree()
// for an example.
if (change != kReattach)
ClearNeedsStyleRecalc();
}
if (change >= kUpdatePseudoElements || ChildNeedsStyleRecalc()) {
// ChildrenCanHaveStyle(), hence ShouldCallRecalcStyleForChildren(),
// returns false for <object> elements below. Yet, they may have ::backdrop
// elements.
UpdatePseudoElement(kPseudoIdBackdrop, change);
}
if (ShouldCallRecalcStyleForChildren(change)) {
UpdatePseudoElement(kPseudoIdBefore, change);
if (change > kUpdatePseudoElements || ChildNeedsStyleRecalc()) {
SelectorFilterParentScope filter_scope(*this);
if (ShadowRoot* root = GetShadowRoot()) {
if (root->ShouldCallRecalcStyle(change))
root->RecalcStyle(change);
}
RecalcDescendantStyles(change);
}
UpdatePseudoElement(kPseudoIdAfter, change);
// If we are re-attaching us or any of our descendants, we need to attach
// the descendants before we know if this element generates a ::first-letter
// and which element the ::first-letter inherits style from.
if (change < kReattach && !ChildNeedsReattachLayoutTree())
UpdateFirstLetterPseudoElement(StyleUpdatePhase::kRecalc);
ClearChildNeedsStyleRecalc();
}
if (HasCustomStyleCallbacks())
DidRecalcStyle(change);
}
scoped_refptr<ComputedStyle> Element::PropagateInheritedProperties(
StyleRecalcChange change) {
if (change != kIndependentInherit)
return nullptr;
if (IsPseudoElement())
return nullptr;
if (NeedsStyleRecalc())
return nullptr;
if (HasAnimations())
return nullptr;
const ComputedStyle* parent_style = ParentComputedStyle();
DCHECK(parent_style);
const ComputedStyle* style = GetComputedStyle();
if (!style || style->Animations() || style->Transitions())
return nullptr;
scoped_refptr<ComputedStyle> new_style = ComputedStyle::Clone(*style);
new_style->PropagateIndependentInheritedProperties(*parent_style);
INCREMENT_STYLE_STATS_COUNTER(GetDocument().GetStyleEngine(),
independent_inherited_styles_propagated, 1);
return new_style;
}
StyleRecalcChange Element::RecalcOwnStyle(StyleRecalcChange change) {
DCHECK(GetDocument().InStyleRecalc());
DCHECK(change >= kIndependentInherit || NeedsStyleRecalc());
DCHECK(ParentComputedStyle());
DCHECK(!GetNonAttachedStyle());
scoped_refptr<const ComputedStyle> old_style = GetComputedStyle();
// When propagating inherited changes, we don't need to do a full style recalc
// if the only changed properties are independent. In this case, we can simply
// set these directly on the ComputedStyle object.
scoped_refptr<ComputedStyle> new_style = PropagateInheritedProperties(change);
if (!new_style)
new_style = StyleForLayoutObject();
if (!new_style) {
DCHECK(IsPseudoElement());
SetNeedsReattachLayoutTree();
return kReattach;
}
StyleRecalcChange local_change =
ComputedStyle::StylePropagationDiff(old_style.get(), new_style.get());
if (local_change == kNoChange) {
INCREMENT_STYLE_STATS_COUNTER(GetDocument().GetStyleEngine(),
styles_unchanged, 1);
} else {
INCREMENT_STYLE_STATS_COUNTER(GetDocument().GetStyleEngine(),
styles_changed, 1);
if (this == GetDocument().documentElement()) {
if (GetDocument().GetStyleEngine().UpdateRemUnits(old_style.get(),
new_style.get())) {
// Trigger a full document recalc on rem unit changes. We could keep
// track of which elements depend on rem units like we do for viewport
// styles, but we assume root font size changes are rare and just
// recalculate everything.
if (local_change < kForce)
local_change = kForce;
}
}
}
if (change == kReattach || local_change == kReattach) {
SetNonAttachedStyle(new_style);
SetNeedsReattachLayoutTree();
return kReattach;
}
DCHECK(old_style);
if (local_change != kNoChange)
UpdateCallbackSelectors(old_style.get(), new_style.get());
if (LayoutObject* layout_object = GetLayoutObject()) {
// kNoChange may mean that the computed style didn't change, but there are
// additional flags in ComputedStyle which may have changed. For instance,
// the AffectedBy* flags. We don't need to go through the visual
// invalidation diffing in that case, but we replace the old ComputedStyle
// object with the new one to ensure the mentioned flags are up to date.
if (local_change == kNoChange)
layout_object->SetStyleInternal(new_style.get());
else
layout_object->SetStyle(new_style.get());
} else {
if (ShouldStoreNonLayoutObjectComputedStyle(*new_style))
StoreNonLayoutObjectComputedStyle(new_style);
else if (HasRareData())
GetElementRareData()->ClearComputedStyle();
}
if (GetStyleChangeType() >= kSubtreeStyleChange)
return kForce;
if (change > kInherit || local_change > kInherit)
return max(local_change, change);
if (local_change < kIndependentInherit) {
if (old_style->HasChildDependentFlags()) {
if (ChildNeedsStyleRecalc())
return kInherit;
new_style->CopyChildDependentFlagsFrom(*old_style);
}
if (old_style->HasPseudoElementStyle() ||
new_style->HasPseudoElementStyle())
return kUpdatePseudoElements;
}
return local_change;
}
void Element::RebuildLayoutTree(WhitespaceAttacher& whitespace_attacher) {
DCHECK(InActiveDocument());
DCHECK(parentNode());
if (NeedsReattachLayoutTree()) {
AttachContext reattach_context;
ReattachLayoutTree(reattach_context);
whitespace_attacher.DidReattachElement(this,
reattach_context.previous_in_flow);
} else {
// We create a local WhitespaceAttacher when rebuilding children of an
// element with a LayoutObject since whitespace nodes do not rely on layout
// objects further up the tree. Also, if this Element's layout object is an
// out-of-flow box, in-flow children should not affect whitespace siblings
// of the out-of-flow box. However, if this element is a display:contents
// element. Continue using the passed in attacher as display:contents
// children may affect whitespace nodes further up the tree as they may be
// layout tree siblings.
WhitespaceAttacher local_attacher;
WhitespaceAttacher* child_attacher;
if (GetLayoutObject() || !HasDisplayContentsStyle()) {
whitespace_attacher.DidVisitElement(this);
if (GetDocument().GetStyleEngine().NeedsWhitespaceReattachment(this))
local_attacher.SetReattachAllWhitespaceNodes();
child_attacher = &local_attacher;
} else {
child_attacher = &whitespace_attacher;
}
RebuildPseudoElementLayoutTree(kPseudoIdAfter, *child_attacher);
if (GetShadowRoot())
RebuildShadowRootLayoutTree(*child_attacher);
else
RebuildChildrenLayoutTrees(*child_attacher);
RebuildPseudoElementLayoutTree(kPseudoIdBefore, *child_attacher);
RebuildPseudoElementLayoutTree(kPseudoIdBackdrop, *child_attacher);
RebuildFirstLetterLayoutTree();
ClearChildNeedsReattachLayoutTree();
}
DCHECK(!NeedsStyleRecalc());
DCHECK(!ChildNeedsStyleRecalc());
DCHECK(!NeedsReattachLayoutTree());
DCHECK(!GetNonAttachedStyle());
DCHECK(!ChildNeedsReattachLayoutTree());
}
void Element::RebuildShadowRootLayoutTree(
WhitespaceAttacher& whitespace_attacher) {
DCHECK(IsShadowHost(this));
ShadowRoot* root = GetShadowRoot();
root->RebuildLayoutTree(whitespace_attacher);
RebuildNonDistributedChildren();
}
void Element::RebuildPseudoElementLayoutTree(
PseudoId pseudo_id,
WhitespaceAttacher& whitespace_attacher) {
if (PseudoElement* element = GetPseudoElement(pseudo_id)) {
if (element->NeedsRebuildLayoutTree(whitespace_attacher))
element->RebuildLayoutTree(whitespace_attacher);
}
}
void Element::RebuildFirstLetterLayoutTree() {
// Need to create a ::first-letter element here for the following case:
//
// <style>#outer::first-letter {...}</style>
// <div id=outer><div id=inner style="display:none">Text</div></div>
// <script> outer.offsetTop; inner.style.display = "block" </script>
//
// The creation of FirstLetterPseudoElement relies on the layout tree of the
// block contents. In this case, the ::first-letter element is not created
// initially since the #inner div is not displayed. On RecalcStyle it's not
// created since the layout tree is still not built, and AttachLayoutTree
// for #inner will not update the ::first-letter of outer. However, we end
// up here for #outer after AttachLayoutTree is called on #inner at which
// point the layout sub-tree is available for deciding on creating the
// ::first-letter.
UpdateFirstLetterPseudoElement(StyleUpdatePhase::kRebuildLayoutTree);
if (PseudoElement* element = GetPseudoElement(kPseudoIdFirstLetter)) {
WhitespaceAttacher whitespace_attacher;
if (element->NeedsRebuildLayoutTree(whitespace_attacher))
element->RebuildLayoutTree(whitespace_attacher);
}
}
void Element::UpdateCallbackSelectors(const ComputedStyle* old_style,
const ComputedStyle* new_style) {
Vector<String> empty_vector;
const Vector<String>& old_callback_selectors =
old_style ? old_style->CallbackSelectors() : empty_vector;
const Vector<String>& new_callback_selectors =
new_style ? new_style->CallbackSelectors() : empty_vector;
if (old_callback_selectors.IsEmpty() && new_callback_selectors.IsEmpty())
return;
if (old_callback_selectors != new_callback_selectors)
CSSSelectorWatch::From(GetDocument())
.UpdateSelectorMatches(old_callback_selectors, new_callback_selectors);
}
void Element::AddCallbackSelectors() {
UpdateCallbackSelectors(nullptr, GetComputedStyle());
}
void Element::RemoveCallbackSelectors() {
UpdateCallbackSelectors(GetComputedStyle(), nullptr);
}
ShadowRoot& Element::CreateAndAttachShadowRoot(ShadowRootType type) {
#if DCHECK_IS_ON()
NestingLevelIncrementer slot_assignment_recalc_forbidden_scope(
GetDocument().SlotAssignmentRecalcForbiddenRecursionDepth());
#endif
EventDispatchForbiddenScope assert_no_event_dispatch;
ScriptForbiddenScope forbid_script;
DCHECK(!GetShadowRoot());
ShadowRoot* shadow_root = ShadowRoot::Create(GetDocument(), type);
if (type != ShadowRootType::V0) {
// Detach the host's children here for v1 (including UA shadow root),
// because we skip SetNeedsDistributionRecalc() in attaching v1 shadow root.
// See https://crrev.com/2822113002 for details.
// We need to call child.LazyReattachIfAttached() before setting a shadow
// root to the element because detach must use the original flat tree
// structure before attachShadow happens.
for (Node& child : NodeTraversal::ChildrenOf(*this))
child.LazyReattachIfAttached();
}
EnsureElementRareData().SetShadowRoot(*shadow_root);
shadow_root->SetParentOrShadowHostNode(this);
shadow_root->SetParentTreeScope(GetTreeScope());
if (type == ShadowRootType::V0) {
shadow_root->SetNeedsDistributionRecalc();
}
shadow_root->InsertedInto(*this);
SetChildNeedsStyleRecalc();
SetNeedsStyleRecalc(kSubtreeStyleChange, StyleChangeReasonForTracing::Create(
StyleChangeReason::kShadow));
probe::didPushShadowRoot(this, shadow_root);
return *shadow_root;
}
// TODO(kochi): inline this.
ShadowRoot* Element::GetShadowRoot() const {
return HasRareData() ? GetElementRareData()->GetShadowRoot() : nullptr;
}
void Element::PseudoStateChanged(CSSSelector::PseudoType pseudo) {
// We can't schedule invaliation sets from inside style recalc otherwise
// we'd never process them.
// TODO(esprehn): Make this an ASSERT and fix places that call into this
// like HTMLSelectElement.
if (GetDocument().InStyleRecalc())
return;
GetDocument().GetStyleEngine().PseudoStateChangedForElement(pseudo, *this);
}
void Element::SetAnimationStyleChange(bool animation_style_change) {
if (animation_style_change && GetDocument().InStyleRecalc())
return;
if (!HasRareData())
return;
if (ElementAnimations* element_animations =
GetElementRareData()->GetElementAnimations())
element_animations->SetAnimationStyleChange(animation_style_change);
}
void Element::ClearAnimationStyleChange() {
if (!HasRareData())
return;
if (ElementAnimations* element_animations =
GetElementRareData()->GetElementAnimations())
element_animations->SetAnimationStyleChange(false);
}
void Element::SetNeedsAnimationStyleRecalc() {
if (GetStyleChangeType() != kNoStyleChange)
return;
SetNeedsStyleRecalc(kLocalStyleChange, StyleChangeReasonForTracing::Create(
StyleChangeReason::kAnimation));
SetAnimationStyleChange(true);
}
void Element::SetNeedsCompositingUpdate() {
if (!GetDocument().IsActive())
return;
LayoutBoxModelObject* layout_object = GetLayoutBoxModelObject();
if (!layout_object)
return;
if (!layout_object->HasLayer())
return;
layout_object->Layer()->SetNeedsCompositingInputsUpdate();
// Changes in the return value of requiresAcceleratedCompositing change if
// the PaintLayer is self-painting.
layout_object->Layer()->UpdateSelfPaintingLayer();
}
void Element::V0SetCustomElementDefinition(
V0CustomElementDefinition* definition) {
if (!HasRareData() && !definition)
return;
DCHECK(!GetV0CustomElementDefinition());
EnsureElementRareData().V0SetCustomElementDefinition(definition);
}
V0CustomElementDefinition* Element::GetV0CustomElementDefinition() const {
if (HasRareData())
return GetElementRareData()->GetV0CustomElementDefinition();
return nullptr;
}
void Element::SetCustomElementDefinition(CustomElementDefinition* definition) {
DCHECK(definition);
DCHECK(!GetCustomElementDefinition());
EnsureElementRareData().SetCustomElementDefinition(definition);
SetCustomElementState(CustomElementState::kCustom);
}
CustomElementDefinition* Element::GetCustomElementDefinition() const {
if (HasRareData())
return GetElementRareData()->GetCustomElementDefinition();
return nullptr;
}
void Element::SetIsValue(const AtomicString& is_value) {
DCHECK(IsValue().IsNull()) << "SetIsValue() should be called at most once.";
EnsureElementRareData().SetIsValue(is_value);
}
const AtomicString& Element::IsValue() const {
if (HasRareData())
return GetElementRareData()->IsValue();
return g_null_atom;
}
ShadowRoot* Element::createShadowRoot(ExceptionState& exception_state) {
if (ShadowRoot* root = GetShadowRoot()) {
if (root->IsUserAgent()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidStateError,
"Shadow root cannot be created on a host which already hosts a "
"user-agent shadow tree.");
} else {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidStateError,
"Shadow root cannot be created on a host which already hosts a "
"shadow tree.");
}
return nullptr;
}
if (AlwaysCreateUserAgentShadowRoot()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidStateError,
"Shadow root cannot be created on a host which already hosts a "
"user-agent shadow tree.");
return nullptr;
}
// Some elements make assumptions about what kind of layoutObjects they allow
// as children so we can't allow author shadows on them for now.
if (!AreAuthorShadowsAllowed()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kHierarchyRequestError,
"Author-created shadow roots are disabled for this element.");
return nullptr;
}
return &CreateShadowRootInternal();
}
bool Element::CanAttachShadowRoot() const {
const AtomicString& tag_name = localName();
// Checking Is{V0}CustomElement() here is just an optimization
// because IsValidName is not cheap.
return (IsCustomElement() && CustomElement::IsValidName(tag_name)) ||
(IsV0CustomElement() && V0CustomElement::IsValidName(tag_name)) ||
tag_name == HTMLNames::articleTag || tag_name == HTMLNames::asideTag ||
tag_name == HTMLNames::blockquoteTag ||
tag_name == HTMLNames::bodyTag || tag_name == HTMLNames::divTag ||
tag_name == HTMLNames::footerTag || tag_name == HTMLNames::h1Tag ||
tag_name == HTMLNames::h2Tag || tag_name == HTMLNames::h3Tag ||
tag_name == HTMLNames::h4Tag || tag_name == HTMLNames::h5Tag ||
tag_name == HTMLNames::h6Tag || tag_name == HTMLNames::headerTag ||
tag_name == HTMLNames::navTag || tag_name == HTMLNames::mainTag ||
tag_name == HTMLNames::pTag || tag_name == HTMLNames::sectionTag ||
tag_name == HTMLNames::spanTag;
}
ShadowRoot* Element::attachShadow(const ShadowRootInit& shadow_root_init_dict,
ExceptionState& exception_state) {
DCHECK(shadow_root_init_dict.hasMode());
if (!CanAttachShadowRoot()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kNotSupportedError,
"This element does not support attachShadow");
return nullptr;
}
if (GetShadowRoot()) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
"Shadow root cannot be created on a host "
"which already hosts a shadow tree.");
return nullptr;
}
ShadowRootType type = shadow_root_init_dict.mode() == "open"
? ShadowRootType::kOpen
: ShadowRootType::kClosed;
if (type == ShadowRootType::kOpen)
UseCounter::Count(GetDocument(), WebFeature::kElementAttachShadowOpen);
else
UseCounter::Count(GetDocument(), WebFeature::kElementAttachShadowClosed);
DCHECK(!shadow_root_init_dict.hasMode() || !GetShadowRoot());
bool delegates_focus = shadow_root_init_dict.hasDelegatesFocus() &&
shadow_root_init_dict.delegatesFocus();
bool manual_slotting = shadow_root_init_dict.slotting() == "manual";
return &AttachShadowRootInternal(type, delegates_focus, manual_slotting);
}
ShadowRoot& Element::CreateShadowRootInternal() {
DCHECK(!ClosedShadowRoot());
DCHECK(AreAuthorShadowsAllowed());
DCHECK(!AlwaysCreateUserAgentShadowRoot());
GetDocument().SetShadowCascadeOrder(ShadowCascadeOrder::kShadowCascadeV0);
return CreateAndAttachShadowRoot(ShadowRootType::V0);
}
ShadowRoot& Element::CreateUserAgentShadowRoot() {
DCHECK(!GetShadowRoot());
return CreateAndAttachShadowRoot(ShadowRootType::kUserAgent);
}
ShadowRoot& Element::AttachShadowRootInternal(ShadowRootType type,
bool delegates_focus,
bool manual_slotting) {
// SVG <use> is a special case for using this API to create a closed shadow
// root.
DCHECK(CanAttachShadowRoot() || IsSVGUseElement(*this));
DCHECK(type == ShadowRootType::kOpen || type == ShadowRootType::kClosed)
<< type;
DCHECK(!AlwaysCreateUserAgentShadowRoot());
GetDocument().SetShadowCascadeOrder(ShadowCascadeOrder::kShadowCascadeV1);
ShadowRoot& shadow_root = CreateAndAttachShadowRoot(type);
shadow_root.SetDelegatesFocus(delegates_focus);
shadow_root.SetSlotting(manual_slotting ? ShadowRootSlotting::kManual
: ShadowRootSlotting::kAuto);
return shadow_root;
}
ShadowRoot* Element::OpenShadowRoot() const {
ShadowRoot* root = GetShadowRoot();
if (!root)
return nullptr;
return root->GetType() == ShadowRootType::V0 ||
root->GetType() == ShadowRootType::kOpen
? root
: nullptr;
}
ShadowRoot* Element::ClosedShadowRoot() const {
ShadowRoot* root = GetShadowRoot();
if (!root)
return nullptr;
return root->GetType() == ShadowRootType::kClosed ? root : nullptr;
}
ShadowRoot* Element::AuthorShadowRoot() const {
ShadowRoot* root = GetShadowRoot();
if (!root)
return nullptr;
return !root->IsUserAgent() ? root : nullptr;
}
ShadowRoot* Element::UserAgentShadowRoot() const {
ShadowRoot* root = GetShadowRoot();
DCHECK(!root || root->IsUserAgent());
return root;
}
ShadowRoot& Element::EnsureUserAgentShadowRoot() {
if (ShadowRoot* shadow_root = UserAgentShadowRoot()) {
DCHECK(shadow_root->GetType() == ShadowRootType::kUserAgent);
return *shadow_root;
}
ShadowRoot& shadow_root =
CreateAndAttachShadowRoot(ShadowRootType::kUserAgent);
DidAddUserAgentShadowRoot(shadow_root);
return shadow_root;
}
bool Element::ChildTypeAllowed(NodeType type) const {
switch (type) {
case kElementNode:
case kTextNode:
case kCommentNode:
case kProcessingInstructionNode:
case kCdataSectionNode:
return true;
default:
break;
}
return false;
}
namespace {
bool HasSiblingsForNonEmpty(const Node* sibling,
Node* (*next_func)(const Node&)) {
for (; sibling; sibling = next_func(*sibling)) {
if (sibling->IsElementNode())
return true;
if (sibling->IsTextNode() && !ToText(sibling)->data().IsEmpty())
return true;
}
return false;
}
} // namespace
void Element::CheckForEmptyStyleChange(const Node* node_before_change,
const Node* node_after_change) {
if (!InActiveDocument())
return;
if (!StyleAffectedByEmpty())
return;
if (HasSiblingsForNonEmpty(node_before_change,
NodeTraversal::PreviousSibling) ||
HasSiblingsForNonEmpty(node_after_change, NodeTraversal::NextSibling)) {
return;
}
PseudoStateChanged(CSSSelector::kPseudoEmpty);
}
void Element::ChildrenChanged(const ChildrenChange& change) {
ContainerNode::ChildrenChanged(change);
CheckForEmptyStyleChange(change.sibling_before_change,
change.sibling_after_change);
if (!change.by_parser && change.IsChildElementChange())
CheckForSiblingStyleChanges(
change.type == kElementRemoved ? kSiblingElementRemoved
: kSiblingElementInserted,
ToElement(change.sibling_changed), change.sibling_before_change,
change.sibling_after_change);
if (ShadowRoot* shadow_root = GetShadowRoot())
shadow_root->SetNeedsDistributionRecalcWillBeSetNeedsAssignmentRecalc();
}
void Element::FinishParsingChildren() {
SetIsFinishedParsingChildren(true);
CheckForEmptyStyleChange(this, this);
CheckForSiblingStyleChanges(kFinishedParsingChildren, nullptr, lastChild(),
nullptr);
}
AttrNodeList* Element::GetAttrNodeList() {
return HasRareData() ? GetElementRareData()->GetAttrNodeList() : nullptr;
}
void Element::RemoveAttrNodeList() {
DCHECK(GetAttrNodeList());
if (HasRareData())
GetElementRareData()->RemoveAttrNodeList();
}
Attr* Element::setAttributeNode(Attr* attr_node,
ExceptionState& exception_state) {
Attr* old_attr_node = AttrIfExists(attr_node->GetQualifiedName());
if (old_attr_node == attr_node)
return attr_node; // This Attr is already attached to the element.
// InUseAttributeError: Raised if node is an Attr that is already an attribute
// of another Element object. The DOM user must explicitly clone Attr nodes
// to re-use them in other elements.
if (attr_node->ownerElement()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInUseAttributeError,
"The node provided is an attribute node that is already an attribute "
"of another Element; attribute nodes must be explicitly cloned.");
return nullptr;
}
if (!IsHTMLElement() && attr_node->GetDocument().IsHTMLDocument() &&
attr_node->name() != attr_node->name().LowerASCII())
UseCounter::Count(
GetDocument(),
WebFeature::
kNonHTMLElementSetAttributeNodeFromHTMLDocumentNameNotLowercase);
SynchronizeAllAttributes();
const UniqueElementData& element_data = EnsureUniqueElementData();
AttributeCollection attributes = element_data.Attributes();
size_t index = attributes.FindIndex(attr_node->GetQualifiedName());
AtomicString local_name;
if (index != kNotFound) {
const Attribute& attr = attributes[index];
// If the name of the ElementData attribute doesn't
// (case-sensitively) match that of the Attr node, record it
// on the Attr so that it can correctly resolve the value on
// the Element.
if (!attr.GetName().Matches(attr_node->GetQualifiedName()))
local_name = attr.LocalName();
if (old_attr_node) {
DetachAttrNodeFromElementWithValue(old_attr_node, attr.Value());
} else {
// FIXME: using attrNode's name rather than the
// Attribute's for the replaced Attr is compatible with
// all but Gecko (and, arguably, the DOM Level1 spec text.)
// Consider switching.
old_attr_node = Attr::Create(GetDocument(), attr_node->GetQualifiedName(),
attr.Value());
}
}
SetAttributeInternal(index, attr_node->GetQualifiedName(), attr_node->value(),
kNotInSynchronizationOfLazyAttribute);
attr_node->AttachToElement(this, local_name);
GetTreeScope().AdoptIfNeeded(*attr_node);
EnsureElementRareData().AddAttr(attr_node);
return old_attr_node;
}
Attr* Element::setAttributeNodeNS(Attr* attr, ExceptionState& exception_state) {
return setAttributeNode(attr, exception_state);
}
Attr* Element::removeAttributeNode(Attr* attr,
ExceptionState& exception_state) {
if (attr->ownerElement() != this) {
exception_state.ThrowDOMException(
DOMExceptionCode::kNotFoundError,
"The node provided is owned by another element.");
return nullptr;
}
DCHECK_EQ(GetDocument(), attr->GetDocument());
SynchronizeAttribute(attr->GetQualifiedName());
size_t index =
GetElementData()->Attributes().FindIndex(attr->GetQualifiedName());
if (index == kNotFound) {
exception_state.ThrowDOMException(
DOMExceptionCode::kNotFoundError,
"The attribute was not found on this element.");
return nullptr;
}
DetachAttrNodeAtIndex(attr, index);
return attr;
}
void Element::ParseAttribute(const AttributeModificationParams& params) {
if (params.name == tabindexAttr) {
int tabindex = 0;
if (params.new_value.IsEmpty() ||
!ParseHTMLInteger(params.new_value, tabindex)) {
ClearTabIndexExplicitlyIfNeeded();
} else {
// We only set when value is in integer range.
SetTabIndexExplicitly();
}
} else if (params.name == XMLNames::langAttr) {
PseudoStateChanged(CSSSelector::kPseudoLang);
}
}
bool Element::ParseAttributeName(QualifiedName& out,
const AtomicString& namespace_uri,
const AtomicString& qualified_name,
ExceptionState& exception_state) {
AtomicString prefix, local_name;
if (!Document::ParseQualifiedName(qualified_name, prefix, local_name,
exception_state))
return false;
DCHECK(!exception_state.HadException());
QualifiedName q_name(prefix, local_name, namespace_uri);
if (!Document::HasValidNamespaceForAttributes(q_name)) {
exception_state.ThrowDOMException(
DOMExceptionCode::kNamespaceError,
"'" + namespace_uri + "' is an invalid namespace for attributes.");
return false;
}
out = q_name;
return true;
}
void Element::setAttributeNS(const AtomicString& namespace_uri,
const AtomicString& qualified_name,
const AtomicString& value,
ExceptionState& exception_state) {
QualifiedName parsed_name = g_any_name;
if (!ParseAttributeName(parsed_name, namespace_uri, qualified_name,
exception_state))
return;
setAttribute(parsed_name, value);
}
void Element::RemoveAttributeInternal(
size_t index,
SynchronizationOfLazyAttribute in_synchronization_of_lazy_attribute) {
MutableAttributeCollection attributes =
EnsureUniqueElementData().Attributes();
SECURITY_DCHECK(index < attributes.size());
QualifiedName name = attributes[index].GetName();
AtomicString value_being_removed = attributes[index].Value();
if (!in_synchronization_of_lazy_attribute) {
if (!value_being_removed.IsNull()) {
WillModifyAttribute(name, value_being_removed, g_null_atom);
} else if (GetCustomElementState() == CustomElementState::kCustom) {
// This would otherwise be enqueued by willModifyAttribute.
CustomElement::EnqueueAttributeChangedCallback(
this, name, value_being_removed, g_null_atom);
}
}
if (Attr* attr_node = AttrIfExists(name))
DetachAttrNodeFromElementWithValue(attr_node, attributes[index].Value());
attributes.Remove(index);
if (!in_synchronization_of_lazy_attribute)
DidRemoveAttribute(name, value_being_removed);
}
void Element::AppendAttributeInternal(
const QualifiedName& name,
const AtomicString& value,
SynchronizationOfLazyAttribute in_synchronization_of_lazy_attribute) {
if (!in_synchronization_of_lazy_attribute)
WillModifyAttribute(name, g_null_atom, value);
EnsureUniqueElementData().Attributes().Append(name, value);
if (!in_synchronization_of_lazy_attribute)
DidAddAttribute(name, value);
}
void Element::removeAttribute(const AtomicString& name) {
if (!GetElementData())
return;
AtomicString local_name = LowercaseIfNecessary(name);
size_t index = GetElementData()->Attributes().FindIndex(local_name);
if (index == kNotFound) {
if (UNLIKELY(local_name == styleAttr) &&
GetElementData()->style_attribute_is_dirty_ && IsStyledElement())
RemoveAllInlineStyleProperties();
return;
}
RemoveAttributeInternal(index, kNotInSynchronizationOfLazyAttribute);
}
void Element::removeAttributeNS(const AtomicString& namespace_uri,
const AtomicString& local_name) {
removeAttribute(QualifiedName(g_null_atom, local_name, namespace_uri));
}
Attr* Element::getAttributeNode(const AtomicString& local_name) {
if (!GetElementData())
return nullptr;
SynchronizeAttribute(local_name);
const Attribute* attribute =
GetElementData()->Attributes().Find(LowercaseIfNecessary(local_name));
if (!attribute)
return nullptr;
return EnsureAttr(attribute->GetName());
}
Attr* Element::getAttributeNodeNS(const AtomicString& namespace_uri,
const AtomicString& local_name) {
if (!GetElementData())
return nullptr;
QualifiedName q_name(g_null_atom, local_name, namespace_uri);
SynchronizeAttribute(q_name);
const Attribute* attribute = GetElementData()->Attributes().Find(q_name);
if (!attribute)
return nullptr;
return EnsureAttr(attribute->GetName());
}
bool Element::hasAttribute(const AtomicString& local_name) const {
if (!GetElementData())
return false;
SynchronizeAttribute(local_name);
return GetElementData()->Attributes().FindIndex(
LowercaseIfNecessary(local_name)) != kNotFound;
}
bool Element::hasAttributeNS(const AtomicString& namespace_uri,
const AtomicString& local_name) const {
if (!GetElementData())
return false;
QualifiedName q_name(g_null_atom, local_name, namespace_uri);
SynchronizeAttribute(q_name);
return GetElementData()->Attributes().Find(q_name);
}
void Element::focus(FocusOptions options) {
focus(FocusParams(SelectionBehaviorOnFocus::kRestore, kWebFocusTypeNone,
nullptr, options));
}
void Element::focus(const FocusParams& params) {
if (!isConnected())
return;
if (GetDocument().FocusedElement() == this)
return;
if (!GetDocument().IsActive())
return;
if (IsFrameOwnerElement() &&
ToHTMLFrameOwnerElement(this)->contentDocument() &&
ToHTMLFrameOwnerElement(this)->contentDocument()->UnloadStarted())
return;
GetDocument().UpdateStyleAndLayoutTreeIgnorePendingStylesheets();
if (!IsFocusable())
return;
if (AuthorShadowRoot() && AuthorShadowRoot()->delegatesFocus()) {
if (IsShadowIncludingInclusiveAncestorOf(GetDocument().FocusedElement()))
return;
// Slide the focus to its inner node.
Element* found = GetDocument()
.GetPage()
->GetFocusController()
.FindFocusableElementInShadowHost(*this);
if (found && IsShadowIncludingInclusiveAncestorOf(found)) {
found->focus(FocusParams(SelectionBehaviorOnFocus::kReset,
kWebFocusTypeForward, nullptr, params.options));
return;
}
}
if (!GetDocument().GetPage()->GetFocusController().SetFocusedElement(
this, GetDocument().GetFrame(), params))
return;
if (GetDocument().FocusedElement() == this &&
GetDocument().GetFrame()->HasBeenActivated()) {
// Bring up the keyboard in the context of anything triggered by a user
// gesture. Since tracking that across arbitrary boundaries (eg.
// animations) is difficult, for now we match IE's heuristic and bring
// up the keyboard if there's been any gesture since load.
GetDocument()
.GetPage()
->GetChromeClient()
.ShowVirtualKeyboardOnElementFocus(*GetDocument().GetFrame());
}
}
void Element::UpdateFocusAppearance(
SelectionBehaviorOnFocus selection_behavior) {
UpdateFocusAppearanceWithOptions(selection_behavior, FocusOptions());
}
void Element::UpdateFocusAppearanceWithOptions(
SelectionBehaviorOnFocus selection_behavior,
const FocusOptions& options) {
if (selection_behavior == SelectionBehaviorOnFocus::kNone)
return;
if (IsRootEditableElement(*this)) {
LocalFrame* frame = GetDocument().GetFrame();
if (!frame)
return;
// When focusing an editable element in an iframe, don't reset the selection
// if it already contains a selection.
if (this == frame->Selection()
.ComputeVisibleSelectionInDOMTreeDeprecated()
.RootEditableElement())
return;
// FIXME: We should restore the previous selection if there is one.
// Passing DoNotSetFocus as this function is called after
// FocusController::setFocusedElement() and we don't want to change the
// focus to a new Element.
frame->Selection().SetSelection(
SelectionInDOMTree::Builder()
.Collapse(FirstPositionInOrBeforeNode(*this))
.Build(),
SetSelectionOptions::Builder()
.SetShouldCloseTyping(true)
.SetShouldClearTypingStyle(true)
.SetDoNotSetFocus(true)
.Build());
if (!options.preventScroll())
frame->Selection().RevealSelection();
} else if (GetLayoutObject() &&
!GetLayoutObject()->IsLayoutEmbeddedContent()) {
if (!options.preventScroll()) {
GetLayoutObject()->ScrollRectToVisible(BoundingBoxForScrollIntoView(),
WebScrollIntoViewParams());
}
}
}
void Element::blur() {
CancelFocusAppearanceUpdate();
if (AdjustedFocusedElementInTreeScope() == this) {
Document& doc = GetDocument();
if (doc.GetPage()) {
doc.GetPage()->GetFocusController().SetFocusedElement(nullptr,
doc.GetFrame());
} else {
doc.ClearFocusedElement();
}
}
}
bool Element::SupportsFocus() const {
// FIXME: supportsFocus() can be called when layout is not up to date.
// Logic that deals with the layoutObject should be moved to
// layoutObjectIsFocusable().
// But supportsFocus must return true when the element is editable, or else
// it won't be focusable. Furthermore, supportsFocus cannot just return true
// always or else tabIndex() will change for all HTML elements.
return HasElementFlag(ElementFlags::kTabIndexWasSetExplicitly) ||
IsRootEditableElement(*this) ||
(IsShadowHost(this) && AuthorShadowRoot() &&
AuthorShadowRoot()->delegatesFocus()) ||
SupportsSpatialNavigationFocus();
}
bool Element::SupportsSpatialNavigationFocus() const {
// This function checks whether the element satisfies the extended criteria
// for the element to be focusable, introduced by spatial navigation feature,
// i.e. checks if click or keyboard event handler is specified.
// This is the way to make it possible to navigate to (focus) elements
// which web designer meant for being active (made them respond to click
// events).
if (!IsSpatialNavigationEnabled(GetDocument().GetFrame()) ||
SpatialNavigationIgnoresEventHandlers(GetDocument().GetFrame()))
return false;
if (HasEventListeners(EventTypeNames::click) ||
HasEventListeners(EventTypeNames::keydown) ||
HasEventListeners(EventTypeNames::keypress) ||
HasEventListeners(EventTypeNames::keyup))
return true;
if (!IsSVGElement())
return false;
return (HasEventListeners(EventTypeNames::focus) ||
HasEventListeners(EventTypeNames::blur) ||
HasEventListeners(EventTypeNames::focusin) ||
HasEventListeners(EventTypeNames::focusout));
}
bool Element::IsFocusable() const {
// Style cannot be cleared out for non-active documents, so in that case the
// needsLayoutTreeUpdateForNode check is invalid.
DCHECK(!GetDocument().IsActive() ||
!GetDocument().NeedsLayoutTreeUpdateForNode(*this));
return isConnected() && SupportsFocus() && !IsInert() && IsFocusableStyle();
}
bool Element::IsKeyboardFocusable() const {
return IsFocusable() && tabIndex() >= 0;
}
bool Element::IsMouseFocusable() const {
return IsFocusable();
}
bool Element::IsFocusedElementInDocument() const {
return this == GetDocument().FocusedElement();
}
Element* Element::AdjustedFocusedElementInTreeScope() const {
return IsInTreeScope() ? ContainingTreeScope().AdjustedFocusedElement()
: nullptr;
}
void Element::DispatchFocusEvent(Element* old_focused_element,
WebFocusType type,
InputDeviceCapabilities* source_capabilities) {
DispatchEvent(*FocusEvent::Create(EventTypeNames::focus, Event::Bubbles::kNo,
GetDocument().domWindow(), 0,
old_focused_element, source_capabilities));
}
void Element::DispatchBlurEvent(Element* new_focused_element,
WebFocusType type,
InputDeviceCapabilities* source_capabilities) {
DispatchEvent(*FocusEvent::Create(EventTypeNames::blur, Event::Bubbles::kNo,
GetDocument().domWindow(), 0,
new_focused_element, source_capabilities));
}
void Element::DispatchFocusInEvent(
const AtomicString& event_type,
Element* old_focused_element,
WebFocusType,
InputDeviceCapabilities* source_capabilities) {
#if DCHECK_IS_ON()
DCHECK(!EventDispatchForbiddenScope::IsEventDispatchForbidden());
#endif
DCHECK(event_type == EventTypeNames::focusin ||
event_type == EventTypeNames::DOMFocusIn);
DispatchScopedEvent(*FocusEvent::Create(
event_type, Event::Bubbles::kYes, GetDocument().domWindow(), 0,
old_focused_element, source_capabilities));
}
void Element::DispatchFocusOutEvent(
const AtomicString& event_type,
Element* new_focused_element,
InputDeviceCapabilities* source_capabilities) {
#if DCHECK_IS_ON()
DCHECK(!EventDispatchForbiddenScope::IsEventDispatchForbidden());
#endif
DCHECK(event_type == EventTypeNames::focusout ||
event_type == EventTypeNames::DOMFocusOut);
DispatchScopedEvent(*FocusEvent::Create(
event_type, Event::Bubbles::kYes, GetDocument().domWindow(), 0,
new_focused_element, source_capabilities));
}
String Element::InnerHTMLAsString() const {
return CreateMarkup(this, kChildrenOnly);
}
String Element::OuterHTMLAsString() const {
return CreateMarkup(this);
}
void Element::innerHTML(StringOrTrustedHTML& result) const {
result.SetString(InnerHTMLAsString());
}
void Element::outerHTML(StringOrTrustedHTML& result) const {
result.SetString(OuterHTMLAsString());
}
void Element::SetInnerHTMLFromString(const String& html,
ExceptionState& exception_state) {
probe::breakableLocation(&GetDocument(), "Element.setInnerHTML");
if (html.IsEmpty() && !HasNonInBodyInsertionMode()) {
setTextContent(html);
} else {
if (DocumentFragment* fragment = CreateFragmentForInnerOuterHTML(
html, this, kAllowScriptingContent, "innerHTML", exception_state)) {
ContainerNode* container = this;
if (auto* template_element = ToHTMLTemplateElementOrNull(*this))
container = template_element->content();
ReplaceChildrenWithFragment(container, fragment, exception_state);
}
}
}
void Element::SetInnerHTMLFromString(const String& html) {
SetInnerHTMLFromString(html, ASSERT_NO_EXCEPTION);
}
void Element::setInnerHTML(const StringOrTrustedHTML& string_or_html,
ExceptionState& exception_state) {
String html =
TrustedHTML::GetString(string_or_html, &GetDocument(), exception_state);
if (!exception_state.HadException()) {
SetInnerHTMLFromString(html, exception_state);
}
}
void Element::setInnerHTML(const StringOrTrustedHTML& string_or_html) {
setInnerHTML(string_or_html, ASSERT_NO_EXCEPTION);
}
void Element::SetOuterHTMLFromString(const String& html,
ExceptionState& exception_state) {
Node* p = parentNode();
if (!p) {
exception_state.ThrowDOMException(
DOMExceptionCode::kNoModificationAllowedError,
"This element has no parent node.");
return;
}
if (!p->IsElementNode()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kNoModificationAllowedError,
"This element's parent is of type '" + p->nodeName() +
"', which is not an element node.");
return;
}
Element* parent = ToElement(p);
Node* prev = previousSibling();
Node* next = nextSibling();
DocumentFragment* fragment = CreateFragmentForInnerOuterHTML(
html, parent, kAllowScriptingContent, "outerHTML", exception_state);
if (exception_state.HadException())
return;
parent->ReplaceChild(fragment, this, exception_state);
Node* node = next ? next->previousSibling() : nullptr;
if (!exception_state.HadException() && node && node->IsTextNode())
MergeWithNextTextNode(ToText(node), exception_state);
if (!exception_state.HadException() && prev && prev->IsTextNode())
MergeWithNextTextNode(ToText(prev), exception_state);
}
void Element::setOuterHTML(const StringOrTrustedHTML& string_or_html,
ExceptionState& exception_state) {
String html =
TrustedHTML::GetString(string_or_html, &GetDocument(), exception_state);
if (!exception_state.HadException()) {
SetOuterHTMLFromString(html, exception_state);
}
}
Node* Element::InsertAdjacent(const String& where,
Node* new_child,
ExceptionState& exception_state) {
if (DeprecatedEqualIgnoringCase(where, "beforeBegin")) {
if (ContainerNode* parent = parentNode()) {
parent->InsertBefore(new_child, this, exception_state);
if (!exception_state.HadException())
return new_child;
}
return nullptr;
}
if (DeprecatedEqualIgnoringCase(where, "afterBegin")) {
InsertBefore(new_child, firstChild(), exception_state);
return exception_state.HadException() ? nullptr : new_child;
}
if (DeprecatedEqualIgnoringCase(where, "beforeEnd")) {
AppendChild(new_child, exception_state);
return exception_state.HadException() ? nullptr : new_child;
}
if (DeprecatedEqualIgnoringCase(where, "afterEnd")) {
if (ContainerNode* parent = parentNode()) {
parent->InsertBefore(new_child, nextSibling(), exception_state);
if (!exception_state.HadException())
return new_child;
}
return nullptr;
}
exception_state.ThrowDOMException(
DOMExceptionCode::kSyntaxError,
"The value provided ('" + where +
"') is not one of 'beforeBegin', 'afterBegin', "
"'beforeEnd', or 'afterEnd'.");
return nullptr;
}
ElementIntersectionObserverData* Element::IntersectionObserverData() const {
if (HasRareData())
return GetElementRareData()->IntersectionObserverData();
return nullptr;
}
ElementIntersectionObserverData& Element::EnsureIntersectionObserverData() {
return EnsureElementRareData().EnsureIntersectionObserverData();
}
HeapHashMap<TraceWrapperMember<ResizeObserver>, Member<ResizeObservation>>*
Element::ResizeObserverData() const {
if (HasRareData())
return GetElementRareData()->ResizeObserverData();
return nullptr;
}
HeapHashMap<TraceWrapperMember<ResizeObserver>, Member<ResizeObservation>>&
Element::EnsureResizeObserverData() {
return EnsureElementRareData().EnsureResizeObserverData();
}
void Element::SetNeedsResizeObserverUpdate() {
if (auto* data = ResizeObserverData()) {
for (auto& observation : data->Values())
observation->ElementSizeChanged();
}
}
void Element::WillBeginCustomizedScrollPhase(
ScrollCustomization::ScrollDirection direction) {
DCHECK(!GetScrollCustomizationCallbacks().InScrollPhase(this));
LayoutBox* box = GetLayoutBox();
if (!box)
return;
ScrollCustomization::ScrollDirection scroll_customization =
box->Style()->ScrollCustomization();
GetScrollCustomizationCallbacks().SetInScrollPhase(
this, direction & scroll_customization);
}
void Element::DidEndCustomizedScrollPhase() {
GetScrollCustomizationCallbacks().SetInScrollPhase(this, false);
}
// Step 1 of http://domparsing.spec.whatwg.org/#insertadjacenthtml()
static Element* ContextElementForInsertion(const String& where,
Element* element,
ExceptionState& exception_state) {
if (DeprecatedEqualIgnoringCase(where, "beforeBegin") ||
DeprecatedEqualIgnoringCase(where, "afterEnd")) {
Element* parent = element->parentElement();
if (!parent) {
exception_state.ThrowDOMException(
DOMExceptionCode::kNoModificationAllowedError,
"The element has no parent.");
return nullptr;
}
return parent;
}
if (DeprecatedEqualIgnoringCase(where, "afterBegin") ||
DeprecatedEqualIgnoringCase(where, "beforeEnd"))
return element;
exception_state.ThrowDOMException(
DOMExceptionCode::kSyntaxError,
"The value provided ('" + where +
"') is not one of 'beforeBegin', 'afterBegin', "
"'beforeEnd', or 'afterEnd'.");
return nullptr;
}
Element* Element::insertAdjacentElement(const String& where,
Element* new_child,
ExceptionState& exception_state) {
Node* return_value = InsertAdjacent(where, new_child, exception_state);
return ToElement(return_value);
}
void Element::insertAdjacentText(const String& where,
const String& text,
ExceptionState& exception_state) {
InsertAdjacent(where, GetDocument().createTextNode(text), exception_state);
}
void Element::insertAdjacentHTML(const String& where,
const String& markup,
ExceptionState& exception_state) {
Element* context_element =
ContextElementForInsertion(where, this, exception_state);
if (!context_element)
return;
DocumentFragment* fragment = CreateFragmentForInnerOuterHTML(
markup, context_element, kAllowScriptingContent, "insertAdjacentHTML",
exception_state);
if (!fragment)
return;
InsertAdjacent(where, fragment, exception_state);
}
void Element::insertAdjacentHTML(const String& where,
const StringOrTrustedHTML& string_or_html,
ExceptionState& exception_state) {
String markup =
TrustedHTML::GetString(string_or_html, &GetDocument(), exception_state);
if (!exception_state.HadException()) {
insertAdjacentHTML(where, markup, exception_state);
}
}
void Element::setPointerCapture(int pointer_id,
ExceptionState& exception_state) {
if (GetDocument().GetFrame()) {
if (!GetDocument().GetFrame()->GetEventHandler().IsPointerEventActive(
pointer_id)) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidPointerId,
"InvalidPointerId");
} else if (!isConnected() ||
(GetDocument().GetPage() && GetDocument()
.GetPage()
->GetPointerLockController()
.GetElement())) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
"InvalidStateError");
} else {
GetDocument().GetFrame()->GetEventHandler().SetPointerCapture(pointer_id,
this);
}
}
}
void Element::releasePointerCapture(int pointer_id,
ExceptionState& exception_state) {
if (GetDocument().GetFrame()) {
if (!GetDocument().GetFrame()->GetEventHandler().IsPointerEventActive(
pointer_id)) {
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidPointerId,
"InvalidPointerId");
} else {
GetDocument().GetFrame()->GetEventHandler().ReleasePointerCapture(
pointer_id, this);
}
}
}
bool Element::hasPointerCapture(int pointer_id) const {
return GetDocument().GetFrame() &&
GetDocument().GetFrame()->GetEventHandler().HasPointerCapture(
pointer_id, this);
}
bool Element::HasProcessedPointerCapture(int pointer_id) const {
return GetDocument().GetFrame() &&
GetDocument().GetFrame()->GetEventHandler().HasProcessedPointerCapture(
pointer_id, this);
}
String Element::innerText() {
// We need to update layout, since plainText uses line boxes in the layout
// tree.
GetDocument().UpdateStyleAndLayoutIgnorePendingStylesheetsForNode(this);
if (!GetLayoutObject() && !HasDisplayContentsStyle())
return textContent(true);
return PlainText(
EphemeralRange::RangeOfContents(*this),
TextIteratorBehavior::Builder().SetForInnerText(true).Build());
}
String Element::outerText() {
// Getting outerText is the same as getting innerText, only
// setting is different. You would think this should get the plain
// text for the outer range, but this is wrong, <br> for instance
// would return different values for inner and outer text by such
// a rule, but it doesn't in WinIE, and we want to match that.
return innerText();
}
String Element::TextFromChildren() {
Text* first_text_node = nullptr;
bool found_multiple_text_nodes = false;
unsigned total_length = 0;
for (Node* child = firstChild(); child; child = child->nextSibling()) {
if (!child->IsTextNode())
continue;
Text* text = ToText(child);
if (!first_text_node)
first_text_node = text;
else
found_multiple_text_nodes = true;
unsigned length = text->data().length();
if (length > std::numeric_limits<unsigned>::max() - total_length)
return g_empty_string;
total_length += length;
}
if (!first_text_node)
return g_empty_string;
if (first_text_node && !found_multiple_text_nodes) {
first_text_node->Atomize();
return first_text_node->data();
}
StringBuilder content;
content.ReserveCapacity(total_length);
for (Node* child = first_text_node; child; child = child->nextSibling()) {
if (!child->IsTextNode())
continue;
content.Append(ToText(child)->data());
}
DCHECK_EQ(content.length(), total_length);
return content.ToString();
}
const AtomicString& Element::ShadowPseudoId() const {
if (ShadowRoot* root = ContainingShadowRoot()) {
if (root->IsUserAgent())
return FastGetAttribute(pseudoAttr);
}
return g_null_atom;
}
void Element::SetShadowPseudoId(const AtomicString& id) {
DCHECK(CSSSelector::ParsePseudoType(id, false) ==
CSSSelector::kPseudoWebKitCustomElement ||
CSSSelector::ParsePseudoType(id, false) ==
CSSSelector::kPseudoBlinkInternalElement);
setAttribute(pseudoAttr, id);
}
bool Element::IsInDescendantTreeOf(const Element* shadow_host) const {
DCHECK(shadow_host);
DCHECK(IsShadowHost(shadow_host));
for (const Element* ancestor_shadow_host = OwnerShadowHost();
ancestor_shadow_host;
ancestor_shadow_host = ancestor_shadow_host->OwnerShadowHost()) {
if (ancestor_shadow_host == shadow_host)
return true;
}
return false;
}
const ComputedStyle* Element::EnsureComputedStyle(
PseudoId pseudo_element_specifier) {
if (PseudoElement* element = GetPseudoElement(pseudo_element_specifier))
return element->EnsureComputedStyle();
if (!InActiveDocument()) {
// FIXME: Try to do better than this. Ensure that styleForElement() works
// for elements that are not in the document tree and figure out when to
// destroy the computed style for such elements.
return nullptr;
}
// FIXME: Find and use the layoutObject from the pseudo element instead of the
// actual element so that the 'length' properties, which are only known by the
// layoutObject because it did the layout, will be correct and so that the
// values returned for the ":selection" pseudo-element will be correct.
ComputedStyle* element_style = MutableComputedStyle();
if (!element_style) {
ElementRareData& rare_data = EnsureElementRareData();
if (!rare_data.GetComputedStyle())
rare_data.SetComputedStyle(
GetDocument().StyleForElementIgnoringPendingStylesheets(this));
element_style = rare_data.GetComputedStyle();
}
if (!pseudo_element_specifier)
return element_style;
if (ComputedStyle* pseudo_element_style =
element_style->GetCachedPseudoStyle(pseudo_element_specifier))
return pseudo_element_style;
const ComputedStyle* layout_parent_style = element_style;
if (HasDisplayContentsStyle()) {
LayoutObject* parent_layout_object =
LayoutTreeBuilderTraversal::ParentLayoutObject(*this);
if (parent_layout_object)
layout_parent_style = parent_layout_object->Style();
}
scoped_refptr<ComputedStyle> result =
GetDocument().EnsureStyleResolver().PseudoStyleForElement(
this,
PseudoStyleRequest(pseudo_element_specifier,
PseudoStyleRequest::kForComputedStyle),
element_style, layout_parent_style);
DCHECK(result);
return element_style->AddCachedPseudoStyle(std::move(result));
}
const ComputedStyle* Element::NonLayoutObjectComputedStyle() const {
if (NeedsReattachLayoutTree())
return GetNonAttachedStyle();
if (!HasRareData())
return nullptr;
return GetElementRareData()->GetComputedStyle();
}
bool Element::HasDisplayContentsStyle() const {
if (const ComputedStyle* style = NonLayoutObjectComputedStyle())
return style->Display() == EDisplay::kContents;
return false;
}
bool Element::ShouldStoreNonLayoutObjectComputedStyle(
const ComputedStyle& style) const {
#if DCHECK_IS_ON()
if (style.Display() == EDisplay::kContents && !NeedsReattachLayoutTree())
DCHECK(!GetLayoutObject() || IsPseudoElement());
#endif
if (style.Display() == EDisplay::kNone)
return false;
if (IsSVGElement()) {
Element* parent_element = LayoutTreeBuilderTraversal::ParentElement(*this);
if (parent_element && !parent_element->IsSVGElement())
return false;
if (IsSVGStopElement(*this))
return true;
}
if (style.Display() == EDisplay::kContents)
return true;
return IsHTMLOptGroupElement(*this) || IsHTMLOptionElement(*this);
}
void Element::StoreNonLayoutObjectComputedStyle(
scoped_refptr<ComputedStyle> style) {
DCHECK(style);
DCHECK(ShouldStoreNonLayoutObjectComputedStyle(*style));
EnsureElementRareData().SetComputedStyle(std::move(style));
}
AtomicString Element::ComputeInheritedLanguage() const {
const Node* n = this;
AtomicString value;
// The language property is inherited, so we iterate over the parents to find
// the first language.
do {
if (n->IsElementNode()) {
if (const ElementData* element_data = ToElement(n)->GetElementData()) {
AttributeCollection attributes = element_data->Attributes();
// Spec: xml:lang takes precedence -- http://www.w3.org/TR/xhtml1/#C_7
if (const Attribute* attribute = attributes.Find(XMLNames::langAttr))
value = attribute->Value();
else if (const Attribute* attribute =
attributes.Find(HTMLNames::langAttr))
value = attribute->Value();
}
} else if (n->IsDocumentNode()) {
// checking the MIME content-language
value = ToDocument(n)->ContentLanguage();
}
n = n->ParentOrShadowHostNode();
} while (n && value.IsNull());
return value;
}
Locale& Element::GetLocale() const {
return GetDocument().GetCachedLocale(ComputeInheritedLanguage());
}
void Element::CancelFocusAppearanceUpdate() {
if (GetDocument().FocusedElement() == this)
GetDocument().CancelFocusAppearanceUpdate();
}
void Element::UpdateFirstLetterPseudoElement(StyleUpdatePhase phase) {
// Update the ::first-letter pseudo elements presence and its style. This
// method may be called from style recalc or layout tree rebuilding/
// reattachment. In order to know if an element generates a ::first-letter
// element, we need to know if:
//
// * The element generates a block level box to which ::first-letter applies.
// * The element's layout subtree generates any first letter text.
// * None of the descendant blocks generate a ::first-letter element.
// (This is not correct according to spec as all block containers should be
// able to generate ::first-letter elements around the first letter of the
// first formatted text, but Blink is only supporting a single
// ::first-letter element which is the innermost block generating a
// ::first-letter).
//
// We do not always do this at style recalc time as that would have required
// us to collect the information about how the layout tree will look like
// after the layout tree is attached. So, instead we will wait until we have
// an up-to-date layout sub-tree for the element we are considering for
// ::first-letter.
//
// The StyleUpdatePhase tells where we are in the process of updating style
// and layout tree.
PseudoElement* element = GetPseudoElement(kPseudoIdFirstLetter);
if (!element) {
element = CreatePseudoElementIfNeeded(kPseudoIdFirstLetter);
// If we are in Element::AttachLayoutTree, don't mess up the ancestor flags
// for layout tree attachment/rebuilding. We will unconditionally call
// AttachLayoutTree for the created pseudo element immediately after this
// call.
if (element && phase != StyleUpdatePhase::kAttachLayoutTree)
element->SetNeedsReattachLayoutTree();
return;
}
if (phase == StyleUpdatePhase::kRebuildLayoutTree &&
element->NeedsReattachLayoutTree()) {
// We were already updated in RecalcStyle and ready for reattach.
DCHECK(element->GetNonAttachedStyle());
return;
}
if (!CanGeneratePseudoElement(kPseudoIdFirstLetter)) {
GetElementRareData()->SetPseudoElement(kPseudoIdFirstLetter, nullptr);
return;
}
LayoutObject* remaining_text_layout_object =
FirstLetterPseudoElement::FirstLetterTextLayoutObject(*element);
if (!remaining_text_layout_object) {
GetElementRareData()->SetPseudoElement(kPseudoIdFirstLetter, nullptr);
return;
}
bool text_node_changed =
remaining_text_layout_object !=
ToFirstLetterPseudoElement(element)->RemainingTextLayoutObject();
if (phase == StyleUpdatePhase::kAttachLayoutTree) {
// RemainingTextLayoutObject should have been cleared from DetachLayoutTree.
DCHECK(!ToFirstLetterPseudoElement(element)->RemainingTextLayoutObject());
DCHECK(text_node_changed);
scoped_refptr<ComputedStyle> pseudo_style = element->StyleForLayoutObject();
if (PseudoElementLayoutObjectIsNeeded(pseudo_style.get()))
element->SetNonAttachedStyle(std::move(pseudo_style));
else
GetElementRareData()->SetPseudoElement(kPseudoIdFirstLetter, nullptr);
return;
}
element->RecalcStyle(text_node_changed ? kReattach : kForce);
if (element->NeedsReattachLayoutTree() &&
!PseudoElementLayoutObjectIsNeeded(element->GetNonAttachedStyle())) {
GetElementRareData()->SetPseudoElement(kPseudoIdFirstLetter, nullptr);
}
}
void Element::UpdatePseudoElement(PseudoId pseudo_id,
StyleRecalcChange change) {
PseudoElement* element = GetPseudoElement(pseudo_id);
if (!element) {
if (change < kUpdatePseudoElements)
return;
if ((element = CreatePseudoElementIfNeeded(pseudo_id)))
element->SetNeedsReattachLayoutTree();
return;
}
if (change == kUpdatePseudoElements ||
element->ShouldCallRecalcStyle(change)) {
if (CanGeneratePseudoElement(pseudo_id)) {
element->RecalcStyle(change == kUpdatePseudoElements ? kForce : change);
if (!element->NeedsReattachLayoutTree())
return;
if (PseudoElementLayoutObjectIsNeeded(element->GetNonAttachedStyle()))
return;
}
GetElementRareData()->SetPseudoElement(pseudo_id, nullptr);
}
}
PseudoElement* Element::CreatePseudoElementIfNeeded(PseudoId pseudo_id) {
if (IsPseudoElement())
return nullptr;
if (!CanGeneratePseudoElement(pseudo_id))
return nullptr;
if (pseudo_id == kPseudoIdFirstLetter) {
if (!FirstLetterPseudoElement::FirstLetterTextLayoutObject(*this))
return nullptr;
}
PseudoElement* pseudo_element = PseudoElement::Create(this, pseudo_id);
EnsureElementRareData().SetPseudoElement(pseudo_id, pseudo_element);
pseudo_element->InsertedInto(*this);
scoped_refptr<ComputedStyle> pseudo_style =
pseudo_element->StyleForLayoutObject();
if (!PseudoElementLayoutObjectIsNeeded(pseudo_style.get())) {
GetElementRareData()->SetPseudoElement(pseudo_id, nullptr);
return nullptr;
}
if (pseudo_id == kPseudoIdBackdrop)
GetDocument().AddToTopLayer(pseudo_element, this);
pseudo_element->SetNonAttachedStyle(std::move(pseudo_style));
probe::pseudoElementCreated(pseudo_element);
return pseudo_element;
}
void Element::AttachPseudoElement(PseudoId pseudo_id, AttachContext& context) {
if (PseudoElement* pseudo_element = GetPseudoElement(pseudo_id))
pseudo_element->AttachLayoutTree(context);
}
void Element::DetachPseudoElement(PseudoId pseudo_id,
const AttachContext& context) {
if (PseudoElement* pseudo_element = GetPseudoElement(pseudo_id))
pseudo_element->DetachLayoutTree(context);
}
PseudoElement* Element::GetPseudoElement(PseudoId pseudo_id) const {
return HasRareData() ? GetElementRareData()->GetPseudoElement(pseudo_id)
: nullptr;
}
LayoutObject* Element::PseudoElementLayoutObject(PseudoId pseudo_id) const {
if (PseudoElement* element = GetPseudoElement(pseudo_id))
return element->GetLayoutObject();
return nullptr;
}
ComputedStyle* Element::CachedStyleForPseudoElement(
const PseudoStyleRequest& request,
const ComputedStyle* parent_style) {
ComputedStyle* style = MutableComputedStyle();
if (!style || (request.pseudo_id < kFirstInternalPseudoId &&
!style->HasPseudoStyle(request.pseudo_id))) {
return nullptr;
}
if (ComputedStyle* cached = style->GetCachedPseudoStyle(request.pseudo_id))
return cached;
scoped_refptr<ComputedStyle> result =
StyleForPseudoElement(request, parent_style);
if (result)
return style->AddCachedPseudoStyle(std::move(result));
return nullptr;
}
scoped_refptr<ComputedStyle> Element::StyleForPseudoElement(
const PseudoStyleRequest& request,
const ComputedStyle* parent_style) {
const ComputedStyle* style = GetComputedStyle();
const bool is_before_or_after = request.pseudo_id == kPseudoIdBefore ||
request.pseudo_id == kPseudoIdAfter;
DCHECK(style);
DCHECK(!parent_style || !is_before_or_after);
if (is_before_or_after) {
const ComputedStyle* layout_parent_style = style;
if (style->Display() == EDisplay::kContents) {
// TODO(futhark@chromium.org): Calling getComputedStyle for elements
// outside the flat tree should return empty styles, but currently we do
// not. See issue https://crbug.com/831568. We can replace the if-test
// with DCHECK(layout_parent) when that issue is fixed.
if (Node* layout_parent =
LayoutTreeBuilderTraversal::LayoutParent(*this)) {
layout_parent_style = layout_parent->GetComputedStyle();
}
}
return GetDocument().EnsureStyleResolver().PseudoStyleForElement(
this, request, style, layout_parent_style);
}
if (!parent_style)
parent_style = style;
if (request.pseudo_id == kPseudoIdFirstLineInherited) {
scoped_refptr<ComputedStyle> result =
GetDocument().EnsureStyleResolver().StyleForElement(this, parent_style,
parent_style);
result->SetStyleType(kPseudoIdFirstLineInherited);
return result;
}
return GetDocument().EnsureStyleResolver().PseudoStyleForElement(
this, request, parent_style, parent_style);
}
bool Element::CanGeneratePseudoElement(PseudoId pseudo_id) const {
if (pseudo_id == kPseudoIdBackdrop && !IsInTopLayer())
return false;
if (pseudo_id == kPseudoIdFirstLetter && IsSVGElement())
return false;
if (const ComputedStyle* style = GetComputedStyle())
return style->CanGeneratePseudoElement(pseudo_id);
return false;
}
bool Element::MayTriggerVirtualKeyboard() const {
return HasEditableStyle(*this);
}
bool Element::matches(const AtomicString& selectors,
ExceptionState& exception_state) {
SelectorQuery* selector_query = GetDocument().GetSelectorQueryCache().Add(
selectors, GetDocument(), exception_state);
if (!selector_query)
return false;
return selector_query->Matches(*this);
}
bool Element::matches(const AtomicString& selectors) {
return matches(selectors, ASSERT_NO_EXCEPTION);
}
Element* Element::closest(const AtomicString& selectors,
ExceptionState& exception_state) {
SelectorQuery* selector_query = GetDocument().GetSelectorQueryCache().Add(
selectors, GetDocument(), exception_state);
if (!selector_query)
return nullptr;
return selector_query->Closest(*this);
}
Element* Element::closest(const AtomicString& selectors) {
return closest(selectors, ASSERT_NO_EXCEPTION);
}
DOMTokenList& Element::classList() {
ElementRareData& rare_data = EnsureElementRareData();
if (!rare_data.GetClassList()) {
DOMTokenList* class_list = DOMTokenList::Create(*this, classAttr);
class_list->DidUpdateAttributeValue(g_null_atom, getAttribute(classAttr));
rare_data.SetClassList(class_list);
}
return *rare_data.GetClassList();
}
DOMStringMap& Element::dataset() {
ElementRareData& rare_data = EnsureElementRareData();
if (!rare_data.Dataset())
rare_data.SetDataset(DatasetDOMStringMap::Create(this));
return *rare_data.Dataset();
}
KURL Element::HrefURL() const {
// FIXME: These all have href() or url(), but no common super class. Why
// doesn't <link> implement URLUtils?
if (IsHTMLAnchorElement(*this) || IsHTMLAreaElement(*this) ||
IsHTMLLinkElement(*this))
return GetURLAttribute(hrefAttr);
if (auto* svg_a = ToSVGAElementOrNull(*this))
return svg_a->LegacyHrefURL(GetDocument());
return KURL();
}
KURL Element::GetURLAttribute(const QualifiedName& name) const {
#if DCHECK_IS_ON()
if (GetElementData()) {
if (const Attribute* attribute = Attributes().Find(name))
DCHECK(IsURLAttribute(*attribute));
}
#endif
return GetDocument().CompleteURL(
StripLeadingAndTrailingHTMLSpaces(getAttribute(name)));
}
void Element::GetURLAttribute(const QualifiedName& name,
StringOrTrustedScriptURL& result) const {
KURL url = GetURLAttribute(name);
result.SetString(url.GetString());
}
void Element::GetURLAttribute(const QualifiedName& name,
USVStringOrTrustedURL& result) const {
String url = GetURLAttribute(name);
result.SetUSVString(url);
}
void Element::FastGetAttribute(const QualifiedName& name,
USVStringOrTrustedURL& result) const {
String attr = FastGetAttribute(name);
result.SetUSVString(attr);
}
void Element::FastGetAttribute(const QualifiedName& name,
StringOrTrustedHTML& result) const {
String html = FastGetAttribute(name);
result.SetString(html);
}
KURL Element::GetNonEmptyURLAttribute(const QualifiedName& name) const {
#if DCHECK_IS_ON()
if (GetElementData()) {
if (const Attribute* attribute = Attributes().Find(name))
DCHECK(IsURLAttribute(*attribute));
}
#endif
String value = StripLeadingAndTrailingHTMLSpaces(getAttribute(name));
if (value.IsEmpty())
return KURL();
return GetDocument().CompleteURL(value);
}
int Element::GetIntegralAttribute(const QualifiedName& attribute_name) const {
int integral_value = 0;
ParseHTMLInteger(getAttribute(attribute_name), integral_value);
return integral_value;
}
void Element::SetIntegralAttribute(const QualifiedName& attribute_name,
int value) {
setAttribute(attribute_name, AtomicString::Number(value));
}
void Element::SetUnsignedIntegralAttribute(const QualifiedName& attribute_name,
unsigned value,
unsigned default_value) {
// Range restrictions are enforced for unsigned IDL attributes that
// reflect content attributes,
// http://www.whatwg.org/specs/web-apps/current-work/multipage/common-dom-interfaces.html#reflecting-content-attributes-in-idl-attributes
if (value > 0x7fffffffu)
value = default_value;
setAttribute(attribute_name, AtomicString::Number(value));
}
double Element::GetFloatingPointAttribute(const QualifiedName& attribute_name,
double fallback_value) const {
return ParseToDoubleForNumberType(getAttribute(attribute_name),
fallback_value);
}
void Element::SetFloatingPointAttribute(const QualifiedName& attribute_name,
double value) {
setAttribute(attribute_name, AtomicString::Number(value));
}
void Element::SetContainsFullScreenElement(bool flag) {
SetElementFlag(ElementFlags::kContainsFullScreenElement, flag);
// When exiting fullscreen, the element's document may not be active.
if (flag) {
DCHECK(GetDocument().IsActive());
GetDocument().GetStyleEngine().EnsureUAStyleForFullscreen();
}
PseudoStateChanged(CSSSelector::kPseudoFullScreenAncestor);
}
// Unlike Node::parentOrShadowHostElement, this can cross frame boundaries.
static Element* NextAncestorElement(Element* element) {
DCHECK(element);
if (element->ParentOrShadowHostElement())
return element->ParentOrShadowHostElement();
Frame* frame = element->GetDocument().GetFrame();
if (!frame || !frame->Owner())
return nullptr;
// Find the next LocalFrame on the ancestor chain, and return the
// corresponding <iframe> element for the remote child if it exists.
while (frame->Tree().Parent() && frame->Tree().Parent()->IsRemoteFrame())
frame = frame->Tree().Parent();
if (frame->Owner() && frame->Owner()->IsLocal())
return ToHTMLFrameOwnerElement(frame->Owner());
return nullptr;
}
void Element::SetContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(
bool flag) {
for (Element* element = NextAncestorElement(this); element;
element = NextAncestorElement(element))
element->SetContainsFullScreenElement(flag);
}
void Element::SetContainsPersistentVideo(bool value) {
SetElementFlag(ElementFlags::kContainsPersistentVideo, value);
PseudoStateChanged(CSSSelector::kPseudoVideoPersistentAncestor);
// In some rare situations, when the persistent video has been removed from
// the tree, part of the tree might still carry the flag.
if (!value && Fullscreen::IsFullscreenElement(*this)) {
for (Node* node = firstChild(); node;) {
if (!node->IsElementNode() ||
!ToElement(node)->ContainsPersistentVideo()) {
node = node->nextSibling();
break;
}
ToElement(node)->SetContainsPersistentVideo(false);
node = node->firstChild();
}
}
}
void Element::SetIsInTopLayer(bool in_top_layer) {
if (IsInTopLayer() == in_top_layer)
return;
SetElementFlag(ElementFlags::kIsInTopLayer, in_top_layer);
// We must ensure a reattach occurs so the layoutObject is inserted in the
// correct sibling order under LayoutView according to its top layer position,
// or in its usual place if not in the top layer.
LazyReattachIfAttached();
}
void Element::requestPointerLock() {
if (GetDocument().GetPage())
GetDocument().GetPage()->GetPointerLockController().RequestPointerLock(
this);
}
SpellcheckAttributeState Element::GetSpellcheckAttributeState() const {
const AtomicString& value = FastGetAttribute(spellcheckAttr);
if (value == g_null_atom)
return kSpellcheckAttributeDefault;
if (DeprecatedEqualIgnoringCase(value, "true") ||
DeprecatedEqualIgnoringCase(value, ""))
return kSpellcheckAttributeTrue;
if (DeprecatedEqualIgnoringCase(value, "false"))
return kSpellcheckAttributeFalse;
return kSpellcheckAttributeDefault;
}
bool Element::IsSpellCheckingEnabled() const {
for (const Element* element = this; element;
element = element->ParentOrShadowHostElement()) {
switch (element->GetSpellcheckAttributeState()) {
case kSpellcheckAttributeTrue:
return true;
case kSpellcheckAttributeFalse:
return false;
case kSpellcheckAttributeDefault:
break;
}
}
if (!GetDocument().GetPage())
return true;
return GetDocument().GetPage()->GetSettings().GetSpellCheckEnabledByDefault();
}
#if DCHECK_IS_ON()
bool Element::FastAttributeLookupAllowed(const QualifiedName& name) const {
if (name == HTMLNames::styleAttr)
return false;
if (IsSVGElement())
return !ToSVGElement(this)->IsAnimatableAttribute(name);
return true;
}
#endif
#ifdef DUMP_NODE_STATISTICS
bool Element::HasNamedNodeMap() const {
return HasRareData() && GetElementRareData()->AttributeMap();
}
#endif
inline void Element::UpdateName(const AtomicString& old_name,
const AtomicString& new_name) {
if (!IsInDocumentTree())
return;
if (old_name == new_name)
return;
NamedItemType type = GetNamedItemType();
if (type != NamedItemType::kNone)
UpdateNamedItemRegistration(type, old_name, new_name);
}
inline void Element::UpdateId(const AtomicString& old_id,
const AtomicString& new_id) {
if (!IsInTreeScope())
return;
if (old_id == new_id)
return;
UpdateId(ContainingTreeScope(), old_id, new_id);
}
inline void Element::UpdateId(TreeScope& scope,
const AtomicString& old_id,
const AtomicString& new_id) {
DCHECK(IsInTreeScope());
DCHECK_NE(old_id, new_id);
if (!old_id.IsEmpty())
scope.RemoveElementById(old_id, *this);
if (!new_id.IsEmpty())
scope.AddElementById(new_id, *this);
NamedItemType type = GetNamedItemType();
if (type == NamedItemType::kNameOrId ||
type == NamedItemType::kNameOrIdWithName)
UpdateIdNamedItemRegistration(type, old_id, new_id);
}
void Element::WillModifyAttribute(const QualifiedName& name,
const AtomicString& old_value,
const AtomicString& new_value) {
if (name == HTMLNames::nameAttr) {
UpdateName(old_value, new_value);
}
if (GetCustomElementState() == CustomElementState::kCustom) {
CustomElement::EnqueueAttributeChangedCallback(this, name, old_value,
new_value);
}
if (old_value != new_value) {
GetDocument().GetStyleEngine().AttributeChangedForElement(name, *this);
if (IsUpgradedV0CustomElement()) {
V0CustomElement::AttributeDidChange(this, name.LocalName(), old_value,
new_value);
}
}
if (MutationObserverInterestGroup* recipients =
MutationObserverInterestGroup::CreateForAttributesMutation(*this,
name))
recipients->EnqueueMutationRecord(
MutationRecord::CreateAttributes(this, name, old_value));
probe::willModifyDOMAttr(this, old_value, new_value);
}
DISABLE_CFI_PERF
void Element::DidAddAttribute(const QualifiedName& name,
const AtomicString& value) {
if (name == HTMLNames::idAttr)
UpdateId(g_null_atom, value);
AttributeChanged(AttributeModificationParams(
name, g_null_atom, value, AttributeModificationReason::kDirectly));
probe::didModifyDOMAttr(this, name, value);
DispatchSubtreeModifiedEvent();
}
void Element::DidModifyAttribute(const QualifiedName& name,
const AtomicString& old_value,
const AtomicString& new_value) {
if (name == HTMLNames::idAttr)
UpdateId(old_value, new_value);
AttributeChanged(AttributeModificationParams(
name, old_value, new_value, AttributeModificationReason::kDirectly));
probe::didModifyDOMAttr(this, name, new_value);
// Do not dispatch a DOMSubtreeModified event here; see bug 81141.
}
void Element::DidRemoveAttribute(const QualifiedName& name,
const AtomicString& old_value) {
if (name == HTMLNames::idAttr)
UpdateId(old_value, g_null_atom);
AttributeChanged(AttributeModificationParams(
name, old_value, g_null_atom, AttributeModificationReason::kDirectly));
probe::didRemoveDOMAttr(this, name);
DispatchSubtreeModifiedEvent();
}
static bool NeedsURLResolutionForInlineStyle(const Element& element,
const Document& old_document,
const Document& new_document) {
if (old_document == new_document)
return false;
if (old_document.BaseURL() == new_document.BaseURL())
return false;
const CSSPropertyValueSet* style = element.InlineStyle();
if (!style)
return false;
for (unsigned i = 0; i < style->PropertyCount(); ++i) {
if (style->PropertyAt(i).Value().MayContainUrl())
return true;
}
return false;
}
static void ReResolveURLsInInlineStyle(const Document& document,
MutableCSSPropertyValueSet& style) {
for (unsigned i = 0; i < style.PropertyCount(); ++i) {
const CSSValue& value = style.PropertyAt(i).Value();
if (value.MayContainUrl())
value.ReResolveUrl(document);
}
}
void Element::DidMoveToNewDocument(Document& old_document) {
Node::DidMoveToNewDocument(old_document);
// If the documents differ by quirks mode then they differ by case sensitivity
// for class and id names so we need to go through the attribute change logic
// to pick up the new casing in the ElementData.
if (old_document.InQuirksMode() != GetDocument().InQuirksMode()) {
// TODO(tkent): If new owner Document has a ShareableElementData matching to
// this element's attributes, we shouldn't make UniqueElementData, and this
// element should point to the shareable one.
EnsureUniqueElementData();
if (HasID())
SetIdAttribute(GetIdAttribute());
if (HasClass())
setAttribute(HTMLNames::classAttr, GetClassAttribute());
}
// TODO(tkent): Even if Documents' modes are same, keeping
// ShareableElementData owned by old_document isn't right.
if (NeedsURLResolutionForInlineStyle(*this, old_document, GetDocument()))
ReResolveURLsInInlineStyle(GetDocument(), EnsureMutableInlineStyle());
}
void Element::UpdateNamedItemRegistration(NamedItemType type,
const AtomicString& old_name,
const AtomicString& new_name) {
if (!GetDocument().IsHTMLDocument())
return;
HTMLDocument& doc = ToHTMLDocument(GetDocument());
if (!old_name.IsEmpty())
doc.RemoveNamedItem(old_name);
if (!new_name.IsEmpty())
doc.AddNamedItem(new_name);
if (type == NamedItemType::kNameOrIdWithName) {
const AtomicString id = GetIdAttribute();
if (!id.IsEmpty()) {
if (!old_name.IsEmpty() && new_name.IsEmpty())
doc.RemoveNamedItem(id);
else if (old_name.IsEmpty() && !new_name.IsEmpty())
doc.AddNamedItem(id);
}
}
}
void Element::UpdateIdNamedItemRegistration(NamedItemType type,
const AtomicString& old_id,
const AtomicString& new_id) {
if (!GetDocument().IsHTMLDocument())
return;
if (type == NamedItemType::kNameOrIdWithName && GetNameAttribute().IsEmpty())
return;
if (!old_id.IsEmpty())
ToHTMLDocument(GetDocument()).RemoveNamedItem(old_id);
if (!new_id.IsEmpty())
ToHTMLDocument(GetDocument()).AddNamedItem(new_id);
}
ScrollOffset Element::SavedLayerScrollOffset() const {
return HasRareData() ? GetElementRareData()->SavedLayerScrollOffset()
: ScrollOffset();
}
void Element::SetSavedLayerScrollOffset(const ScrollOffset& size) {
if (size.IsZero() && !HasRareData())
return;
EnsureElementRareData().SetSavedLayerScrollOffset(size);
}
Attr* Element::AttrIfExists(const QualifiedName& name) {
if (AttrNodeList* attr_node_list = GetAttrNodeList()) {
for (const auto& attr : *attr_node_list) {
if (attr->GetQualifiedName().Matches(name))
return attr.Get();
}
}
return nullptr;
}
Attr* Element::EnsureAttr(const QualifiedName& name) {
Attr* attr_node = AttrIfExists(name);
if (!attr_node) {
attr_node = Attr::Create(*this, name);
GetTreeScope().AdoptIfNeeded(*attr_node);
EnsureElementRareData().AddAttr(attr_node);
}
return attr_node;
}
void Element::DetachAttrNodeFromElementWithValue(Attr* attr_node,
const AtomicString& value) {
DCHECK(GetAttrNodeList());
attr_node->DetachFromElementWithValue(value);
AttrNodeList* list = GetAttrNodeList();
size_t index = list->Find(attr_node);
DCHECK_NE(index, kNotFound);
list->EraseAt(index);
if (list->IsEmpty())
RemoveAttrNodeList();
}
void Element::DetachAllAttrNodesFromElement() {
AttrNodeList* list = GetAttrNodeList();
if (!list)
return;
AttributeCollection attributes = GetElementData()->Attributes();
for (const Attribute& attr : attributes) {
if (Attr* attr_node = AttrIfExists(attr.GetName()))
attr_node->DetachFromElementWithValue(attr.Value());
}
RemoveAttrNodeList();
}
Node::InsertionNotificationRequest Node::InsertedInto(
ContainerNode& insertion_point) {
DCHECK(!ChildNeedsStyleInvalidation());
DCHECK(!NeedsStyleInvalidation());
DCHECK(insertion_point.isConnected() || insertion_point.IsInShadowTree() ||
IsContainerNode());
if (insertion_point.isConnected()) {
SetFlag(kIsConnectedFlag);
insertion_point.GetDocument().IncrementNodeCount();
}
if (ParentOrShadowHostNode()->IsInShadowTree())
SetFlag(kIsInShadowTreeFlag);
if (ChildNeedsDistributionRecalc() &&
!insertion_point.ChildNeedsDistributionRecalc())
insertion_point.MarkAncestorsWithChildNeedsDistributionRecalc();
if (AXObjectCache* cache = GetDocument().ExistingAXObjectCache())
cache->ChildrenChanged(&insertion_point);
return kInsertionDone;
}
void Node::RemovedFrom(ContainerNode& insertion_point) {
DCHECK(insertion_point.isConnected() || IsContainerNode() ||
IsInShadowTree());
if (insertion_point.isConnected()) {
ClearFlag(kIsConnectedFlag);
insertion_point.GetDocument().DecrementNodeCount();
}
if (IsInShadowTree() && !ContainingTreeScope().RootNode().IsShadowRoot())
ClearFlag(kIsInShadowTreeFlag);
if (AXObjectCache* cache = GetDocument().ExistingAXObjectCache()) {
cache->Remove(this);
cache->ChildrenChanged(&insertion_point);
}
}
void Element::WillRecalcStyle(StyleRecalcChange) {
DCHECK(HasCustomStyleCallbacks());
}
void Element::DidRecalcStyle(StyleRecalcChange) {
DCHECK(HasCustomStyleCallbacks());
}
scoped_refptr<ComputedStyle> Element::CustomStyleForLayoutObject() {
DCHECK(HasCustomStyleCallbacks());
return OriginalStyleForLayoutObject();
}
void Element::CloneAttributesFrom(const Element& other) {
if (HasRareData())
DetachAllAttrNodesFromElement();
other.SynchronizeAllAttributes();
if (!other.element_data_) {
element_data_.Clear();
return;
}
const AtomicString& old_id = GetIdAttribute();
const AtomicString& new_id = other.GetIdAttribute();
if (!old_id.IsNull() || !new_id.IsNull())
UpdateId(old_id, new_id);
const AtomicString& old_name = GetNameAttribute();
const AtomicString& new_name = other.GetNameAttribute();
if (!old_name.IsNull() || !new_name.IsNull())
UpdateName(old_name, new_name);
// Quirks mode makes class and id not case sensitive. We can't share the
// ElementData if the idForStyleResolution and the className need different
// casing.
bool owner_documents_have_different_case_sensitivity = false;
if (other.HasClass() || other.HasID())
owner_documents_have_different_case_sensitivity =
other.GetDocument().InQuirksMode() != GetDocument().InQuirksMode();
// If 'other' has a mutable ElementData, convert it to an immutable one so we
// can share it between both elements.
// We can only do this if there are no presentation attributes and sharing the
// data won't result in different case sensitivity of class or id.
if (other.element_data_->IsUnique() &&
!owner_documents_have_different_case_sensitivity &&
!other.element_data_->PresentationAttributeStyle())
const_cast<Element&>(other).element_data_ =
ToUniqueElementData(other.element_data_)->MakeShareableCopy();
if (!other.element_data_->IsUnique() &&
!owner_documents_have_different_case_sensitivity &&
!NeedsURLResolutionForInlineStyle(other, other.GetDocument(),
GetDocument()))
element_data_ = other.element_data_;
else
element_data_ = other.element_data_->MakeUniqueCopy();
for (const Attribute& attr : element_data_->Attributes()) {
AttributeChanged(
AttributeModificationParams(attr.GetName(), g_null_atom, attr.Value(),
AttributeModificationReason::kByCloning));
}
if (other.nonce() != g_null_atom)
setNonce(other.nonce());
}
void Element::CreateUniqueElementData() {
if (!element_data_) {
element_data_ = UniqueElementData::Create();
} else {
DCHECK(!element_data_->IsUnique());
element_data_ = ToShareableElementData(element_data_)->MakeUniqueCopy();
}
}
void Element::SynchronizeStyleAttributeInternal() const {
DCHECK(IsStyledElement());
DCHECK(GetElementData());
DCHECK(GetElementData()->style_attribute_is_dirty_);
GetElementData()->style_attribute_is_dirty_ = false;
const CSSPropertyValueSet* inline_style = InlineStyle();
const_cast<Element*>(this)->SetSynchronizedLazyAttribute(
styleAttr,
inline_style ? AtomicString(inline_style->AsText()) : g_empty_atom);
}
CSSStyleDeclaration* Element::style() {
if (!IsStyledElement())
return nullptr;
return &EnsureElementRareData().EnsureInlineCSSStyleDeclaration(this);
}
StylePropertyMap* Element::attributeStyleMap() {
if (!IsStyledElement())
return nullptr;
return &EnsureElementRareData().EnsureInlineStylePropertyMap(this);
}
StylePropertyMapReadOnly* Element::ComputedStyleMap() {
return GetDocument().ComputedStyleMap(this);
}
MutableCSSPropertyValueSet& Element::EnsureMutableInlineStyle() {
DCHECK(IsStyledElement());
Member<CSSPropertyValueSet>& inline_style =
EnsureUniqueElementData().inline_style_;
if (!inline_style) {
CSSParserMode mode = (!IsHTMLElement() || GetDocument().InQuirksMode())
? kHTMLQuirksMode
: kHTMLStandardMode;
inline_style = MutableCSSPropertyValueSet::Create(mode);
} else if (!inline_style->IsMutable()) {
inline_style = inline_style->MutableCopy();
}
return *ToMutableCSSPropertyValueSet(inline_style);
}
void Element::ClearMutableInlineStyleIfEmpty() {
if (EnsureMutableInlineStyle().IsEmpty()) {
EnsureUniqueElementData().inline_style_.Clear();
}
}
inline void Element::SetInlineStyleFromString(
const AtomicString& new_style_string) {
DCHECK(IsStyledElement());
Member<CSSPropertyValueSet>& inline_style = GetElementData()->inline_style_;
// Avoid redundant work if we're using shared attribute data with already
// parsed inline style.
if (inline_style && !GetElementData()->IsUnique())
return;
// We reconstruct the property set instead of mutating if there is no CSSOM
// wrapper. This makes wrapperless property sets immutable and so cacheable.
if (inline_style && !inline_style->IsMutable())
inline_style.Clear();
if (!inline_style) {
inline_style =
CSSParser::ParseInlineStyleDeclaration(new_style_string, this);
} else {
DCHECK(inline_style->IsMutable());
static_cast<MutableCSSPropertyValueSet*>(inline_style.Get())
->ParseDeclarationList(new_style_string,
GetDocument().GetSecureContextMode(),
GetDocument().ElementSheet().Contents());
}
}
void Element::StyleAttributeChanged(
const AtomicString& new_style_string,
AttributeModificationReason modification_reason) {
DCHECK(IsStyledElement());
WTF::OrdinalNumber start_line_number = WTF::OrdinalNumber::BeforeFirst();
if (GetDocument().GetScriptableDocumentParser() &&
!GetDocument().IsInDocumentWrite())
start_line_number =
GetDocument().GetScriptableDocumentParser()->LineNumber();
if (new_style_string.IsNull()) {
EnsureUniqueElementData().inline_style_.Clear();
} else if (modification_reason == AttributeModificationReason::kByCloning ||
ContentSecurityPolicy::ShouldBypassMainWorld(&GetDocument()) ||
(ContainingShadowRoot() &&
ContainingShadowRoot()->IsUserAgent()) ||
GetDocument().GetContentSecurityPolicy()->AllowInlineStyle(
this, GetDocument().Url(), String(), start_line_number,
new_style_string,
ContentSecurityPolicy::InlineType::kAttribute)) {
SetInlineStyleFromString(new_style_string);
}
GetElementData()->style_attribute_is_dirty_ = false;
SetNeedsStyleRecalc(kLocalStyleChange,
StyleChangeReasonForTracing::Create(
StyleChangeReason::kStyleSheetChange));
probe::didInvalidateStyleAttr(this);
}
void Element::InlineStyleChanged() {
DCHECK(IsStyledElement());
SetNeedsStyleRecalc(kLocalStyleChange, StyleChangeReasonForTracing::Create(
StyleChangeReason::kInline));
DCHECK(GetElementData());
GetElementData()->style_attribute_is_dirty_ = true;
probe::didInvalidateStyleAttr(this);
if (MutationObserverInterestGroup* recipients =
MutationObserverInterestGroup::CreateForAttributesMutation(
*this, styleAttr)) {
// We don't use getAttribute() here to get a style attribute value
// before the change.
AtomicString old_value;
if (const Attribute* attribute =
GetElementData()->Attributes().Find(styleAttr))
old_value = attribute->Value();
recipients->EnqueueMutationRecord(
MutationRecord::CreateAttributes(this, styleAttr, old_value));
// Need to synchronize every time so that following MutationRecords will
// have correct oldValues.
SynchronizeAttribute(styleAttr);
}
}
void Element::SetInlineStyleProperty(CSSPropertyID property_id,
CSSValueID identifier,
bool important) {
SetInlineStyleProperty(property_id, *CSSIdentifierValue::Create(identifier),
important);
}
void Element::SetInlineStyleProperty(CSSPropertyID property_id,
double value,
CSSPrimitiveValue::UnitType unit,
bool important) {
SetInlineStyleProperty(property_id, *CSSPrimitiveValue::Create(value, unit),
important);
}
void Element::SetInlineStyleProperty(CSSPropertyID property_id,
const CSSValue& value,
bool important) {
DCHECK(IsStyledElement());
EnsureMutableInlineStyle().SetProperty(property_id, value, important);
InlineStyleChanged();
}
bool Element::SetInlineStyleProperty(CSSPropertyID property_id,
const String& value,
bool important) {
DCHECK(IsStyledElement());
bool did_change = EnsureMutableInlineStyle()
.SetProperty(property_id, value, important,
GetDocument().GetSecureContextMode(),
GetDocument().ElementSheet().Contents())
.did_change;
if (did_change)
InlineStyleChanged();
return did_change;
}
bool Element::RemoveInlineStyleProperty(CSSPropertyID property_id) {
DCHECK(IsStyledElement());
if (!InlineStyle())
return false;
bool did_change = EnsureMutableInlineStyle().RemoveProperty(property_id);
if (did_change)
InlineStyleChanged();
return did_change;
}
bool Element::RemoveInlineStyleProperty(const AtomicString& property_name) {
DCHECK(IsStyledElement());
if (!InlineStyle())
return false;
bool did_change = EnsureMutableInlineStyle().RemoveProperty(property_name);
if (did_change)
InlineStyleChanged();
return did_change;
}
void Element::RemoveAllInlineStyleProperties() {
DCHECK(IsStyledElement());
if (!InlineStyle())
return;
EnsureMutableInlineStyle().Clear();
InlineStyleChanged();
}
void Element::UpdatePresentationAttributeStyle() {
SynchronizeAllAttributes();
// ShareableElementData doesn't store presentation attribute style, so make
// sure we have a UniqueElementData.
UniqueElementData& element_data = EnsureUniqueElementData();
element_data.presentation_attribute_style_is_dirty_ = false;
element_data.presentation_attribute_style_ =
ComputePresentationAttributeStyle(*this);
}
void Element::AddPropertyToPresentationAttributeStyle(
MutableCSSPropertyValueSet* style,
CSSPropertyID property_id,
CSSValueID identifier) {
DCHECK(IsStyledElement());
style->SetProperty(property_id, *CSSIdentifierValue::Create(identifier));
}
void Element::AddPropertyToPresentationAttributeStyle(
MutableCSSPropertyValueSet* style,
CSSPropertyID property_id,
double value,
CSSPrimitiveValue::UnitType unit) {
DCHECK(IsStyledElement());
style->SetProperty(property_id, *CSSPrimitiveValue::Create(value, unit));
}
void Element::AddPropertyToPresentationAttributeStyle(
MutableCSSPropertyValueSet* style,
CSSPropertyID property_id,
const String& value) {
DCHECK(IsStyledElement());
Document& document = GetDocument();
style->SetProperty(property_id, value, false, document.GetSecureContextMode(),
document.ElementSheet().Contents());
}
void Element::AddPropertyToPresentationAttributeStyle(
MutableCSSPropertyValueSet* style,
CSSPropertyID property_id,
const CSSValue& value) {
DCHECK(IsStyledElement());
style->SetProperty(property_id, value);
}
void Element::LogAddElementIfIsolatedWorldAndInDocument(
const char element[],
const QualifiedName& attr1) {
if (!isConnected())
return;
V8DOMActivityLogger* activity_logger =
V8DOMActivityLogger::CurrentActivityLoggerIfIsolatedWorldForMainThread();
if (!activity_logger)
return;
Vector<String, 2> argv;
argv.push_back(element);
argv.push_back(FastGetAttribute(attr1));
activity_logger->LogEvent("blinkAddElement", argv.size(), argv.data());
}
void Element::LogAddElementIfIsolatedWorldAndInDocument(
const char element[],
const QualifiedName& attr1,
const QualifiedName& attr2) {
if (!isConnected())
return;
V8DOMActivityLogger* activity_logger =
V8DOMActivityLogger::CurrentActivityLoggerIfIsolatedWorldForMainThread();
if (!activity_logger)
return;
Vector<String, 3> argv;
argv.push_back(element);
argv.push_back(FastGetAttribute(attr1));
argv.push_back(FastGetAttribute(attr2));
activity_logger->LogEvent("blinkAddElement", argv.size(), argv.data());
}
void Element::LogAddElementIfIsolatedWorldAndInDocument(
const char element[],
const QualifiedName& attr1,
const QualifiedName& attr2,
const QualifiedName& attr3) {
if (!isConnected())
return;
V8DOMActivityLogger* activity_logger =
V8DOMActivityLogger::CurrentActivityLoggerIfIsolatedWorldForMainThread();
if (!activity_logger)
return;
Vector<String, 4> argv;
argv.push_back(element);
argv.push_back(FastGetAttribute(attr1));
argv.push_back(FastGetAttribute(attr2));
argv.push_back(FastGetAttribute(attr3));
activity_logger->LogEvent("blinkAddElement", argv.size(), argv.data());
}
void Element::LogUpdateAttributeIfIsolatedWorldAndInDocument(
const char element[],
const AttributeModificationParams& params) {
if (!isConnected())
return;
V8DOMActivityLogger* activity_logger =
V8DOMActivityLogger::CurrentActivityLoggerIfIsolatedWorldForMainThread();
if (!activity_logger)
return;
Vector<String, 4> argv;
argv.push_back(element);
argv.push_back(params.name.ToString());
argv.push_back(params.old_value);
argv.push_back(params.new_value);
activity_logger->LogEvent("blinkSetAttribute", argv.size(), argv.data());
}
void Element::Trace(blink::Visitor* visitor) {
if (HasRareData())
visitor->TraceWithWrappers(GetElementRareData());
visitor->Trace(element_data_);
ContainerNode::Trace(visitor);
}
bool Element::HasPartName() const {
if (!RuntimeEnabledFeatures::CSSPartPseudoElementEnabled())
return false;
if (HasRareData()) {
if (auto* part_names = GetElementRareData()->PartNames()) {
return part_names->size() > 0;
}
}
return false;
}
const SpaceSplitString* Element::PartNames() const {
return RuntimeEnabledFeatures::CSSPartPseudoElementEnabled() && HasRareData()
? GetElementRareData()->PartNames()
: nullptr;
}
bool Element::HasPartNamesMap() const {
const NamesMap* names_map = PartNamesMap();
return names_map && names_map->size() > 0;
}
const NamesMap* Element::PartNamesMap() const {
return RuntimeEnabledFeatures::CSSPartPseudoElementEnabled() && HasRareData()
? GetElementRareData()->PartNamesMap()
: nullptr;
}
} // namespace blink
|