The headless browser for AI agents and web scraping
render: real-world CSS rendering parity
SGavrl2652ee64a448
diff --git a/Cargo.lock b/Cargo.lockindex bdff8cec..e42ad3e8 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -229,7 +229,7 @@ version = "0.71.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5f58bf3d7db68cfbac37cfc485a8d711e87e064c3d0fe0435b92f7a407f9d6b3"dependencies = [- "bitflags 2.13.0",+ "bitflags","cexpr","clang-sys","itertools",@@ -238,7 +238,7 @@ dependencies = ["proc-macro2","quote","regex",- "rustc-hash",+ "rustc-hash 2.1.2","shlex 1.3.0","syn",]@@ -249,14 +249,14 @@ version = "0.72.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895"dependencies = [- "bitflags 2.13.0",+ "bitflags","cexpr","clang-sys","itertools","proc-macro2","quote","regex",- "rustc-hash",+ "rustc-hash 2.1.2","shlex 1.3.0","syn",]@@ -276,12 +276,6 @@ version = "0.8.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"-[[package]]-name = "bitflags"-version = "1.3.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"-[[package]]name = "bitflags"version = "2.13.0"@@ -345,7 +339,7 @@ version = "0.5.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2c5e60b8c8d282c86360cab651ded04ab0335a7b5390c8d34145cbeab8cacf5f"dependencies = [- "bitflags 2.13.0",+ "bitflags","btls-sys","foreign-types","libc",@@ -375,6 +369,20 @@ name = "bytemuck"version = "1.25.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c8efb64bd706a16a1bdde310ae86b351e4d21550d98d056f22f8a7f7a2183fec"+dependencies = [+ "bytemuck_derive",+]++[[package]]+name = "bytemuck_derive"+version = "1.10.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f9abbd1bc6865053c427f7198e6af43bfdedc55ab791faed4fbd361d789575ff"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+][[package]]name = "byteorder"@@ -573,6 +581,29 @@ dependencies = ["libm",]+[[package]]+name = "cosmic-text"+version = "0.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "59fd57d82eb4bfe7ffa9b1cec0c05e2fd378155b47f255a67983cb4afe0e80c2"+dependencies = [+ "bitflags",+ "fontdb 0.16.2",+ "log",+ "rangemap",+ "rayon",+ "rustc-hash 1.1.0",+ "rustybuzz 0.14.1",+ "self_cell",+ "swash",+ "sys-locale",+ "ttf-parser 0.21.1",+ "unicode-bidi",+ "unicode-linebreak",+ "unicode-script",+ "unicode-segmentation",+]+[[package]]name = "cpufeatures"version = "0.2.17"@@ -591,6 +622,31 @@ dependencies = ["cfg-if",]+[[package]]+name = "crossbeam-deque"+version = "0.8.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9dd111b7b7f7d55b72c0a6ae361660ee5853c9af73f70c3c2ef6858b950e2e51"+dependencies = [+ "crossbeam-epoch",+ "crossbeam-utils",+]++[[package]]+name = "crossbeam-epoch"+version = "0.9.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e"+dependencies = [+ "crossbeam-utils",+]++[[package]]+name = "crossbeam-utils"+version = "0.8.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28"+[[package]]name = "crypto-common"version = "0.1.7"@@ -915,6 +971,28 @@ version = "0.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"+[[package]]+name = "font-types"+version = "0.7.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b3971f9a5ca983419cdc386941ba3b9e1feba01a0ab888adf78739feb2798492"+dependencies = [+ "bytemuck",+]++[[package]]+name = "fontdb"+version = "0.16.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b0299020c3ef3f60f526a4f64ab4a3d4ce116b1acbf24cdd22da0068e5d81dc3"+dependencies = [+ "log",+ "memmap2",+ "slotmap",+ "tinyvec",+ "ttf-parser 0.20.0",+]+[[package]]name = "fontdb"version = "0.23.0"@@ -924,7 +1002,7 @@ dependencies = ["log","slotmap","tinyvec",- "ttf-parser",+ "ttf-parser 0.25.1",][[package]]@@ -1170,9 +1248,9 @@ checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280"[[package]]name = "grid"-version = "0.15.0"+version = "1.0.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "36119f3a540b086b4e436bb2b588cf98a68863470e0e880f4d0842f112a3183a"+checksum = "b40ca9252762c466af32d0b1002e91e4e1bc5398f77455e55474deb466355ff5"[[package]]name = "gzip-header"@@ -1482,16 +1560,18 @@ checksum = "cd62e6b5e86ea8eeeb8db1de02880a6abc01a397b2ebb64b5d74ac255318f5cb"[[package]]name = "image"-version = "0.24.9"+version = "0.25.10"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5690139d2f55868e080017335e4b94cb7414274c74f1669c84fb5feba2c9f69d"+checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104"dependencies = ["bytemuck",- "byteorder",- "color_quant",- "jpeg-decoder",+ "byteorder-lite",+ "image-webp",+ "moxcms","num-traits",- "png 0.17.16",+ "png",+ "zune-core",+ "zune-jpeg",][[package]]@@ -1569,12 +1649,6 @@ dependencies = ["libc",]-[[package]]-name = "jpeg-decoder"-version = "0.3.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "00810f1d8b74be64b13dbf3db89ac67740615d6c891f0e7b6179326533011a07"-[[package]]name = "js-sys"version = "0.3.102"@@ -1726,6 +1800,15 @@ version = "2.8.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "88904434abc2901f197fe8cc55f0445e7ded921dba5911dad2e2b39b48e663c4"+[[package]]+name = "memmap2"+version = "0.9.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d1219ed1b7f229ee7104d281dd01d6802fe28bb6e95d292942c4daacdeb798c0"+dependencies = [+ "libc",+]+[[package]]name = "minimal-lexical"version = "0.2.1"@@ -1753,6 +1836,16 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "moxcms"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b"+dependencies = [+ "num-traits",+ "pxfm",+]+[[package]]name = "new_debug_unreachable"version = "1.0.6"@@ -1972,6 +2065,7 @@ version = "0.1.0"dependencies = ["ab_glyph","base64",+ "cosmic-text","cssparser","image","obscura-dom",@@ -2024,7 +2118,7 @@ version = "0.25.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "36820e9051aca1014ddc75770aab4d68bc1e9e632f0f5627c4086bc216fb583b"dependencies = [- "ttf-parser",+ "ttf-parser 0.25.1",][[package]]@@ -2172,26 +2266,13 @@ version = "0.3.33"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e"-[[package]]-name = "png"-version = "0.17.16"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526"-dependencies = [- "bitflags 1.3.2",- "crc32fast",- "fdeflate",- "flate2",- "miniz_oxide",-]-[[package]]name = "png"version = "0.18.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"dependencies = [- "bitflags 2.13.0",+ "bitflags","crc32fast","fdeflate","flate2",@@ -2291,6 +2372,12 @@ dependencies = ["unicode-ident",]+[[package]]+name = "pxfm"+version = "0.1.29"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e0c5ccf5294c6ccd63a74f1565028353830a9c2f5eb0c682c355c471726a6e3f"+[[package]]name = "quick-error"version = "2.0.1"@@ -2308,7 +2395,7 @@ dependencies = ["pin-project-lite","quinn-proto","quinn-udp",- "rustc-hash",+ "rustc-hash 2.1.2","rustls","socket2","thiserror 2.0.18",@@ -2328,7 +2415,7 @@ dependencies = ["lru-slab","rand 0.9.4","ring",- "rustc-hash",+ "rustc-hash 2.1.2","rustls","rustls-pki-types","slab",@@ -2426,6 +2513,32 @@ dependencies = ["getrandom 0.3.4",]+[[package]]+name = "rangemap"+version = "1.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "973443cf09a9c8656b574a866ab68dfa19f0867d0340648c7d2f6a71b8a8ea68"++[[package]]+name = "rayon"+version = "1.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d"+dependencies = [+ "either",+ "rayon-core",+]++[[package]]+name = "rayon-core"+version = "1.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"+dependencies = [+ "crossbeam-deque",+ "crossbeam-utils",+]+[[package]]name = "rcgen"version = "0.13.2"@@ -2439,13 +2552,23 @@ dependencies = ["yasna",]+[[package]]+name = "read-fonts"+version = "0.22.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "69aacb76b5c29acfb7f90155d39759a29496aebb49395830e928a9703d2eec2f"+dependencies = [+ "bytemuck",+ "font-types",+]+[[package]]name = "redox_syscall"version = "0.5.18"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"dependencies = [- "bitflags 2.13.0",+ "bitflags",][[package]]@@ -2564,6 +2687,12 @@ dependencies = ["memchr",]+[[package]]+name = "rustc-hash"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2"+[[package]]name = "rustc-hash"version = "2.1.2"@@ -2576,7 +2705,7 @@ version = "0.38.44"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154"dependencies = [- "bitflags 2.13.0",+ "bitflags","errno","libc","linux-raw-sys 0.4.15",@@ -2589,7 +2718,7 @@ version = "1.1.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"dependencies = [- "bitflags 2.13.0",+ "bitflags","errno","libc","linux-raw-sys 0.12.1",@@ -2638,20 +2767,37 @@ version = "1.0.22"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"+[[package]]+name = "rustybuzz"+version = "0.14.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cfb9cf8877777222e4a3bc7eb247e398b56baba500c38c1c46842431adc8b55c"+dependencies = [+ "bitflags",+ "bytemuck",+ "libm",+ "smallvec",+ "ttf-parser 0.21.1",+ "unicode-bidi-mirroring 0.2.0",+ "unicode-ccc 0.2.0",+ "unicode-properties",+ "unicode-script",+]+[[package]]name = "rustybuzz"version = "0.20.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "fd3c7c96f8a08ee34eff8857b11b49b07d71d1c3f4e88f8a88d4c9e9f90b1702"dependencies = [- "bitflags 2.13.0",+ "bitflags","bytemuck","core_maths","log","smallvec",- "ttf-parser",- "unicode-bidi-mirroring",- "unicode-ccc",+ "ttf-parser 0.25.1",+ "unicode-bidi-mirroring 0.4.0",+ "unicode-ccc 0.4.0","unicode-properties","unicode-script",]@@ -2674,7 +2820,7 @@ version = "0.26.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "fd568a4c9bb598e291a08244a5c1f5a8a6650bee243b5b0f8dbb3d9cc1d87fe8"dependencies = [- "bitflags 2.13.0",+ "bitflags","cssparser","derive_more","fxhash",@@ -2687,6 +2833,12 @@ dependencies = ["smallvec",]+[[package]]+name = "self_cell"+version = "1.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b12e76d157a900eb52e81bc6e9f3069344290341720e9178cde2407113ac8d89"+[[package]]name = "semver"version = "1.0.28"@@ -2846,6 +2998,16 @@ version = "1.0.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8ee5873ec9cce0195efcb7a4e9507a04cd49aec9c83d0389df45b1ef7ba2e649"+[[package]]+name = "skrifa"+version = "0.22.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8e1c44ad1f6c5bdd4eefed8326711b7dbda9ea45dfd36068c427d332aa382cbe"+dependencies = [+ "bytemuck",+ "read-fonts",+]+[[package]]name = "slab"version = "0.4.12"@@ -2888,7 +3050,7 @@ dependencies = ["data-encoding","debugid","if_chain",- "rustc-hash",+ "rustc-hash 2.1.2","serde","serde_json","unicode-id-start",@@ -2990,6 +3152,17 @@ dependencies = ["siphasher",]+[[package]]+name = "swash"+version = "0.1.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cbd59f3f359ddd2c95af4758c18270eddd9c730dde98598023cdabff472c2ca2"+dependencies = [+ "skrifa",+ "yazi",+ "zeno",+]+[[package]]name = "syn"version = "2.0.117"@@ -3021,6 +3194,15 @@ dependencies = ["syn",]+[[package]]+name = "sys-locale"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8eab9a99a024a169fe8a903cf9d4a3b3601109bcc13bd9e3c6fff259138626c4"+dependencies = [+ "libc",+]+[[package]]name = "sys_traits"version = "0.1.28"@@ -3043,9 +3225,9 @@ dependencies = [[[package]]name = "taffy"-version = "0.7.7"+version = "0.12.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ab4f4d046dd956a47a7e1a2947083d7ac3e6aa3cfaaead36173ceaa5ab11878c"+checksum = "73afc801dd6bd47529eaa7c7e90557f107527d1b7c9c7ed7d7803c7b8d0c357f"dependencies = ["arrayvec","grid",@@ -3162,7 +3344,7 @@ dependencies = ["bytemuck","cfg-if","log",- "png 0.18.1",+ "png","tiny-skia-path",]@@ -3309,7 +3491,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"dependencies = ["async-compression",- "bitflags 2.13.0",+ "bitflags","bytes","futures-core","futures-util",@@ -3404,6 +3586,18 @@ version = "0.2.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"+[[package]]+name = "ttf-parser"+version = "0.20.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "17f77d76d837a7830fe1d4f12b7b4ba4192c1888001c7164257e4bc6d21d96b4"++[[package]]+name = "ttf-parser"+version = "0.21.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2c591d83f69777866b9126b24c6dd9a18351f177e49d625920d19f989fd31cf8"+[[package]]name = "ttf-parser"version = "0.25.1"@@ -3462,12 +3656,24 @@ version = "0.3.18"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5"+[[package]]+name = "unicode-bidi-mirroring"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "23cb788ffebc92c5948d0e997106233eeb1d8b9512f93f41651f52b6c5f5af86"+[[package]]name = "unicode-bidi-mirroring"version = "0.4.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5dfa6e8c60bb66d49db113e0125ee8711b7647b5579dc7f5f19c42357ed039fe"+[[package]]+name = "unicode-ccc"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1df77b101bcc4ea3d78dafc5ad7e4f58ceffe0b2b16bf446aeb50b6cb4157656"+[[package]]name = "unicode-ccc"version = "0.4.0"@@ -3486,6 +3692,12 @@ version = "1.0.24"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"+[[package]]+name = "unicode-linebreak"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3b09c83c3c29d37506a3e260c08c03743a6bb66a9cd432c6934ab501a190571f"+[[package]]name = "unicode-properties"version = "0.1.4"@@ -3498,6 +3710,12 @@ version = "0.5.8"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "383ad40bb927465ec0ce7720e033cb4ca06912855fc35db31b5755d0de75b1ee"+[[package]]+name = "unicode-segmentation"+version = "1.13.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"+[[package]]name = "unicode-vo"version = "0.1.0"@@ -3563,19 +3781,19 @@ dependencies = ["base64","data-url","flate2",- "fontdb",+ "fontdb 0.23.0","imagesize","kurbo","log","pico-args","roxmltree",- "rustybuzz",+ "rustybuzz 0.20.1","simplecss","siphasher","strict-num","svgtypes","tiny-skia-path",- "ttf-parser",+ "ttf-parser 0.25.1","unicode-bidi","unicode-script","unicode-vo",@@ -3618,7 +3836,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "33995a1fee055ff743281cde33a41f0d618ee0bdbe8bdf6859e11864499c2595"dependencies = ["bindgen 0.71.1",- "bitflags 2.13.0",+ "bitflags","fslock","gzip-header","home",@@ -3771,7 +3989,7 @@ version = "0.244.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe"dependencies = [- "bitflags 2.13.0",+ "bitflags","hashbrown 0.15.5","indexmap","semver",@@ -4105,7 +4323,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2"dependencies = ["anyhow",- "bitflags 2.13.0",+ "bitflags","indexmap","log","serde",@@ -4241,6 +4459,12 @@ dependencies = ["time",]+[[package]]+name = "yazi"+version = "0.1.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c94451ac9513335b5e23d7a8a2b61a7102398b8cca5160829d313e84c9d98be1"+[[package]]name = "yoke"version = "0.8.3"@@ -4264,6 +4488,12 @@ dependencies = ["synstructure",]+[[package]]+name = "zeno"+version = "0.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dd15f8e0dbb966fd9245e7498c7e9e5055d9e5c8b676b95bd67091cd11a1e697"+[[package]]name = "zerocopy"version = "0.8.52"diff --git a/Cargo.toml b/Cargo.tomlindex 5ce079d9..02be25b9 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -33,7 +33,7 @@ selectors = "0.26"servo_arc = "0.4"cssparser = "0.34"# Layout engine for the optional render layer (obscura-render). Pure Rust.-taffy = "0.7"+taffy = "0.12"# CPU-only pure-Rust 2D rasterizer for the render layer's paint step.tiny-skia = "0.12"# Pure-Rust glyph rasterizer for the render layer's text step.diff --git a/crates/obscura-cdp/src/domains/page.rs b/crates/obscura-cdp/src/domains/page.rsindex d92320fb..05cf2e50 100644--- a/crates/obscura-cdp/src/domains/page.rs+++ b/crates/obscura-cdp/src/domains/page.rs@@ -655,9 +655,10 @@ mod tests {!err.contains("Unknown Page method"),"captureScreenshot must NOT fall through to the catch-all: {err}");+ #[cfg(not(feature = "render"))]assert!(- err.contains("not supported by Obscura"),- "error must clearly state screenshot is unsupported: {err}"+ err.contains("requires a build with the render feature"),+ "error must clearly state screenshot needs the render feature: {err}");// Same for the MHTML snapshot sibling method.let err2 = handle("captureSnapshot", &json!({}), &mut ctx, &None)diff --git a/crates/obscura-cli/src/main.rs b/crates/obscura-cli/src/main.rsindex f7660452..ea32bf8a 100644--- a/crates/obscura-cli/src/main.rs+++ b/crates/obscura-cli/src/main.rs@@ -659,7 +659,11 @@ async fn run_fetch(#[cfg(feature = "render")]{// Default CSS-pixel viewport, matching the engine's innerWidth/Height.- match page.screenshot((1280.0, 720.0)) {+ // OBSCURA_SHOT_W / OBSCURA_SHOT_H override it (e.g. a tall viewport to+ // capture below-the-fold content in one shot).+ let shot_w = std::env::var("OBSCURA_SHOT_W").ok().and_then(|v| v.parse::<f32>().ok()).unwrap_or(1280.0);+ let shot_h = std::env::var("OBSCURA_SHOT_H").ok().and_then(|v| v.parse::<f32>().ok()).unwrap_or(720.0);+ match page.screenshot((shot_w, shot_h)) {Some(bytes) => std::fs::write(path, &bytes)?,None => anyhow::bail!("screenshot failed: page has no DOM to render"),}@@ -1819,6 +1823,7 @@ mod tests {quiet: true,output: None,storage_dir: None,+ screenshot: None,});assert!(is_quiet_command(&cmd));}diff --git a/crates/obscura-dom/src/selector.rs b/crates/obscura-dom/src/selector.rsindex f611e80d..ec6cf65e 100644--- a/crates/obscura-dom/src/selector.rs+++ b/crates/obscura-dom/src/selector.rs@@ -187,6 +187,17 @@ impl<'i> parser::Parser<'i> for ObscuraSelectorParser {true}+ // Allow `:is()` and `:where()`. The selectors crate gates these on this hook+ // (default false), so without it every `:where(...)`/`:is(...)` selector+ // failed to parse and was dropped, discarding those rules from both the+ // render cascade and querySelectorAll. Tailwind's preflight and most modern+ // resets wrap their rules in `:where(...)` for zero specificity, so this+ // blanked large parts of many sites. Matching (Component::Is/Where) is built+ // into the crate, so enabling parsing is sufficient.+ fn parse_is_and_where(&self) -> bool {+ true+ }+fn parse_non_ts_pseudo_class(&self,_location: cssparser::SourceLocation,diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.jsindex d4839605..b15060db 100644--- a/crates/obscura-js/js/bootstrap.js+++ b/crates/obscura-js/js/bootstrap.js@@ -4527,8 +4527,12 @@ if (typeof TextDecoder === 'undefined') {globalThis.matchMedia = _markNative(function matchMedia(q) {var s = (q || '').toLowerCase().replace(/\s+/g, '');var matches = false;- if (s.includes('prefers-color-scheme:light')) matches = false;- else if (s.includes('prefers-color-scheme:dark')) matches = true;+ // Match headless Chromium's default: light color scheme. Reporting dark+ // here made every JS-driven site (mdBook, docs, apps) switch itself into a+ // dark theme, rendering nothing like a normal headless-Chrome screenshot.+ if (s.includes('prefers-color-scheme:dark')) matches = false;+ else if (s.includes('prefers-color-scheme:light')) matches = true;+ else if (s.includes('prefers-color-scheme:no-preference')) matches = false;else if (s.includes('prefers-reduced-motion:no-preference')) matches = true;else if (s.includes('prefers-reduced-motion:reduce')) matches = false;else if (s.includes('any-pointer:fine')) matches = true;diff --git a/crates/obscura-render/Cargo.toml b/crates/obscura-render/Cargo.tomlindex 76f50118..256feb5e 100644--- a/crates/obscura-render/Cargo.toml+++ b/crates/obscura-render/Cargo.toml@@ -8,16 +8,21 @@ description = "Optional scoped render layer for Obscura: layout (taffy) and, wit[features]default = []-# Rasterize the laid-out tree to a pixmap (tiny-skia) with text (ab_glyph) and images.+# Rasterize the laid-out tree to a pixmap (tiny-skia) with text (cosmic-text+# shaping + line breaking, ab_glyph fallback) and images.# Off by default; the layout core (getBoundingClientRect etc.) works without it.-paint = ["dep:tiny-skia", "dep:ab_glyph", "dep:image", "dep:ureq", "dep:base64", "dep:resvg", "dep:usvg", "dep:url"]+paint = ["dep:tiny-skia", "dep:ab_glyph", "dep:cosmic-text", "dep:image", "dep:ureq", "dep:base64", "dep:resvg", "dep:usvg", "dep:url"][dependencies]taffy = { workspace = true }obscura-dom = { workspace = true }tiny-skia = { workspace = true, optional = true }ab_glyph = { workspace = true, optional = true }-image = { version = "0.24", default-features = false, features = ["jpeg", "png", "webp"], optional = true }+# Real inline text layout: HarfBuzz-class shaping (rustybuzz) + UAX#14 line+# breaking, the same algorithms browsers use. Built with only our embedded+# fonts (no system-font scan) so layout stays deterministic across hosts.+cosmic-text = { version = "=0.12.1", default-features = false, features = ["std", "swash"], optional = true }+image = { version = "0.25", default-features = false, features = ["jpeg", "png", "webp"], optional = true }ureq = { version = "2.9", default-features = false, features = ["tls"], optional = true }base64 = { workspace = true, optional = true }# SVG rasterization for <img src="*.svg">, inline <svg>, and background-imagediff --git a/crates/obscura-render/assets/dejavu-sans-bold.ttf b/crates/obscura-render/assets/dejavu-sans-bold.ttfnew file mode 100644index 00000000..426812b9Binary files /dev/null and b/crates/obscura-render/assets/dejavu-sans-bold.ttf differdiff --git a/crates/obscura-render/assets/dejavu-sans-boldoblique.ttf b/crates/obscura-render/assets/dejavu-sans-boldoblique.ttfnew file mode 100644index 00000000..b8886cb5Binary files /dev/null and b/crates/obscura-render/assets/dejavu-sans-boldoblique.ttf differdiff --git a/crates/obscura-render/assets/dejavu-sans-oblique.ttf b/crates/obscura-render/assets/dejavu-sans-oblique.ttfnew file mode 100644index 00000000..300ea68bBinary files /dev/null and b/crates/obscura-render/assets/dejavu-sans-oblique.ttf differdiff --git a/crates/obscura-render/src/css.rs b/crates/obscura-render/src/css.rsindex 23b7d04c..ad84253e 100644--- a/crates/obscura-render/src/css.rs+++ b/crates/obscura-render/src/css.rs@@ -27,6 +27,17 @@ pub struct Stylesheet {by_class: HashMap<String, Vec<usize>>,by_local: HashMap<String, Vec<usize>>,universal: Vec<usize>,+ /// `sel::before{content:"..."}` / `sel::after{...}` rules with a plain+ /// string-literal `content`, matched separately from the main cascade:+ /// our selector engine has no pseudo-element matching machinery, but a+ /// `::before`/`::after` selector's *base* (everything before the+ /// pseudo-element) is an ordinary selector we can already compile and+ /// match. Extremely common on Wikipedia (`.hlist`/`.cslist` render as+ /// comma-separated lists purely via `li::before{content:", "}`); without+ /// this, adjacent list items with no real whitespace between them in the+ /// DOM run together with no separator at all.+ before_content: Vec<(CompiledSelector, String)>,+ after_content: Vec<(CompiledSelector, String)>,}impl Stylesheet {@@ -39,10 +50,25 @@ impl Stylesheet {by_class: HashMap::new(),by_local: HashMap::new(),universal: Vec::new(),+ before_content: Vec::new(),+ after_content: Vec::new(),};let mut order = 0usize;for src in sources {for (selector, decls) in parse_stylesheet(src) {+ let sel_trim = selector.trim();+ if let Some(base) = strip_pseudo_element(sel_trim, "before") {+ if let (Some(content), Some(sel)) = (extract_string_content(&decls), tree.compile_rule_selector(base)) {+ sheet.before_content.push((sel, content));+ }+ continue;+ }+ if let Some(base) = strip_pseudo_element(sel_trim, "after") {+ if let (Some(content), Some(sel)) = (extract_string_content(&decls), tree.compile_rule_selector(base)) {+ sheet.after_content.push((sel, content));+ }+ continue;+ }let Some(sel) = tree.compile_rule_selector(&selector) else { continue };let idx = sheet.rules.len();match sel.key() {@@ -58,6 +84,28 @@ impl Stylesheet {sheet}+ /// The literal text (if any) that `::before`/`::after` rules inject for+ /// `nid`, as `(before, after)`. Last matching rule wins, approximating+ /// cascade order without tracking specificity for this small side table.+ pub fn pseudo_content(&self, tree: &DomTree, matcher: &mut Matcher, nid: NodeId) -> (Option<String>, Option<String>) {+ if self.before_content.is_empty() && self.after_content.is_empty() {+ return (None, None);+ }+ let mut before = None;+ for (sel, content) in &self.before_content {+ if matcher.matches(tree, nid, sel) {+ before = Some(content.clone());+ }+ }+ let mut after = None;+ for (sel, content) in &self.after_content {+ if matcher.matches(tree, nid, sel) {+ after = Some(content.clone());+ }+ }+ (before, after)+ }+pub fn is_empty(&self) -> bool {self.rules.is_empty()}@@ -70,6 +118,10 @@ impl Stylesheet {/// Apply every author rule that matches `nid` to `style`, in cascade order/// (ascending specificity, then source order, so the winner is applied last)./// `id`, `classes`, and `local` are the element's precomputed keys.+ /// `parent_props` is the element's inherited custom-property map. Returns+ /// `Some(map)` (parent + this element's own `--x` declarations) when this+ /// element declares any custom properties, so the caller can thread the+ /// richer map to descendants; `None` means "reuse the parent's map".pub fn apply(&self,tree: &DomTree,@@ -79,7 +131,8 @@ impl Stylesheet {classes: &[String],local: &str,style: &mut LayoutStyle,- ) {+ parent_props: &HashMap<String, String>,+ ) -> Option<HashMap<String, String>> {// (specificity, order, rule index) for each matching rule.let mut matched: Vec<(u32, usize, usize)> = Vec::new();let mut consider = |bucket: Option<&Vec<usize>>, matched: &mut Vec<(u32, usize, usize)>| {@@ -105,18 +158,185 @@ impl Stylesheet {}if matched.is_empty() {- return;+ return None;}matched.sort_unstable_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1)));++ // Pass 1: collect this element's own custom properties (`--x: value`),+ // in cascade order (last wins), layered over the inherited map. Custom+ // properties cascade fully before any `var()` is substituted.+ let mut own: Vec<(String, String)> = Vec::new();+ for &(_, _, i) in &matched {+ for decl in crate::style::split_declarations(&self.rules[i].decls) {+ if let Some((name, val)) = decl.split_once(':') {+ let name = name.trim();+ if name.starts_with("--") && name.len() > 2 {+ own.push((name.to_string(), val.trim().to_string()));+ }+ }+ }+ }+ let effective = if own.is_empty() {+ None+ } else {+ let mut m = parent_props.clone();+ for (k, v) in own {+ m.insert(k, v);+ }+ Some(m)+ };+ let props = effective.as_ref().unwrap_or(parent_props);++ // Pass 2: apply normal declarations with `var()` substituted against+ // the resolved custom-property map.for (_, _, i) in matched {- crate::style::apply_inline(style, &self.rules[i].decls);+ let expanded = substitute_vars(&self.rules[i].decls, props, 0);+ crate::style::apply_inline(style, &expanded);+ }+ effective+ }+}++/// Substitute every `var(--name, fallback?)` in `input` with its resolved+/// value from `props` (recursively, so a token that itself references another+/// token resolves; a depth cap guards against reference cycles). A missing+/// variable with no fallback expands to empty, which makes the declaration+/// invalid and dropped, exactly as CSS specifies.+pub(crate) fn substitute_vars(input: &str, props: &HashMap<String, String>, depth: u8) -> String {+ if depth > 16 || !input.contains("var(") {+ return input.to_string();+ }+ let mut out = String::new();+ let mut rest = input;+ while let Some(pos) = rest.find("var(") {+ out.push_str(&rest[..pos]);+ let after = &rest[pos + 4..];+ // Matching close paren, respecting nesting.+ let mut d = 1i32;+ let mut end = None;+ for (i, ch) in after.char_indices() {+ match ch {+ '(' => d += 1,+ ')' => {+ d -= 1;+ if d == 0 {+ end = Some(i);+ break;+ }+ }+ _ => {}+ }+ }+ let Some(end) = end else {+ out.push_str(&rest[pos..]);+ return out;+ };+ let inner = &after[..end];+ let (name, fallback) = match inner.split_once(',') {+ Some((n, f)) => (n.trim(), Some(f.trim())),+ None => (inner.trim(), None),+ };+ let replacement = match props.get(name) {+ Some(v) => substitute_vars(v, props, depth + 1),+ None => fallback.map(|f| substitute_vars(f, props, depth + 1)).unwrap_or_default(),+ };+ out.push_str(&replacement);+ rest = &after[end + 1..];+ }+ out.push_str(rest);+ out+}++/// If `selector`'s rightmost compound is the pseudo-element `which`+/// (`"before"` or `"after"`, matching either the modern `::` or legacy `:`+/// form), return everything before it, trimmed. Only a trailing+/// pseudo-element is handled: `li::before` strips to `li`, but a selector+/// that uses `::before` as anything other than the final component (not+/// valid CSS in the first place) is left alone.+fn strip_pseudo_element<'a>(selector: &'a str, which: &str) -> Option<&'a str> {+ for prefix in ["::", ":"] {+ let suffix = format!("{prefix}{which}");+ if let Some(base) = selector.strip_suffix(&suffix) {+ if !base.is_empty() {+ return Some(base.trim());+ }+ }+ }+ None+}++/// Pull a plain quoted-string `content` value out of a declaration list+/// (`content: ", "` -> `Some(", ")`). Deliberately narrow: real `content`+/// also accepts `counter()`, `attr()`, `url()` and concatenations of these,+/// none of which apply here (no counters or `attr()`-driven content on the+/// pages this targets), so anything other than a single quoted string is+/// left unhandled rather than guessed at. When `content` is declared more+/// than once (the `content: X; content: X / Y` accessible-alt-text pattern),+/// the last one wins, matching normal CSS declaration order.+fn extract_string_content(decls: &str) -> Option<String> {+ let mut result = None;+ let mut search_from = 0;+ while let Some(rel_idx) = decls[search_from..].find("content") {+ let idx = search_from + rel_idx;+ search_from = idx + "content".len();+ let after = decls[search_from..].trim_start();+ let Some(after_colon) = after.strip_prefix(':') else { continue };+ let after_colon = after_colon.trim_start();+ let Some(quote) = after_colon.chars().next() else { continue };+ if quote != '"' && quote != '\'' {+ continue;+ }+ let rest = &after_colon[quote.len_utf8()..];+ let Some(end) = rest.find(quote) else { continue };+ result = Some(unescape_css_string(&rest[..end]));+ }+ result+}++/// Decode CSS string escapes: `\` followed by 1-6 hex digits is a Unicode+/// code point (`\200B` -> U+200B ZERO WIDTH SPACE, ubiquitous in generated+/// `content` for accessible section-edit-link brackets and similar), with a+/// single trailing whitespace character consumed as the escape's own+/// terminator per the CSS spec rather than treated as literal content;+/// anything else after a backslash (`\"`, `\\`) is a literal escaped+/// character. Without this, a hex escape prints as its own literal digits.+fn unescape_css_string(s: &str) -> String {+ let mut out = String::new();+ let mut chars = s.chars().peekable();+ while let Some(c) = chars.next() {+ if c != '\\' {+ out.push(c);+ continue;+ }+ let mut hex = String::new();+ while hex.len() < 6 {+ match chars.peek() {+ Some(h) if h.is_ascii_hexdigit() => {+ hex.push(*h);+ chars.next();+ }+ _ => break,+ }+ }+ if !hex.is_empty() {+ if matches!(chars.peek(), Some(next) if next.is_whitespace()) {+ chars.next();+ }+ if let Some(ch) = u32::from_str_radix(&hex, 16).ok().and_then(char::from_u32) {+ out.push(ch);+ continue;+ }+ }+ if let Some(next) = chars.next() {+ out.push(next);}}+ out}/// Split a stylesheet into `(selector, declarations)` rules. Handles nested/// braces, `/* comments */`, and the at-rules that carry ordinary rules inside-/// (`@media`, `@supports`); other at-rules (`@font-face`, `@keyframes`, ...) are+/// (`@media`, `@supports`, `@layer`); other at-rules (`@font-face`, `@keyframes`, ...) are/// skipped since they do not contribute layout-relevant declarations here.pub fn parse_stylesheet(css: &str) -> Vec<(String, String)> {let mut rules = Vec::new();@@ -145,6 +365,12 @@ pub fn parse_stylesheet(css: &str) -> Vec<(String, String)> {current_decls.push(c);}block_depth += 1;+ } else if c == '}' && block_depth == 0 {+ // Stray top-level close brace (unbalanced author CSS; remoteok.com+ // ships one mid-sheet). Browsers error-recover and keep parsing;+ // without this block_depth goes negative and the state machine+ // inverts, scrambling and losing every rule in the rest of the sheet.+ current_selector.clear();} else if c == '}' {block_depth -= 1;if block_depth == 0 {@@ -153,18 +379,23 @@ pub fn parse_stylesheet(css: &str) -> Vec<(String, String)> {if let Some(at) = sel.strip_prefix('@') {flush_at_rule(at, sel, decls, &mut rules);} else {- for s in sel.split(',') {- let s = s.trim();- if !s.is_empty() {- rules.push((s.to_string(), decls.to_string()));- }- }+ // The body may contain nested rules (CSS Nesting, ubiquitous+ // in Tailwind v4 / modern frameworks: `.a{ &:hover{} .b{} }`).+ // Flatten them against this selector; denest also handles the+ // no-nesting case (just emits the rule's own declarations).+ denest(sel, decls, &mut rules);}current_selector.clear();current_decls.clear();} else {current_decls.push(c);}+ } else if c == ';' && block_depth == 0 {+ // A `;` at the top level terminates an at-statement that carries no+ // rules (`@layer a, b;`, `@import ...;`, `@charset ...;`). Discard+ // the buffered text so it cannot bleed into the next rule's selector+ // and take a real rule down with it.+ current_selector.clear();} else if block_depth > 0 {current_decls.push(c);} else {@@ -183,6 +414,33 @@ fn flush_at_rule(at: &str, sel: &str, inner: &str, rules: &mut Vec<(String, Stri}} else if at.starts_with("supports") {rules.extend(parse_stylesheet(inner));+ } else if at.starts_with("property") {+ // `@property --x { syntax:..; initial-value: V }` declares a custom+ // property and its default. Register the initial-value as a `:root`+ // declaration so `var(--x)` resolves when nothing else sets it. Tailwind+ // v4 and modern frameworks define theme tokens this way; dropping them+ // left those `var()`s (page/section backgrounds, colors) unresolved.+ let name = at["property".len()..].trim();+ if name.starts_with("--") {+ for decl in inner.split(';') {+ if let Some((k, v)) = decl.split_once(':') {+ if k.trim().eq_ignore_ascii_case("initial-value") && !v.trim().is_empty() {+ rules.push((":root".to_string(), format!("{}: {}", name, v.trim())));+ }+ }+ }+ }+ } else if at.starts_with("layer") {+ // Cascade layers: `@layer name { ... }` wraps ordinary rules. We do not+ // model layer priority (real CSS ranks unlayered above layered and+ // later layers above earlier); just flatten the body in source order so+ // the (specificity, source-order) cascade applies it. Tailwind/UnoCSS,+ // Nuxt UI and similar wrap nearly all their CSS, including the `:root`+ // design tokens and background/color utilities, in `@layer`; dropping it+ // left whole pages unstyled (white backgrounds, collapsed layout). The+ // `@layer a, b;` ordering-statement form has no block and is discarded+ // by parse_stylesheet's top-level `;` handling.+ rules.extend(parse_stylesheet(inner));}// Other at-rules (@font-face, @keyframes, @import, ...) carry no// layout-relevant rules for us, so drop them.@@ -195,12 +453,40 @@ fn flush_at_rule(at: &str, sel: &str, inner: &str, rules: &mut Vec<(String, Stri/// strips whitespace before scanning: CSS gives no semantic meaning to spaces/// inside `(feature: value)`, so it's safe to discard them wholesale rather/// than special-case every formatting variant a site might use.-fn media_query_applies(query: &str) -> bool {+pub(crate) fn media_query_applies(query: &str) -> bool {const VIEWPORT_W: f32 = 1280.0;if query.contains("print") {return false;}- let compact: String = query.chars().filter(|c| !c.is_whitespace()).collect();+ let compact: String = query.chars().filter(|c| !c.is_whitespace()).flat_map(|c| c.to_lowercase()).collect();++ // A `not all` / `not all and (...)` query is a browser-targeting hack (most+ // commonly the Safari-only flex-gap fallback `@media not all and+ // (min-resolution:.001dpcm)`, which flips containers from flex to grid); it+ // does not apply in a Chromium-like context.+ if compact.starts_with("notall") {+ return false;+ }++ // Color-scheme: we render the light (default) context. A site's+ // `@media (prefers-color-scheme: dark)` block must NOT apply on top of its+ // light defaults (that is what was leaking dark backgrounds, e.g. near+ // black inline <code>); a `:light` block should apply.+ if compact.contains("prefers-color-scheme:dark") {+ return false;+ }+ // Reduced-motion / high-contrast / inverted: default (no preference).+ if compact.contains("prefers-reduced-motion:reduce")+ || compact.contains("prefers-contrast:more")+ || compact.contains("prefers-contrast:less")+ || compact.contains("inverted-colors:inverted")+ || compact.contains("forced-colors:active")+ {+ return false;+ }++ // Width constraints, both `min-width:`/`max-width:` and the modern range+ // forms `width>=Npx` / `(Npx<=width)`.if let Some(px) = extract_px(&compact, "max-width:") {if VIEWPORT_W > px {return false;@@ -211,9 +497,232 @@ fn media_query_applies(query: &str) -> bool {return false;}}+ if let Some(px) = extract_px(&compact, "width<=") {+ if VIEWPORT_W > px {+ return false;+ }+ }+ if let Some(px) = extract_px(&compact, "width>=") {+ if VIEWPORT_W < px {+ return false;+ }+ }+ if let Some(px) = extract_px(&compact, "width>") {+ if VIEWPORT_W <= px {+ return false;+ }+ }+ if let Some(px) = extract_px(&compact, "width<") {+ if VIEWPORT_W >= px {+ return false;+ }+ }true}+/// Combine a nested selector `child` with its enclosing `parent` (CSS Nesting).+/// `&` in the child is replaced by the parent; a child with no `&` becomes a+/// descendant (`parent child`). Both may be comma lists, so the result is the+/// cartesian product. `parent` is None only at the stylesheet top level, where+/// the child is returned unchanged.+fn combine_selectors(parent: &str, child: &str) -> String {+ let pparts = split_selector_list(parent);+ let cparts = split_selector_list(child);+ let mut out: Vec<String> = Vec::new();+ for c in &cparts {+ let c = c.trim();+ if c.is_empty() {+ continue;+ }+ for p in &pparts {+ let p = p.trim();+ if c.contains('&') {+ out.push(c.replace('&', p));+ } else {+ out.push(format!("{} {}", p, c));+ }+ }+ }+ out.join(", ")+}++/// Flatten a rule body that may contain nested rules (CSS Nesting) into flat+/// `(selector, declarations)` pairs. The parser hands us the whole body of a+/// rule; here we separate its own declarations from nested `sel { ... }` blocks+/// (and nested `@media`/`@supports`/`@layer` at-rules, which keep the parent's+/// selector), emit `(sel, own-declarations)`, and recurse into each nested rule+/// with the combined selector. Without this, Tailwind v4 / modern-framework CSS+/// (which nests almost everything) loses the nested utility rules entirely.+fn denest(sel: &str, body: &str, rules: &mut Vec<(String, String)>) {+ let chars: Vec<char> = body.chars().collect();+ let n = chars.len();+ let mut i = 0;+ let mut seg = 0; // start of the current declaration / nested prelude+ let mut own = String::new();+ let mut quote: Option<char> = None;+ let mut comment = false;+ let mut paren = 0i32;+ while i < n {+ let c = chars[i];+ if comment {+ if c == '*' && chars.get(i + 1) == Some(&'/') {+ comment = false;+ i += 2;+ continue;+ }+ i += 1;+ continue;+ }+ if let Some(q) = quote {+ if c == q {+ quote = None;+ }+ i += 1;+ continue;+ }+ if c == '/' && chars.get(i + 1) == Some(&'*') {+ comment = true;+ i += 2;+ continue;+ }+ match c {+ '\'' | '"' => quote = Some(c),+ '(' => paren += 1,+ ')' => paren = (paren - 1).max(0),+ '{' if paren == 0 => {+ let prelude: String = chars[seg..i].iter().collect();+ // Find the matching close brace (quote/comment aware).+ let mut depth = 1;+ let mut j = i + 1;+ let (mut q2, mut cm2) = (None::<char>, false);+ while j < n && depth > 0 {+ let cj = chars[j];+ if cm2 {+ if cj == '*' && chars.get(j + 1) == Some(&'/') {+ cm2 = false;+ j += 2;+ continue;+ }+ } else if let Some(qq) = q2 {+ if cj == qq {+ q2 = None;+ }+ } else if cj == '/' && chars.get(j + 1) == Some(&'*') {+ cm2 = true;+ j += 2;+ continue;+ } else if cj == '\'' || cj == '"' {+ q2 = Some(cj);+ } else if cj == '{' {+ depth += 1;+ } else if cj == '}' {+ depth -= 1;+ }+ j += 1;+ }+ let inner: String = chars[i + 1..j.saturating_sub(1).max(i + 1)].iter().collect();+ let pre = prelude.trim();+ if let Some(at) = pre.strip_prefix('@') {+ // A nested at-rule keeps the enclosing selector for its body.+ if at.starts_with("media") {+ if media_query_applies(pre) {+ denest(sel, &inner, rules);+ }+ } else if at.starts_with("supports") || at.starts_with("layer") {+ denest(sel, &inner, rules);+ }+ } else if !pre.is_empty() {+ let full = combine_selectors(sel, pre);+ denest(&full, &inner, rules);+ }+ i = j;+ seg = i;+ continue;+ }+ ';' if paren == 0 => {+ let d: String = chars[seg..i].iter().collect();+ let d = d.trim();+ if !d.is_empty() {+ own.push_str(d);+ own.push(';');+ }+ i += 1;+ seg = i;+ continue;+ }+ _ => {}+ }+ i += 1;+ }+ let tail: String = chars[seg..].iter().collect();+ let tail = tail.trim();+ if !tail.is_empty() && !tail.contains('{') {+ own.push_str(tail);+ own.push(';');+ }+ if !own.trim().is_empty() {+ for s in split_selector_list(sel) {+ let s = s.trim();+ if !s.is_empty() {+ rules.push((s.to_string(), own.clone()));+ }+ }+ }+}++/// Split a CSS selector list at top-level commas only, leaving commas inside+/// `()` (e.g. `:is(a, b)`, `:not(.x, .y)`) and `[]` (`[attr="a,b"]`) and quoted+/// strings intact. A naive `split(',')` shatters those grouped selectors into+/// fragments that fail to compile, dropping the whole rule.+fn split_selector_list(sel: &str) -> Vec<String> {+ let mut out = Vec::new();+ let mut depth_paren = 0i32;+ let mut depth_brack = 0i32;+ let mut quote: Option<char> = None;+ let mut cur = String::new();+ let mut chars = sel.chars().peekable();+ while let Some(c) = chars.next() {+ match c {+ '\\' => {+ cur.push(c);+ if let Some(n) = chars.next() {+ cur.push(n);+ }+ }+ _ if quote == Some(c) => {+ quote = None;+ cur.push(c);+ }+ '"' | '\'' if quote.is_none() => {+ quote = Some(c);+ cur.push(c);+ }+ '(' if quote.is_none() => {+ depth_paren += 1;+ cur.push(c);+ }+ ')' if quote.is_none() => {+ depth_paren -= 1;+ cur.push(c);+ }+ '[' if quote.is_none() => {+ depth_brack += 1;+ cur.push(c);+ }+ ']' if quote.is_none() => {+ depth_brack -= 1;+ cur.push(c);+ }+ ',' if quote.is_none() && depth_paren == 0 && depth_brack == 0 => {+ out.push(std::mem::take(&mut cur));+ }+ _ => cur.push(c),+ }+ }+ out.push(cur);+ out+}+/// Read the number immediately following `prop` in `s`. Callers pass a/// whitespace-stripped `s`, so the first non-digit character always ends the/// number. Handles a bare px value (`750px`) and the extremely commondiff --git a/crates/obscura-render/src/dom.rs b/crates/obscura-render/src/dom.rsindex 3c928acf..3b39c65e 100644--- a/crates/obscura-render/src/dom.rs+++ b/crates/obscura-render/src/dom.rs@@ -47,6 +47,14 @@ pub struct DomLayout {/// of (box, word text) pairs rather than a single box, unlike every other/// node kind. Keyed by the text node's `NodeId`, in layout order.pub text_runs: HashMap<NodeId, Vec<(Rect, String)>>,+ /// Inline formatting contexts that were shaped by cosmic-text (see+ /// `inline`): a single leaf per container, its glyphs held in+ /// `text_engine`. `ifc_items` maps the container's `NodeId` to its item+ /// index. Paint rasterizes these instead of the per-word `text_runs`.+ #[cfg(feature = "paint")]+ pub text_engine: crate::inline::TextEngine,+ #[cfg(feature = "paint")]+ pub ifc_items: HashMap<NodeId, usize>,}/// Walk the tree top-down accumulating the clip rect imposed by ancestor@@ -88,34 +96,71 @@ fn cascade_walk(sheet: &crate::css::Stylesheet,matcher: &mut obscura_dom::selector::Matcher,styles: &mut HashMap<NodeId, crate::LayoutStyle>,+ parent_props: &std::rc::Rc<HashMap<String, String>>,+ node_props: &mut HashMap<NodeId, std::rc::Rc<HashMap<String, String>>>,) {let Some(node) = tree.get_node(id) else { return };- let is_element = node.as_element().map(|elem| {+ let is_element = node.is_element();+ // The custom-property map in force for this node's subtree: the parent's,+ // unless this element declares its own `--x` (then a richer map).+ let mut this_props = parent_props.clone();+ if let Some(elem) = node.as_element() {let mut style = crate::style::ua_style(elem.local.as_ref());+ // UA rule `[hidden]:not([hidden=until-found]) { display: none }`.+ // Applied before the author cascade so a matching author `display`+ // still wins (UA origin, per the HTML rendering spec). Sites ship+ // dialogs, tab panels, and menus with a plain `hidden` attribute and+ // reveal them by removing it (eBay's homepage interstitial uses+ // `.lightbox-dialog[role=dialog]:not([hidden]){display:flex}`), so+ // without this the hidden overlay paints its full-page dark backdrop.+ if let Some(h) = node.get_attribute("hidden") {+ if !h.eq_ignore_ascii_case("until-found") {+ style.display = crate::Display::None;+ }+ }if !sheet.is_empty() {let node_id = node.get_attribute("id");let classes: Vec<String> = node.get_attribute("class").map(|c| c.split_whitespace().map(|s| s.to_string()).collect()).unwrap_or_default();- sheet.apply(tree, matcher, id, node_id, &classes, elem.local.as_ref(), &mut style);+ if let Some(m) = sheet.apply(tree, matcher, id, node_id, &classes, elem.local.as_ref(), &mut style, parent_props) {+ this_props = std::rc::Rc::new(m);+ }}+ let (before, after) = sheet.pseudo_content(tree, matcher, id);+ style.before_content = before;+ style.after_content = after;styles.insert(id, style);- });+ node_props.insert(id, this_props.clone());+ }- if is_element.is_some() {+ if is_element {matcher.push_ancestor(tree, id);}for cid in tree.children(id) {- cascade_walk(tree, cid, sheet, matcher, styles);+ cascade_walk(tree, cid, sheet, matcher, styles, &this_props, node_props);}- if is_element.is_some() {+ if is_element {matcher.pop_ancestor();}}/// Lay out a DOM tree within `viewport` (width, height) in CSS pixels.pub fn layout_dom(tree: &DomTree, viewport: (f32, f32)) -> DomLayout {+ layout_dom_with_images(tree, viewport, &HashMap::new())+}++/// Like [`layout_dom`], but `intrinsic` supplies fetched intrinsic pixel sizes+/// (width, height) for replaced elements keyed by `NodeId`. Paint collects+/// these before layout (it has the base URL and the image cache) so a+/// CSS-sized `<img>` with no width/height attribute gets a real box from its+/// intrinsic ratio instead of collapsing to zero area.+pub fn layout_dom_with_images(+ tree: &DomTree,+ viewport: (f32, f32),+ intrinsic: &HashMap<NodeId, (f32, f32)>,+) -> DomLayout {let timing = std::env::var("OBSCURA_RENDER_TIMING").is_ok();// Collect the text of every <style> block in document order.@@ -137,12 +182,17 @@ pub fn layout_dom(tree: &DomTree, viewport: (f32, f32)) -> DomLayout {let t1 = std::time::Instant::now();let mut matcher = tree.matcher();let mut styles: HashMap<NodeId, crate::LayoutStyle> = HashMap::new();+ // Custom-property (`--x`) map per element, inherited down the tree and+ // shared via Rc so only elements that declare their own tokens allocate a+ // new map. Used to resolve `var()` here and in the inline-style pass.+ let mut node_props: HashMap<NodeId, std::rc::Rc<HashMap<String, String>>> = HashMap::new();+ let root_props = std::rc::Rc::new(HashMap::new());// A real preorder walk (not a flat descendants() scan) so the matcher's// ancestor bloom filter tracks the current path: push before recursing// into children, pop on the way back out. This is what lets descendant// combinators (".mw-body .firstHeading") fast-reject via the filter// instead of falling back to the always-true "can't reject" case.- cascade_walk(tree, tree.document(), &sheet, &mut matcher, &mut styles);+ cascade_walk(tree, tree.document(), &sheet, &mut matcher, &mut styles, &root_props, &mut node_props);if timing {let (r, i, c, l, u) = sheet.debug_stats();eprintln!("[timing] parse+index={:?} cascade={:?} rules={} id_keys={} class_keys={} local_keys={} universal={}", t_parse, t1.elapsed(), r, i, c, l, u);@@ -152,7 +202,29 @@ pub fn layout_dom(tree: &DomTree, viewport: (f32, f32)) -> DomLayout {if node.is_element() {if let Some(style) = styles.get_mut(&nid) {if let Some(inline) = node.get_attribute("style") {- crate::style::apply_inline(style, inline);+ // Resolve var() in inline styles against this element's+ // custom-property map (design systems set tokens then+ // reference them inline). Fold in custom properties+ // declared in this same inline style: they are applied+ // after the cascade built node_props, so a `--x` set and+ // referenced inline (e.g. `--bg:url(a.png);+ // background-image:var(--bg)`) is otherwise unresolved.+ let inline_vars: Vec<(String, String)> = crate::style::split_declarations(inline)+ .into_iter()+ .filter_map(|d| d.split_once(':').map(|(n, v)| (n.trim().to_string(), v.trim().to_string())))+ .filter(|(n, _)| n.starts_with("--") && n.len() > 2)+ .collect();+ let base = node_props.get(&nid);+ let expanded = if base.is_some() || !inline_vars.is_empty() {+ let mut map = base.map(|p| (**p).clone()).unwrap_or_default();+ for (k, v) in inline_vars {+ map.insert(k, v);+ }+ crate::css::substitute_vars(inline, &map, 0)+ } else {+ inline.to_string()+ };+ crate::style::apply_inline(style, &expanded);}if let Some(color) = node.get_attribute("color") {crate::style::apply_inline(style, &format!("color: {}", color));@@ -160,21 +232,49 @@ pub fn layout_dom(tree: &DomTree, viewport: (f32, f32)) -> DomLayout {if let Some(bgcolor) = node.get_attribute("bgcolor") {crate::style::apply_inline(style, &format!("background-color: {}", bgcolor));}- if let Some(width) = node.get_attribute("width") {- if width.chars().all(|c| c.is_ascii_digit()) {- crate::style::apply_inline(style, &format!("width: {}px", width));- } else {- crate::style::apply_inline(style, &format!("width: {}", width));+ // `width`/`height` HTML attributes are presentational hints:+ // they rank BELOW author CSS, so a class that sizes the+ // element (`.logo{height:2rem}` over `<img ... height="250">`)+ // must win. Apply the attribute only when the cascade left+ // the dimension unset, else the intrinsic attribute size+ // wrongly overrides the CSS and the element renders oversized.+ // Regardless, both attributes together establish the intrinsic+ // aspect ratio, so a CSS-sized-on-one-axis image (`.logo{+ // width:auto;height:100%}`) still derives the other axis from+ // the ratio instead of collapsing to zero.+ if style.aspect_ratio.is_none() {+ let aw = node.get_attribute("width").and_then(|w| w.parse::<f32>().ok());+ let ah = node.get_attribute("height").and_then(|h| h.parse::<f32>().ok());+ if let (Some(w), Some(h)) = (aw, ah) {+ if w > 0.0 && h > 0.0 {+ style.aspect_ratio = Some(w / h);+ }+ }+ }+ if !style.width_set {+ if let Some(width) = node.get_attribute("width") {+ if width.chars().all(|c| c.is_ascii_digit()) {+ crate::style::apply_inline(style, &format!("width: {}px", width));+ } else {+ crate::style::apply_inline(style, &format!("width: {}", width));+ }}}if let Some(align) = node.get_attribute("align") {crate::style::apply_inline(style, &format!("text-align: {}", align));}- if let Some(height) = node.get_attribute("height") {- if height.chars().all(|c| c.is_ascii_digit()) {- crate::style::apply_inline(style, &format!("height: {}px", height));- } else {- crate::style::apply_inline(style, &format!("height: {}", height));+ if let Some(cellspacing) = node.get_attribute("cellspacing") {+ if cellspacing.chars().all(|c| c.is_ascii_digit()) {+ crate::style::apply_inline(style, &format!("border-spacing: {}px", cellspacing));+ }+ }+ if !style.height_set {+ if let Some(height) = node.get_attribute("height") {+ if height.chars().all(|c| c.is_ascii_digit()) {+ crate::style::apply_inline(style, &format!("height: {}px", height));+ } else {+ crate::style::apply_inline(style, &format!("height: {}", height));+ }}}}@@ -183,10 +283,15 @@ pub fn layout_dom(tree: &DomTree, viewport: (f32, f32)) -> DomLayout {}grow_trailing_auto_cells(tree, &mut styles);+ propagate_border_spacing(tree, &mut styles);- let mut taffy_tree: TaffyTree = TaffyTree::new();+ // The leaf context is the index of a cosmic-text inline formatting+ // context in `engine`; leaves without text carry no context.+ let mut taffy_tree: TaffyTree<usize> = TaffyTree::new();let mut id_map: HashMap<taffy::NodeId, NodeId> = HashMap::new();let mut words: HashMap<taffy::NodeId, (NodeId, String)> = HashMap::new();+ let mut engine = crate::inline::TextEngine::new();+ let mut ifc_items: HashMap<NodeId, usize> = HashMap::new();// The document node itself is not an element; lay out from the first// element descendant (the <html> root).@@ -199,18 +304,95 @@ pub fn layout_dom(tree: &DomTree, viewport: (f32, f32)) -> DomLayout {let mut text_runs = HashMap::new();if let Some(root_id) = root {// Top-down inheritance of the properties CSS inherits by default.- #[derive(Clone, Default)]+ #[derive(Clone)]struct Inherited {color: Option<[u8; 4]>,font_size: Option<f32>,font_weight: Option<String>,+ visibility_hidden: bool,+ opacity_product: f32,+ list_style: crate::ListStyle,+ line_height: crate::LineHeight,+ text_transform: crate::TextTransform,+ italic: bool,}+ impl Default for Inherited {+ fn default() -> Self {+ Inherited {+ color: None,+ font_size: None,+ font_weight: None,+ visibility_hidden: false,+ opacity_product: 1.0,+ // CSS initial value of list-style-type.+ list_style: crate::ListStyle::Disc,+ line_height: crate::LineHeight::Normal,+ text_transform: crate::TextTransform::None,+ italic: false,+ }+ }+ }+ // Viewport-per-unit for vw/vh, and the root font-size for rem. em/rem/+ // vw/vh lengths were parsed unresolved (the element font-size and+ // viewport are not known at parse time); resolve them here, top-down,+ // where the computed font-size is available.+ let vw = viewport.0 / 100.0;+ let vh = viewport.1 / 100.0;+ let root_fs = {+ let s = styles.get(&root_id);+ match (s.and_then(|s| s.font_size), s.and_then(|s| s.font_size_raw)) {+ (Some(px), _) => px,+ (None, Some(d)) => match d.resolve(16.0, 16.0, vw, vh) {+ crate::Dimension::Px(p) => p,+ crate::Dimension::Percent(p) => 16.0 * p,+ _ => 16.0,+ },+ _ => 16.0,+ }+ };+let mut queue = vec![(root_id, Inherited::default())];while let Some((id, mut inh)) = queue.pop() {if let Some(style) = styles.get_mut(&id) {match style.color { Some(c) => inh.color = Some(c), None => style.color = inh.color }+ // Resolve a relative font-size against the PARENT (em/%) or+ // ROOT (rem) font-size before inheriting it downward.+ let parent_fs = inh.font_size.unwrap_or(16.0);+ if let Some(raw) = style.font_size_raw {+ let resolved = match raw {+ crate::Dimension::Percent(p) => parent_fs * p,+ crate::Dimension::Em(v) => parent_fs * v,+ d => match d.resolve(parent_fs, root_fs, vw, vh) {+ crate::Dimension::Px(p) => p,+ _ => parent_fs,+ },+ };+ style.font_size = Some(resolved);+ }match style.font_size { Some(s) => inh.font_size = Some(s), None => style.font_size = inh.font_size }+ // em in non-font-size properties is relative to this element's+ // OWN computed font-size; resolve every relative length now.+ let em_px = style.font_size.unwrap_or(parent_fs);+ style.width = style.width.resolve(em_px, root_fs, vw, vh);+ style.height = style.height.resolve(em_px, root_fs, vw, vh);+ style.min_width = style.min_width.resolve(em_px, root_fs, vw, vh);+ style.min_height = style.min_height.resolve(em_px, root_fs, vw, vh);+ style.max_width = style.max_width.resolve(em_px, root_fs, vw, vh);+ style.max_height = style.max_height.resolve(em_px, root_fs, vw, vh);+ style.flex_basis = style.flex_basis.resolve(em_px, root_fs, vw, vh);+ for i in style.inset.iter_mut() {+ if let Some(d) = i {+ *i = Some(d.resolve(em_px, root_fs, vw, vh));+ }+ }match &style.font_weight { Some(w) => inh.font_weight = Some(w.clone()), None => style.font_weight = inh.font_weight.clone() }+ inh.visibility_hidden = style.visibility_hidden.unwrap_or(inh.visibility_hidden);+ inh.opacity_product *= style.opacity.unwrap_or(1.0);+ style.effectively_invisible = inh.visibility_hidden || inh.opacity_product < 0.02;+ match style.list_style { Some(v) => inh.list_style = v, None => style.list_style = Some(inh.list_style) }+ match style.line_height { Some(v) => inh.line_height = v, None => style.line_height = Some(inh.line_height) }+ match style.text_transform { Some(v) => inh.text_transform = v, None => style.text_transform = Some(inh.text_transform) }+ match style.font_style_italic { Some(v) => inh.italic = v, None => style.font_style_italic = Some(inh.italic) }}for cid in tree.children(id).into_iter().rev() {queue.push((cid, inh.clone()));@@ -219,15 +401,269 @@ pub fn layout_dom(tree: &DomTree, viewport: (f32, f32)) -> DomLayout {resolve_grid_areas(tree, root_id, &mut styles);- if let Some(taffy_root) = build(tree, root_id, &mut taffy_tree, &mut id_map, &mut words, &styles) {- let _ = taffy_tree.compute_layout(- taffy_root,- taffy::Size {- width: taffy::AvailableSpace::Definite(viewport.0),- height: taffy::AvailableSpace::Definite(viewport.1),- },- );+ // The initial containing block is modelled by the root taffy node's+ // definite viewport height (set at build), which is what `html,body{+ // height:100%}` chains and sticky-footer app shells resolve against.+ // taffy 0.7 needed an extra `min-height: viewport` push on the root+ // style to stop those chains collapsing to content height; taffy 0.12+ // resolves them from the node's definite height directly, and that push+ // instead over-propagated the viewport height down every `height:100%`+ // subtree (nextjs.org's nav stretched to a full 688px, burying the+ // hero), so it is gone.++ // Apply fetched intrinsic image sizes. A replaced element with no+ // explicit dimensions must size from its intrinsic pixels (else it is+ // 0x0 and never paints); with one dimension given, the aspect ratio+ // fills the other. `max-width:100%` (a UA default for img) still caps+ // it to the container, and the aspect ratio keeps it proportional.+ for (&nid, &(iw, ih)) in intrinsic {+ if iw <= 0.0 || ih <= 0.0 {+ continue;+ }+ if let Some(s) = styles.get_mut(&nid) {+ if s.aspect_ratio.is_none() {+ s.aspect_ratio = Some(iw / ih);+ }+ let w_auto = matches!(s.width, crate::Dimension::Auto);+ let h_auto = matches!(s.height, crate::Dimension::Auto);+ if w_auto && h_auto {+ s.width = crate::Dimension::Px(iw);+ s.height = crate::Dimension::Px(ih);+ }+ }+ }++ if let Some(taffy_root) = build(tree, root_id, &mut taffy_tree, &mut id_map, &mut words, &mut engine, &mut ifc_items, &styles) {+ let available = taffy::Size {+ width: taffy::AvailableSpace::Definite(viewport.0),+ height: taffy::AvailableSpace::Definite(viewport.1),+ };+ #[cfg(feature = "paint")]+ {+ let engine = &mut engine;+ let mut measure =+ |known: taffy::Size<Option<f32>>, avail: taffy::Size<taffy::AvailableSpace>, _node, ctx: Option<&mut usize>, _style: &taffy::Style| {+ match ctx {+ Some(&mut idx) => {+ // Width to line-break at: a known definite width,+ // else the available width; MinContent -> narrowest+ // (longest word), MaxContent -> unbounded (one line).+ let width = known.width.or(match avail.width {+ taffy::AvailableSpace::Definite(w) => Some(w),+ taffy::AvailableSpace::MinContent => Some(0.0),+ taffy::AvailableSpace::MaxContent => None,+ });+ let (w, h) = engine.measure(idx, width);+ taffy::Size { width: w, height: h }+ }+ None => taffy::Size::ZERO,+ }+ };++ // Table used-width pass. A grid table is built at width:auto, so+ // its final width has to be chosen the way CSS chooses a table's+ // used width: at least the content min-content (so an unbreakable+ // wide cell, e.g. a fixed-width image row in an infobox, makes the+ // table grow rather than overflow), at most the available width,+ // preferring the author's specified width when there is one.+ let mut tables: Vec<(taffy::NodeId, NodeId, usize)> = id_map+ .iter()+ .filter(|(_, dom)| {+ tree.get_node(**dom)+ .and_then(|n| n.as_element().map(|e| e.local.as_ref() == "table"))+ .unwrap_or(false)+ })+ .map(|(t, d)| (*t, *d, dom_depth(tree, *d)))+ .collect();+ // Deepest table first: an inner table gets its final width set+ // before an outer table measures the subtree that contains it.+ // Two tables at the same depth cannot be nested in one another+ // (nesting increases depth), so their relative order is+ // irrelevant and the final layout is deterministic even though+ // id_map iteration order is not.+ tables.sort_by(|a, b| b.2.cmp(&a.2));+ for (tnode, dom, _depth) in tables {+ // A percentage-width table resolves against its container, so+ // leave taffy's percentage handling in place.+ let width_style = styles.get(&dom).map(|s| s.width.clone());+ if matches!(width_style, Some(crate::Dimension::Percent(_))) {+ continue;+ }+ let min_c = {+ let _ = taffy_tree.compute_layout_with_measure(+ tnode,+ taffy::Size { width: taffy::AvailableSpace::MinContent, height: taffy::AvailableSpace::MaxContent },+ &mut measure,+ );+ taffy_tree.layout(tnode).map(|l| l.size.width).unwrap_or(0.0)+ };+ // A table can never be narrower than an unshrinkable+ // fixed-width descendant. A Wikipedia infobox holds a+ // ~267px image montage and a ~250px geologic-timeline+ // widget, each with an explicit px width; taffy's grid+ // min-content does not surface such a deep descendant's+ // definite width up through the intervening flex/absolute+ // boxes, leaving the table too narrow so those widgets+ // overflow it. Floor min-content by the widest fixed child,+ // matching CSS (a table's min-content is at least any+ // fixed-width content it contains).+ let min_c = min_c.max(max_definite_descendant_width(tree, dom, &styles).unwrap_or(0.0));+ let max_c = {+ let _ = taffy_tree.compute_layout_with_measure(+ tnode,+ taffy::Size { width: taffy::AvailableSpace::MaxContent, height: taffy::AvailableSpace::MaxContent },+ &mut measure,+ );+ taffy_tree.layout(tnode).map(|l| l.size.width).unwrap_or(0.0)+ };+ let preferred = match width_style {+ Some(crate::Dimension::Px(w)) => w,+ _ => max_c,+ };+ let used = preferred.max(min_c).min(viewport.0.max(min_c));+ // Distribute `used` across the columns proportionally between+ // each column's own min-content and max-content width, the way+ // CSS tables do, instead of letting the grid hand every auto+ // track an equal share of the surplus (which over-widens narrow+ // label columns and starves wide prose columns). NetSurf+ // layout.c layout_table: col.width = col.min + (col.max - col.min)+ // * (used - min) / (max - min). The table's border, padding, and+ // inter-column border-spacing are layout-invariant, so they are+ // recovered once from the whole-table min-content width and kept+ // out of the interpolation.+ let cells: Vec<(taffy::NodeId, usize, usize)> = taffy_tree+ .children(tnode)+ .unwrap_or_default()+ .into_iter()+ .filter_map(|cell| {+ let gc = taffy_tree.style(cell).ok()?.grid_column.clone();+ let col = match gc.start {+ GridPlacement::Line(l) => (l.as_i16().max(1) as usize) - 1,+ _ => return None,+ };+ let span = match gc.end {+ GridPlacement::Span(s) => (s as usize).max(1),+ _ => 1,+ };+ Some((cell, col, span))+ })+ .collect();+ let ncols = taffy_tree+ .style(tnode)+ .map(|s| s.grid_template_columns.len())+ .unwrap_or(0);+ // Bound the extra per-cell measurement work; a pathologically+ // large table keeps the grid's equal-share sizing (still renders).+ if ncols > 0 && cells.len() <= 4096 {+ // Measure every cell's own min-content and max-content width+ // in isolation (the cell node is a valid subtree root; its+ // grid placement only matters to its parent, so it lays out+ // as a plain box here).+ let mut measured: Vec<(usize, usize, f32, f32)> =+ Vec::with_capacity(cells.len());+ for (cell, col, span) in &cells {+ let _ = taffy_tree.compute_layout_with_measure(+ *cell,+ taffy::Size { width: taffy::AvailableSpace::MinContent, height: taffy::AvailableSpace::MaxContent },+ &mut measure,+ );+ let cmin = taffy_tree.layout(*cell).map(|l| l.size.width).unwrap_or(0.0);+ let _ = taffy_tree.compute_layout_with_measure(+ *cell,+ taffy::Size { width: taffy::AvailableSpace::MaxContent, height: taffy::AvailableSpace::MaxContent },+ &mut measure,+ );+ let cmax = taffy_tree.layout(*cell).map(|l| l.size.width).unwrap_or(0.0);+ measured.push((*col, *span, cmin, cmax.max(cmin)));+ }+ let mut col_min = vec![0.0f32; ncols];+ let mut col_max = vec![0.0f32; ncols];+ // Pass 1: single-column cells set each column's floor.+ for &(col, span, cmin, cmax) in &measured {+ if span == 1 && col < ncols {+ col_min[col] = col_min[col].max(cmin);+ col_max[col] = col_max[col].max(cmax);+ }+ }+ // Pass 2: a spanning cell that needs more than its columns+ // currently give grows them, splitting the shortfall evenly+ // across the spanned columns (keeps colspan lining up).+ for &(col, span, cmin, cmax) in &measured {+ if span <= 1 || col >= ncols {+ continue;+ }+ let end = (col + span).min(ncols);+ let n = (end - col) as f32;+ let cur_min: f32 = col_min[col..end].iter().sum();+ if cmin > cur_min {+ let add = (cmin - cur_min) / n;+ for w in &mut col_min[col..end] {+ *w += add;+ }+ }+ let cur_max: f32 = col_max[col..end].iter().sum();+ if cmax > cur_max {+ let add = (cmax - cur_max) / n;+ for w in &mut col_max[col..end] {+ *w += add;+ }+ }+ }+ for j in 0..ncols {+ if col_max[j] < col_min[j] {+ col_max[j] = col_min[j];+ }+ }+ let sum_min: f32 = col_min.iter().sum();+ let sum_max: f32 = col_max.iter().sum();+ // overhead = table border + padding + inter-column spacing,+ // recovered from the whole-table min-content width.+ let overhead = (min_c - sum_min).max(0.0);+ let target = (used - overhead).max(0.0);+ let widths: Vec<f32> = if sum_max <= sum_min || target <= sum_min {+ col_min.clone()+ } else if target >= sum_max {+ // Table wider than max-content (explicit/percentage-ish+ // width): hand the extra out equally, as real tables do.+ let extra = (target - sum_max) / ncols as f32;+ col_max.iter().map(|m| m + extra).collect()+ } else {+ let scale = (target - sum_min) / (sum_max - sum_min);+ col_min+ .iter()+ .zip(&col_max)+ .map(|(mn, mx)| mn + (mx - mn) * scale)+ .collect()+ };+ if let Ok(cur) = taffy_tree.style(tnode) {+ let mut s = cur.clone();+ s.size.width = length(used);+ s.grid_template_columns = widths+ .iter()+ .map(|w| {+ taffy::GridTemplateComponent::Single(taffy::MinMax {+ min: taffy::MinTrackSizingFunction::length(*w),+ max: taffy::MaxTrackSizingFunction::length(*w),+ })+ })+ .collect();+ let _ = taffy_tree.set_style(tnode, s);+ }+ } else if let Ok(cur) = taffy_tree.style(tnode) {+ let mut s = cur.clone();+ s.size.width = length(used);+ let _ = taffy_tree.set_style(tnode, s);+ }+ }++ let _ = taffy_tree.compute_layout_with_measure(taffy_root, available, &mut measure);+ }+ #[cfg(not(feature = "paint"))]+ {+ let _ = taffy_tree.compute_layout(taffy_root, available);+ }compute_absolute_rects(&taffy_tree, taffy_root, 0.0, 0.0, &id_map, &words, &mut rects, &mut text_runs);+ synthesize_row_rects(tree, &mut rects);}}@@ -236,7 +672,40 @@ pub fn layout_dom(tree: &DomTree, viewport: (f32, f32)) -> DomLayout {resolve_clip_rects(tree, root_id, None, &rects, &styles, &mut clip_rects);}- DomLayout { rects, styles, clip_rects, text_runs }+ // Pin each shaped inline context to its final content-box origin/width now+ // that layout is done, so paint draws the same line breaks it was sized for.+ #[cfg(feature = "paint")]+ for (nid, &idx) in &ifc_items {+ if let (Some(rect), Some(style)) = (rects.get(nid), styles.get(nid)) {+ let origin = crate::inline::content_origin(rect, style);+ let cw = crate::inline::content_width(rect, style);+ // The shaped text is this container's own content, so an+ // `overflow: hidden` on the container clips it (this is what keeps+ // the 1x1 "visually hidden" skip-link box from painting its text,+ // now that the text is one leaf rather than clipped word boxes).+ let inherited = clip_rects.get(nid).copied().flatten();+ let clip = if style.overflow_hidden {+ Some(match inherited {+ Some(c) => c.intersect(rect).unwrap_or(crate::Rect::default()),+ None => *rect,+ })+ } else {+ inherited+ };+ engine.finalize(idx, origin, cw, clip);+ }+ }++ DomLayout {+ rects,+ styles,+ clip_rects,+ text_runs,+ #[cfg(feature = "paint")]+ text_engine: engine,+ #[cfg(feature = "paint")]+ ifc_items,+ }}/// HTML table auto-layout approximation: for each `<tr>`, the last `<td>`/@@ -272,6 +741,45 @@ fn grow_trailing_auto_cells(tree: &DomTree, styles: &mut HashMap<NodeId, crate::}}+/// `border-spacing` (from CSS or the `cellspacing` attribute) is set on a+/// `<table>`, but taffy has no native table display mode: our table is a+/// column-flex stack of row-flex `<tr>`s, so the gap that separates cells has+/// to live on each row individually. Distribute the table's border-spacing+/// down as the table's own row gap (space between stacked `<tr>`s) and every+/// descendant `<tr>`'s column gap (space between cells within a row), without+/// crossing into a nested `<table>`'s own scope.+fn propagate_border_spacing(tree: &DomTree, styles: &mut HashMap<NodeId, crate::LayoutStyle>) {+ fn local_name(tree: &DomTree, id: NodeId) -> Option<String> {+ tree.get_node(id).and_then(|n| n.as_element().map(|e| e.local.to_string()))+ }++ fn apply_to_rows(tree: &DomTree, id: NodeId, h: f32, v: f32, styles: &mut HashMap<NodeId, crate::LayoutStyle>) {+ for cid in tree.children(id) {+ if local_name(tree, cid).as_deref() == Some("table") {+ continue;+ }+ if local_name(tree, cid).as_deref() == Some("tr") {+ if let Some(s) = styles.get_mut(&cid) {+ s.column_gap = Some(h);+ s.row_gap = Some(v);+ }+ }+ apply_to_rows(tree, cid, h, v, styles);+ }+ }++ for id in tree.descendants(tree.document()) {+ if local_name(tree, id).as_deref() != Some("table") {+ continue;+ }+ let Some((h, v)) = styles.get(&id).and_then(|s| s.border_spacing) else { continue };+ if let Some(s) = styles.get_mut(&id) {+ s.row_gap = Some(v);+ }+ apply_to_rows(tree, id, h, v, styles);+ }+}+/// Walk the tree; for each `display: grid` element that declares/// `grid-template-areas`, resolve each direct child's `grid-area` name to a/// taffy line placement. This is how Vector 2022 (and most grid layouts) place@@ -286,53 +794,117 @@ fn resolve_grid_areas(for cid in tree.children(id) {stack.push(cid);}- let areas = match styles.get(&id) {- Some(s) if s.display == crate::Display::Grid => match &s.grid_areas {- Some(a) if !a.is_empty() => a.clone(),- _ => continue,- },+ let (areas, col_lines, row_lines) = match styles.get(&id) {+ Some(s) if s.display == crate::Display::Grid => (+ s.grid_areas.clone().filter(|a| !a.is_empty()),+ s.grid_col_line_names.clone(),+ s.grid_row_line_names.clone(),+ ),_ => continue,};+ if areas.is_none() && col_lines.is_none() && row_lines.is_none() {+ continue;+ }- // name -> (row_start, row_end, col_start, col_end) in 0-based track indices.- let mut spans: HashMap<String, (usize, usize, usize, usize)> = HashMap::new();- for (r, row) in areas.iter().enumerate() {- for (c, name) in row.iter().enumerate() {- if name == "." {- continue;+ if let Some(areas) = &areas {+ // name -> (row_start, row_end, col_start, col_end) in 0-based track indices.+ let mut spans: HashMap<String, (usize, usize, usize, usize)> = HashMap::new();+ for (r, row) in areas.iter().enumerate() {+ for (c, name) in row.iter().enumerate() {+ if name == "." {+ continue;+ }+ spans+ .entry(name.clone())+ .and_modify(|s| {+ s.0 = s.0.min(r);+ s.1 = s.1.max(r);+ s.2 = s.2.min(c);+ s.3 = s.3.max(c);+ })+ .or_insert((r, r, c, c));+ }+ }++ for cid in tree.children(id) {+ let Some(cstyle) = styles.get_mut(&cid) else { continue };+ let Some(name) = cstyle.grid_area_name.clone() else { continue };+ if let Some(&(r0, r1, c0, c1)) = spans.get(&name) {+ use taffy::style_helpers::line;+ cstyle.grid_row = Some(taffy::Line {+ start: line((r0 + 1) as i16),+ end: line((r1 + 2) as i16),+ });+ cstyle.grid_column = Some(taffy::Line {+ start: line((c0 + 1) as i16),+ end: line((c1 + 2) as i16),+ });}- spans- .entry(name.clone())- .and_modify(|s| {- s.0 = s.0.min(r);- s.1 = s.1.max(r);- s.2 = s.2.min(c);- s.3 = s.3.max(c);- })- .or_insert((r, r, c, c));}}- for cid in tree.children(id) {- let Some(cstyle) = styles.get_mut(&cid) else { continue };- let Some(name) = cstyle.grid_area_name.clone() else { continue };- if let Some(&(r0, r1, c0, c1)) = spans.get(&name) {- use taffy::style_helpers::line;- cstyle.grid_row = Some(taffy::Line {- start: line((r0 + 1) as i16),- end: line((r1 + 2) as i16),- });- cstyle.grid_column = Some(taffy::Line {- start: line((c0 + 1) as i16),- end: line((c1 + 2) as i16),- });+ // Named grid lines: resolve children placed with `grid-column`/`grid-row`+ // values that reference a line name against this container's maps.+ if col_lines.is_some() || row_lines.is_some() {+ for cid in tree.children(id) {+ let Some(cstyle) = styles.get_mut(&cid) else { continue };+ if let (Some(raw), Some(map)) = (cstyle.grid_column_raw.clone(), &col_lines) {+ if let Some(l) = resolve_named_placement(&raw, map) {+ cstyle.grid_column = Some(l);+ }+ }+ if let (Some(raw), Some(map)) = (cstyle.grid_row_raw.clone(), &row_lines) {+ if let Some(l) = resolve_named_placement(&raw, map) {+ cstyle.grid_row = Some(l);+ }+ }}}}}+/// Resolve a raw `grid-column`/`grid-row` value that names grid lines into a+/// numeric `taffy::Line`, using `map` (line-name -> 1-based line number). Handles+/// `a / b` (each side a name, integer, or `span n`) and the single-ident+/// `grid-column: foo` area shorthand (`foo-start / foo-end`). Returns `None` when+/// a referenced name is absent, leaving the item to auto-place.+fn resolve_named_placement(+ raw: &str,+ map: &HashMap<String, i16>,+) -> Option<taffy::Line<taffy::GridPlacement>> {+ use taffy::style_helpers::{line, span};+ let side = |tok: &str| -> Option<taffy::GridPlacement> {+ let t = tok.trim();+ if t.is_empty() || t.eq_ignore_ascii_case("auto") {+ return Some(taffy::GridPlacement::Auto);+ }+ if let Some(n) = t.strip_prefix("span") {+ if let Ok(s) = n.trim().parse::<u16>() {+ return Some(span(s));+ }+ }+ if let Ok(i) = t.parse::<i16>() {+ return Some(line(i));+ }+ map.get(t).map(|&l| line(l))+ };+ if let Some((a, b)) = raw.split_once('/') {+ Some(taffy::Line { start: side(a)?, end: side(b)? })+ } else {+ let name = raw.trim();+ if let Some(&s) = map.get(&format!("{name}-start")) {+ let end = map+ .get(&format!("{name}-end"))+ .map(|&e| line(e))+ .unwrap_or(taffy::GridPlacement::Auto);+ return Some(taffy::Line { start: line(s), end });+ }+ map.get(name).map(|&s| taffy::Line { start: line(s), end: taffy::GridPlacement::Auto })+ }+}+fn compute_absolute_rects(- taffy_tree: &TaffyTree,+ taffy_tree: &TaffyTree<usize>,taffy_id: taffy::NodeId,abs_x: f32,abs_y: f32,@@ -372,7 +944,18 @@ fn has_inline_content(tree: &DomTree, id: NodeId, styles: &HashMap<NodeId, cratelet Some(node) = tree.get_node(cid) else { return false };match &node.data {obscura_dom::tree::NodeData::Text { contents } => !contents.trim().is_empty(),- _ => styles.get(&cid).map(|s| s.display == crate::Display::Inline).unwrap_or(false),+ _ => styles+ .get(&cid)+ .map(|s| {+ // A display:contents wrapper is transparent: whether it+ // reads as inline content depends on what it splices in.+ if s.display_contents && s.display != crate::Display::None {+ has_inline_content(tree, cid, styles)+ } else {+ s.display == crate::Display::Inline+ }+ })+ .unwrap_or(false),}})}@@ -389,9 +972,11 @@ fn has_inline_content(tree: &DomTree, id: NodeId, styles: &HashMap<NodeId, cratefn build_any(tree: &DomTree,id: NodeId,- taffy_tree: &mut TaffyTree,+ taffy_tree: &mut TaffyTree<usize>,id_map: &mut HashMap<taffy::NodeId, NodeId>,words: &mut HashMap<taffy::NodeId, (NodeId, String)>,+ engine: &mut crate::inline::TextEngine,+ ifc_items: &mut HashMap<NodeId, usize>,styles: &HashMap<NodeId, crate::LayoutStyle>,) -> Vec<taffy::NodeId> {let is_text = tree@@ -399,10 +984,76 @@ fn build_any(.map(|n| matches!(n.data, obscura_dom::tree::NodeData::Text { .. })).unwrap_or(false);if is_text {- build_text_words(tree, id, taffy_tree, styles, words)- } else {- build(tree, id, taffy_tree, id_map, words, styles).into_iter().collect()+ return build_text_words(tree, id, taffy_tree, styles, words);+ }+ // `display: contents` removes the element's own box; its children lay out as+ // if they were direct children of its parent (CSS Display 3). Splice them+ // into the caller's child list (same trick as inline wrappers below).+ // Without this the wrapper became a normal auto-sized box (news-site card+ // anchors are `<a style="display:contents">` around the image), which+ // collapsed to zero area and blanked the image inside (bbc.com/news hero,+ // theguardian.com cards). `display:none` still wins.+ let splices_children = styles+ .get(&id)+ .map(|s| s.display_contents && s.display != crate::Display::None)+ .unwrap_or(false);+ if splices_children {+ return tree+ .children(id)+ .into_iter()+ .flat_map(|cid| build_any(tree, cid, taffy_tree, id_map, words, engine, ifc_items, styles))+ .collect();+ }+ if is_flattenable_inline(tree, id, styles) {+ // A plain inline wrapper (`<span>`, `<a>`, `<b>`, ...) around text+ // with no box appearance of its own: giving it its own flex-wrap+ // container, like every other element gets, would make *it* the+ // inline-formatting context instead of the enclosing block, which is+ // backwards. Real inline boxes do not wrap independently; the words+ // they contain wrap as part of the single line-breaking process run+ // by their nearest block ancestor. Concretely, a taffy flex-wrap+ // container with an auto width sizes itself from a "measure" pass+ // that does not yet know the final available width, so it collapses+ // toward a min-content (one word wide) guess — visible on Wikipedia's+ // "53 languages" label, which wrapped to "53" / "languages" on two+ // lines purely because the wrapping `<span>` around that text was+ // itself an independent auto-width wrap container. Flattening the+ // wrapper's children into the caller's list (same trick already used+ // for text nodes in `build_text_words`) fixes this at the root: the+ // words become flat siblings that wrap only at the real block level.+ return tree+ .children(id)+ .into_iter()+ .flat_map(|cid| build_any(tree, cid, taffy_tree, id_map, words, engine, ifc_items, styles))+ .collect();+ }+ build(tree, id, taffy_tree, id_map, words, engine, ifc_items, styles).into_iter().collect()+}++/// Is `id` a `display: inline` element with no box appearance or sizing of+/// its own — safe to flatten into its parent's child list instead of giving+/// it an independent (and, for wrapping auto-width containers, buggy) flex+/// context? Covers the dominant real-world case: `<a>`/`<span>`/`<b>`/etc.+/// wrapping plain text with no inline styling.+fn is_flattenable_inline(tree: &DomTree, id: NodeId, styles: &HashMap<NodeId, crate::LayoutStyle>) -> bool {+ let Some(node) = tree.get_node(id) else { return false };+ if node.as_element().is_none() {+ return false;}+ let Some(style) = styles.get(&id) else { return false };+ style.display == crate::Display::Inline+ && !style.is_inline_block+ && style.before_content.is_none()+ && style.after_content.is_none()+ && style.background_color.is_none()+ && style.background_image.is_none()+ && style.mask_image.is_none()+ && style.border == crate::Edges::default()+ && style.width == crate::Dimension::Auto+ && style.height == crate::Dimension::Auto+ && style.position.is_none()+ && !style.overflow_hidden+ && style.float.is_none()}/// Split a text node into one taffy leaf per word (a whitespace-delimited@@ -417,7 +1068,7 @@ fn build_any(fn build_text_words(tree: &DomTree,id: NodeId,- taffy_tree: &mut TaffyTree,+ taffy_tree: &mut TaffyTree<usize>,styles: &HashMap<NodeId, crate::LayoutStyle>,words: &mut HashMap<taffy::NodeId, (NodeId, String)>,) -> Vec<taffy::NodeId> {@@ -447,7 +1098,22 @@ fn build_text_words(}}- tokenize_with_spaces(&display_text)+ build_word_leaves(id, &display_text, fsize, is_bold, taffy_tree, words)+}++/// Split `text` into one taffy leaf per word and register each against+/// `source_id` in `words`. Shared by `build_text_words` (a real DOM text+/// node) and `build_pseudo_content` (a `::before`/`::after` literal, which+/// has no text node of its own — `source_id` is the host element instead).+fn build_word_leaves(+ source_id: NodeId,+ text: &str,+ fsize: f32,+ is_bold: bool,+ taffy_tree: &mut TaffyTree<usize>,+ words: &mut HashMap<taffy::NodeId, (NodeId, String)>,+) -> Vec<taffy::NodeId> {+ tokenize_with_spaces(text).into_iter().filter_map(|token| {let width = text_width(&token, fsize, is_bold);@@ -459,16 +1125,33 @@ fn build_text_words(// around a run of now-collapsed, display:none list items).let height = if token.trim().is_empty() { 0.0 } else { fsize * 1.2 };let taffy_style = taffy::Style {- size: taffy::Size { width: taffy::Dimension::Length(width), height: taffy::Dimension::Length(height) },+ size: taffy::Size { width: taffy::Dimension::length(width), height: taffy::Dimension::length(height) },..Default::default()};let taffy_id = taffy_tree.new_leaf(taffy_style).ok()?;- words.insert(taffy_id, (id, token));+ words.insert(taffy_id, (source_id, token));Some(taffy_id)}).collect()}+/// Build the word leaves for a `::before`/`::after` literal `content`,+/// registered against the host element's own id (there is no real DOM text+/// node backing generated content, so its geometry is reported under the+/// element itself in `DomLayout::text_runs`, and painted the same way a real+/// text node's words are).+fn build_pseudo_content(+ id: NodeId,+ content: &str,+ style: &crate::LayoutStyle,+ taffy_tree: &mut TaffyTree<usize>,+ words: &mut HashMap<taffy::NodeId, (NodeId, String)>,+) -> Vec<taffy::NodeId> {+ let fsize = style.font_size.unwrap_or(16.0);+ let is_bold = style.font_weight.as_deref() == Some("bold");+ build_word_leaves(id, content, fsize, is_bold, taffy_tree, words)+}+/// Split already whitespace-collapsed text into tokens, each carrying at most/// one trailing space (`"Hello World "` -> `["Hello ", "World "]`), so a/// word's own width naturally includes the gap to the next one.@@ -487,12 +1170,226 @@ fn tokenize_with_spaces(text: &str) -> Vec<String> {tokens}+/// Give each `<tr>`/`<tbody>`/`<thead>`/`<tfoot>` a rect equal to the union of+/// its descendant cell rects. In the grid table model these wrappers are not+/// taffy boxes, so without this their backgrounds and borders (zebra striping,+/// a `thead` background, a per-row border) would never paint. Skips a wrapper+/// that already has a rect (a table that fell back to the flex path keeps its+/// real box).+fn synthesize_row_rects(tree: &DomTree, rects: &mut HashMap<NodeId, Rect>) {+ for id in tree.descendants(tree.document()) {+ let local = match tree.get_node(id).and_then(|n| n.as_element().map(|e| e.local.to_string())) {+ Some(l) => l,+ None => continue,+ };+ if !matches!(local.as_str(), "tr" | "tbody" | "thead" | "tfoot") {+ continue;+ }+ if rects.contains_key(&id) {+ continue;+ }+ let mut acc: Option<Rect> = None;+ for d in tree.descendants(id) {+ let is_cell = tree+ .get_node(d)+ .and_then(|n| n.as_element().map(|e| matches!(e.local.as_ref(), "td" | "th")))+ .unwrap_or(false);+ if !is_cell {+ continue;+ }+ if let Some(r) = rects.get(&d) {+ acc = Some(match acc {+ Some(a) => a.union(r),+ None => *r,+ });+ }+ }+ if let Some(r) = acc {+ rects.insert(id, r);+ }+ }+}++/// Collect `<tr>` elements of a table in document order, descending through+/// `<thead>`/`<tbody>`/`<tfoot>` section wrappers but never into a cell or a+/// nested `<table>` (whose rows belong to that inner table).+/// Number of ancestors of `id` up to the document root. Used to order nested+/// tables deepest-first in the table used-width pass.+fn dom_depth(tree: &DomTree, id: NodeId) -> usize {+ let mut d = 0usize;+ let mut cur = id;+ while let Some(p) = tree.get_node(cur).and_then(|n| n.parent) {+ d += 1;+ cur = p;+ if d > 4096 {+ break;+ }+ }+ d+}++fn collect_table_rows(tree: &DomTree, id: NodeId, rows: &mut Vec<NodeId>) {+ for cid in tree.children(id) {+ let local = tree.get_node(cid).and_then(|n| n.as_element().map(|e| e.local.to_string()));+ match local.as_deref() {+ Some("tr") => rows.push(cid),+ Some("thead") | Some("tbody") | Some("tfoot") => collect_table_rows(tree, cid, rows),+ _ => {}+ }+ }+}++/// Build a `<table>` as a CSS grid. Modeling the table as a grid is what makes+/// columns negotiate a shared width across every row (min-content/max-content+/// track sizing), which the old flex-row-per-`<tr>` stack could not do: each+/// row sized its cells independently, so columns drifted and never lined up.+/// Cells (`<td>`/`<th>`) become grid items placed by (row, column) with+/// colspan/rowspan mapped to grid spans; `<tr>`/`<tbody>`/`<thead>`/`<tfoot>`+/// do not get their own layout boxes (their backgrounds are not modeled yet).+/// The grid node is created at width:auto here; its final width is set later in+/// `layout_dom` by a two-pass intrinsic measurement (see the table-sizing pass)+/// so the table can grow to fit an unbreakable wide cell the way real tables do.+/// Returns `None` (falling back to the generic path) if the table has no cells.+fn build_table(+ tree: &DomTree,+ id: NodeId,+ taffy_tree: &mut TaffyTree<usize>,+ id_map: &mut HashMap<taffy::NodeId, NodeId>,+ words: &mut HashMap<taffy::NodeId, (NodeId, String)>,+ engine: &mut crate::inline::TextEngine,+ ifc_items: &mut HashMap<NodeId, usize>,+ styles: &HashMap<NodeId, crate::LayoutStyle>,+) -> Option<taffy::NodeId> {+ let style = styles.get(&id)?;+ let mut rows: Vec<NodeId> = Vec::new();+ collect_table_rows(tree, id, &mut rows);+ if rows.is_empty() {+ return None;+ }+ // Bounds so a crafted table cannot exhaust memory or time: `colspan`/+ // `rowspan` and the column count are page-controlled, and the occupancy+ // fill is O(rows x cols) native code that neither the V8 watchdog nor a+ // tokio timeout can interrupt. Real tables never approach these. Rows are+ // capped too, both to bound work and to keep grid line/span indices within+ // taffy's i16/u16 range.+ const MAX_SPAN: usize = 1000;+ const MAX_COLS: usize = 1024;+ const MAX_ROWS: usize = 10000;+ if rows.len() > MAX_ROWS {+ rows.truncate(MAX_ROWS);+ }+ let nrows = rows.len();++ // Assign every cell a (row, column) with a rowspan-occupancy grid so a cell+ // that spans down pushes later rows' cells past the columns it still covers.+ let span_attr = |cid: NodeId, name: &str| -> usize {+ tree.get_node(cid)+ .and_then(|n| n.get_attribute(name).and_then(|v| v.trim().parse::<usize>().ok()))+ .unwrap_or(1)+ };+ let mut occupied: std::collections::HashSet<(usize, usize)> = std::collections::HashSet::new();+ let mut placed: Vec<(NodeId, usize, usize, usize, usize)> = Vec::new();+ let mut ncols = 0usize;+ for (r, &tr) in rows.iter().enumerate() {+ let mut c = 0usize;+ for cid in tree.children(tr) {+ let local = tree.get_node(cid).and_then(|n| n.as_element().map(|e| e.local.to_string()));+ if !matches!(local.as_deref(), Some("td") | Some("th")) {+ continue;+ }+ // A hidden cell is removed from the table model entirely (it must+ // not reserve a column slot, or the surviving cells shift right).+ if styles.get(&cid).map(|s| s.display == crate::Display::None).unwrap_or(false) {+ continue;+ }+ while occupied.contains(&(r, c)) {+ c += 1;+ }+ if c >= MAX_COLS {+ break;+ }+ let cs = span_attr(cid, "colspan").clamp(1, MAX_SPAN);+ // rowspan=0 means "span to the end"; a cell can never span more rows+ // than remain, so clamp both to the rows left (which also bounds the+ // occupancy fill and keeps spans within taffy's range).+ let rs_raw = span_attr(cid, "rowspan");+ let rs = if rs_raw == 0 { nrows - r } else { rs_raw }.clamp(1, nrows - r);+ for dr in 0..rs {+ for dc in 0..cs {+ occupied.insert((r + dr, c + dc));+ }+ }+ placed.push((cid, r, c, rs, cs));+ c += cs;+ ncols = ncols.max(c).min(MAX_COLS);+ }+ }+ if placed.is_empty() || ncols == 0 {+ return None;+ }++ // Build each cell and pin it to its grid area.+ let mut children: Vec<taffy::NodeId> = Vec::new();+ for (cid, r, c, rs, cs) in &placed {+ let Some(cell_node) = build(tree, *cid, taffy_tree, id_map, words, engine, ifc_items, styles) else {+ continue;+ };+ if let Ok(cur) = taffy_tree.style(cell_node) {+ let mut cstyle = cur.clone();+ cstyle.grid_row = taffy::Line { start: line((*r as i16) + 1), end: span(*rs as u16) };+ cstyle.grid_column = taffy::Line { start: line((*c as i16) + 1), end: span(*cs as u16) };+ // Grid does the sizing; a leftover flex_grow from the flex-table+ // heuristic would be ignored anyway, but clear it to be explicit.+ cstyle.flex_grow = 0.0;+ let _ = taffy_tree.set_style(cell_node, cstyle);+ }+ children.push(cell_node);+ }+ if children.is_empty() {+ return None;+ }++ // The grid container inherits the table's own box (border, padding,+ // background, margin) but is forced to width:auto so the intrinsic-sizing+ // pass in layout_dom can measure content before choosing the used width.+ let col = || {+ taffy::GridTemplateComponent::Single(taffy::MinMax {+ min: taffy::MinTrackSizingFunction::min_content(),+ max: taffy::MaxTrackSizingFunction::max_content(),+ })+ };+ let row_track = || {+ taffy::GridTemplateComponent::Single(taffy::MinMax {+ min: taffy::MinTrackSizingFunction::auto(),+ max: taffy::MaxTrackSizingFunction::auto(),+ })+ };+ let mut tstyle = to_taffy_style(style);+ tstyle.display = Display::Grid;+ // A percentage width resolves against the container, so keep it and let the+ // used-width pass leave it to taffy. Any other width (px or auto) is forced+ // to auto here so that pass can measure content before choosing the width.+ if !matches!(style.width, crate::Dimension::Percent(_)) {+ tstyle.size.width = Dimension::auto();+ }+ tstyle.grid_template_columns = (0..ncols).map(|_| col()).collect();+ tstyle.grid_template_rows = (0..nrows).map(|_| row_track()).collect();+ if let Some((h, v)) = style.border_spacing {+ tstyle.gap = taffy::Size { width: length(h), height: length(v) };+ }+ let table_node = taffy_tree.new_with_children(tstyle, &children).ok()?;+ id_map.insert(table_node, id);+ Some(table_node)+}+fn build(tree: &DomTree,id: NodeId,- taffy_tree: &mut TaffyTree,+ taffy_tree: &mut TaffyTree<usize>,id_map: &mut HashMap<taffy::NodeId, NodeId>,words: &mut HashMap<taffy::NodeId, (NodeId, String)>,+ engine: &mut crate::inline::TextEngine,+ ifc_items: &mut HashMap<NodeId, usize>,styles: &HashMap<NodeId, crate::LayoutStyle>,) -> Option<taffy::NodeId> {let node = tree.get_node(id)?;@@ -501,8 +1398,32 @@ fn build(if style.display == crate::Display::None {return None;}++ // Real table layout: a <table> becomes a CSS grid so columns negotiate+ // across rows (the flex approximation could not) and colspan/rowspan map to+ // grid spans. Falls through to the generic path only if the table has no+ // usable rows/cells.+ if _name.local.as_ref() == "table" {+ if let Some(node) = build_table(tree, id, taffy_tree, id_map, words, engine, ifc_items, styles) {+ return Some(node);+ }+ }+let mut taffy_style = to_taffy_style(style);+ // If this container is a pure-text inline formatting context, collapse its+ // whole subtree to one leaf shaped and line-broken by cosmic-text (real+ // text layout), sized on demand by the measure function. This is the fast,+ // correct path for paragraphs/headings/labels/cells of text; the flex-wrap+ // approximation below only handles the leftovers (mixed inline + atomic+ // boxes, and layout-only builds where `try_build` always declines).+ if let Some(item) = engine.try_build(tree, id, styles) {+ let leaf = taffy_tree.new_leaf_with_context(taffy_style, item).ok()?;+ id_map.insert(leaf, id);+ ifc_items.insert(id, item);+ return Some(leaf);+ }+// Taffy has no real inline formatting context: its native Block layout// treats every direct child as its own full-width block box, stacked// vertically. That is correct when a block's children are other block@@ -513,19 +1434,67 @@ fn build(// width. Approximate that inline formatting context by promoting such// blocks to a wrapping flex row, so text and inline elements actually// flow together on shared lines instead of each getting its own row.- if style.display == crate::Display::Block && has_inline_content(tree, id, styles) {+ //+ // The same fix applies to `<td>`/`<th>` (and any other UA default that+ // stacks its children in a flex column rather than taffy's Block mode):+ // without it, a text node's per-word leaves (see `build_text_words`)+ // become direct children of a column-direction flex container and each+ // word lands on its own line, one word per row, instead of wrapping+ // several words per line the way inline text actually flows.+ let stacks_children_vertically = style.display == crate::Display::Block+ || (style.display == crate::Display::Flex && style.flex_direction == Some(taffy::FlexDirection::Column));+ let has_inline_ish_content =+ has_inline_content(tree, id, styles) || style.before_content.is_some() || style.after_content.is_some();+ if stacks_children_vertically && has_inline_ish_content {taffy_style.display = taffy::style::Display::Flex;taffy_style.flex_direction = taffy::FlexDirection::Row;taffy_style.flex_wrap = taffy::FlexWrap::Wrap;++ // Before promotion, `align_items` was the horizontal-position stand-in+ // for a column container (from `text-align` or `<center>`; see+ // `style::apply_value`'s "text-align" arm): correct there, since a+ // column's cross axis is horizontal. The promoted container's *main*+ // axis is horizontal instead, so that same "where should content sit+ // horizontally" intent now belongs on `justify_content`, not+ // `align_items` — otherwise e.g. `text-align: right` shoves wrapped+ // text to the bottom of its line (the new cross axis) rather than to+ // the right. Real `justify-content` from actual CSS wins if present.+ if style.justify_content.is_none() {+ taffy_style.justify_content = match style.align_items {+ Some(taffy::AlignItems::FLEX_END) => Some(taffy::JustifyContent::FLEX_END),+ Some(taffy::AlignItems::CENTER) => Some(taffy::JustifyContent::CENTER),+ _ => taffy_style.justify_content,+ };+ }+ taffy_style.align_items = Some(taffy::AlignItems::FLEX_START);}- let dom_children = tree.children(id);+ let mut dom_children = tree.children(id);+ // In a grid formatting context, whitespace-only text between items does not+ // generate an anonymous grid item (CSS Grid). taffy 0.12 places each stray+ // whitespace text node in its own cell, which offsets every real item, so a+ // Tailwind `grid-cols-3` block with newlines between its children lays out+ // diagonally instead of in one row (this collapsed the whole modern+ // framework cluster after the taffy upgrade). Drop them before building.+ if style.display == crate::Display::Grid {+ dom_children.retain(|&cid| {+ tree.get_node(cid).map_or(false, |n| n.is_element()) || !tree.text_content(cid).trim().is_empty()+ });+ }let has_float_child = dom_children.iter().any(|&cid| styles.get(&cid).map(|s| s.float.is_some()).unwrap_or(false));- let child_ids: Vec<taffy::NodeId> = if has_float_child {- build_children_with_float_zone(tree, &dom_children, taffy_tree, id_map, words, styles)+ let mut child_ids: Vec<taffy::NodeId> = if has_float_child {+ build_children_with_float_zone(tree, &dom_children, taffy_tree, id_map, words, engine, ifc_items, styles)} else {- dom_children.into_iter().flat_map(|cid| build_any(tree, cid, taffy_tree, id_map, words, styles)).collect()+ dom_children.into_iter().flat_map(|cid| build_any(tree, cid, taffy_tree, id_map, words, engine, ifc_items, styles)).collect()};+ if let Some(content) = &style.before_content {+ let mut leaves = build_pseudo_content(id, content, style, taffy_tree, words);+ leaves.append(&mut child_ids);+ child_ids = leaves;+ }+ if let Some(content) = &style.after_content {+ child_ids.append(&mut build_pseudo_content(id, content, style, taffy_tree, words));+ }let taffy_id = if child_ids.is_empty() {taffy_tree.new_leaf(taffy_style).ok()?@@ -548,12 +1517,85 @@ fn build(/// common real-world shape: a floated image or infobox near the top of an/// article, sitting beside the intro text, with the rest of the content/// (starting at the next section heading) running full width beneath it.+/// Rough height budget for a float with no explicit size and no images+/// (an icon-only or empty float, rare in practice): enough for a couple of+/// lines of caption-sized text without being so generous it drags in a+/// whole section the way an unbounded zone did.+const DEFAULT_FLOAT_HEIGHT_ESTIMATE: f32 = 200.0;++/// Estimate a float's rendered height in CSS px, for bounding how many flow+/// siblings should wrap alongside it (see `build_children_with_float_zone`).+/// Real layout hasn't run yet at this point (we're still building the taffy+/// tree), so this can only approximate: prefer an explicit height on the+/// float itself, else sum the explicit heights of descendant `<img>`s (the+/// common `<figure><img height=".."><figcaption>` thumbnail shape) plus a+/// text-based estimate of the float's own content (the common tall-infobox+/// shape, where the height comes from many rows of text rather than a+/// single image).+fn estimate_float_height(tree: &DomTree, float_id: NodeId, styles: &HashMap<NodeId, crate::LayoutStyle>) -> f32 {+ if let Some(crate::Dimension::Px(h)) = styles.get(&float_id).map(|s| s.height) {+ return h;+ }+ let image_height: f32 = tree+ .descendants(float_id)+ .into_iter()+ .filter(|&id| {+ tree.get_node(id).and_then(|n| n.as_element().map(|e| e.local.to_string())).as_deref() == Some("img")+ })+ .filter_map(|id| match styles.get(&id).map(|s| s.height) {+ Some(crate::Dimension::Px(h)) => Some(h),+ _ => None,+ })+ .sum();+ const ASSUMED_FLOAT_WIDTH: f32 = 280.0;+ let text_height = estimate_text_height(tree, float_id, styles, ASSUMED_FLOAT_WIDTH);+ (image_height + text_height).max(DEFAULT_FLOAT_HEIGHT_ESTIMATE)+}++/// Estimate how tall `id`'s text content would render at `assumed_width`,+/// using the same average-character-width heuristic as the layout-only+/// (non-`paint`) text sizing fallback. Used only to bound the float-wrapping+/// zone (see `build_children_with_float_zone`), where the real available+/// width is not yet known, so this is deliberately approximate.+fn estimate_text_height(tree: &DomTree, id: NodeId, styles: &HashMap<NodeId, crate::LayoutStyle>, assumed_width: f32) -> f32 {+ let char_count = tree.text_content(id).chars().filter(|c| !c.is_whitespace()).count() as f32;+ if char_count == 0.0 {+ return 0.0;+ }+ let fsize = styles.get(&id).and_then(|s| s.font_size).unwrap_or(16.0);+ const AVG_CHAR_WIDTH_EM: f32 = 0.55;+ let chars_per_line = (assumed_width / (fsize * AVG_CHAR_WIDTH_EM)).max(1.0);+ let lines = (char_count / chars_per_line).ceil().max(1.0);+ lines * fsize * 1.2 + 16.0+}++/// Largest definite (px) width among `id` and its descendants. Used to cap an+/// auto-width floated figure: a Wikipedia thumbnail is `<figure ...><img+/// width=250><figcaption>long text</figcaption></figure>`, and without a cap+/// the caption's unwrapped one-line max-content width (~700px) sizes the float+/// and starves the adjacent flow column to nothing. Real browsers size the+/// figure to the image (display:table) and wrap the caption; the image's+/// definite width is the bound that reproduces that.+fn max_definite_descendant_width(tree: &DomTree, id: NodeId, styles: &HashMap<NodeId, crate::LayoutStyle>) -> Option<f32> {+ let mut best: Option<f32> = None;+ for d in tree.descendants(id) {+ if let Some(crate::Dimension::Px(w)) = styles.get(&d).map(|s| s.width.clone()) {+ if w > 0.0 {+ best = Some(best.map_or(w, |b: f32| b.max(w)));+ }+ }+ }+ best+}+fn build_children_with_float_zone(tree: &DomTree,dom_children: &[NodeId],- taffy_tree: &mut TaffyTree,+ taffy_tree: &mut TaffyTree<usize>,id_map: &mut HashMap<taffy::NodeId, NodeId>,words: &mut HashMap<taffy::NodeId, (NodeId, String)>,+ engine: &mut crate::inline::TextEngine,+ ifc_items: &mut HashMap<NodeId, usize>,styles: &HashMap<NodeId, crate::LayoutStyle>,) -> Vec<taffy::NodeId> {let is_float = |cid: NodeId| styles.get(&cid).map(|s| s.float.is_some()).unwrap_or(false);@@ -565,27 +1607,110 @@ fn build_children_with_float_zone(};let Some(float_idx) = dom_children.iter().position(|&cid| is_float(cid)) else {- return dom_children.iter().flat_map(|&cid| build_any(tree, cid, taffy_tree, id_map, words, styles)).collect();+ return dom_children.iter().flat_map(|&cid| build_any(tree, cid, taffy_tree, id_map, words, engine, ifc_items, styles)).collect();};let mut result: Vec<taffy::NodeId> = dom_children[..float_idx].iter()- .flat_map(|&cid| build_any(tree, cid, taffy_tree, id_map, words, styles))+ .flat_map(|&cid| build_any(tree, cid, taffy_tree, id_map, words, engine, ifc_items, styles)).collect();let float_side = styles.get(&dom_children[float_idx]).and_then(|s| s.float);++ // A run of two or more consecutively floated siblings (the classic+ // float-grid idiom: several `float:left; width:N%` boxes forming columns,+ // e.g. craigslist's `.sites .box{float:left;width:23%}` site directory) is+ // not the single-float-beside-flow shape handled below: real float layout+ // places the run side by side, wrapping to a new line when the row fills.+ // Model the run as a wrapping flex row. Whitespace-only text between the+ // floats does not break the run.+ let mut run_end = float_idx + 1;+ let mut float_count = 1usize;+ while run_end < dom_children.len() {+ let cid = dom_children[run_end];+ if styles.get(&cid).and_then(|s| s.float) == float_side {+ float_count += 1;+ run_end += 1;+ } else if tree.get_node(cid).map_or(false, |n| !n.is_element())+ && tree.text_content(cid).trim().is_empty()+ {+ run_end += 1;+ } else {+ break;+ }+ }+ if float_count >= 2 {+ let run_children: Vec<taffy::NodeId> = dom_children[float_idx..run_end]+ .iter()+ .flat_map(|&cid| build_any(tree, cid, taffy_tree, id_map, words, engine, ifc_items, styles))+ .collect();+ let row_style = taffy::Style {+ display: taffy::style::Display::Flex,+ flex_direction: taffy::FlexDirection::Row,+ flex_wrap: taffy::FlexWrap::Wrap,+ align_items: Some(taffy::AlignItems::FLEX_START),+ ..Default::default()+ };+ if let Ok(row) = taffy_tree.new_with_children(row_style, &run_children) {+ result.push(row);+ }+ result.extend(build_children_with_float_zone(+ tree, &dom_children[run_end..], taffy_tree, id_map, words, engine, ifc_items, styles,+ ));+ return result;+ }++ // Stop growing the zone once the flow siblings collected so far would+ // already fill (an estimate of) the float's own height: real float+ // reflow ends when normal-flow content passes the float's bottom edge,+ // not at the next heading regardless of how tall the float actually is.+ // Without this, a short floated thumbnail (a few hundred px) dragged an+ // entire multi-paragraph section into a narrow flow column alongside it+ // — visibly wrong wrapping plus a large empty gap once the (much+ // shorter) float ran out, both from treating "next heading" as the only+ // bound. The estimate is necessarily rough (actual available width is a+ // taffy layout result we don't have yet at tree-build time), but even an+ // approximate bound beats an unbounded one.+ let float_height_budget = estimate_float_height(tree, dom_children[float_idx], styles);+ const ASSUMED_FLOW_WIDTH: f32 = 500.0;let mut zone_end = float_idx + 1;+ let mut flow_height_estimate = 0.0f32;while zone_end < dom_children.len() && !is_heading(dom_children[zone_end]) && !is_float(dom_children[zone_end]) {+ flow_height_estimate += estimate_text_height(tree, dom_children[zone_end], styles, ASSUMED_FLOW_WIDTH);zone_end += 1;+ if flow_height_estimate >= float_height_budget {+ break;+ }}// The float itself is always an element (only elements get style// entries, and `is_float` above required one), so a direct `build` call// is correct here; only its flow siblings need the word-splitting `build_any`.- let float_taffy = build(tree, dom_children[float_idx], taffy_tree, id_map, words, styles);+ let float_taffy = build(tree, dom_children[float_idx], taffy_tree, id_map, words, engine, ifc_items, styles);+ // Cap an auto-width float at its widest definite-width descendant so a long+ // wrappable caption cannot inflate it to the caption's one-line max-content+ // width and starve the flow column beside it (the Wikipedia-thumbnail /+ // article-body-collapses-to-one-word-per-line bug). Only when the float is+ // itself auto-width and actually contains such a box; text-only floats+ // (pull quotes, sized infoboxes) are left to normal shrink-to-fit.+ if let Some(float_id) = float_taffy {+ let float_dom = dom_children[float_idx];+ let float_auto = styles.get(&float_dom).map(|s| matches!(s.width, crate::Dimension::Auto)).unwrap_or(true);+ if float_auto {+ if let Some(w) = max_definite_descendant_width(tree, float_dom, styles) {+ if let Ok(cur) = taffy_tree.style(float_id) {+ let mut st = cur.clone();+ // A little slack for the figure's own border/padding so the+ // image is not clipped; the caption still wraps to ~image width.+ st.max_size.width = taffy::Dimension::length(w + 12.0);+ let _ = taffy_tree.set_style(float_id, st);+ }+ }+ }+ }let flow_taffy: Vec<taffy::NodeId> = dom_children[float_idx + 1..zone_end].iter()- .flat_map(|&cid| build_any(tree, cid, taffy_tree, id_map, words, styles))+ .flat_map(|&cid| build_any(tree, cid, taffy_tree, id_map, words, engine, ifc_items, styles)).collect();match float_taffy {@@ -595,8 +1720,8 @@ fn build_children_with_float_zone(flex_direction: taffy::FlexDirection::Column,flex_grow: 1.0,flex_shrink: 1.0,- flex_basis: taffy::Dimension::Length(0.0),- min_size: taffy::Size { width: taffy::Dimension::Length(0.0), height: taffy::Dimension::Auto },+ flex_basis: taffy::Dimension::length(0.0),+ min_size: taffy::Size { width: taffy::Dimension::length(0.0), height: taffy::Dimension::auto() },..Default::default()};let flow_column = if flow_taffy.is_empty() {@@ -608,7 +1733,7 @@ fn build_children_with_float_zone(let row_style = taffy::Style {display: taffy::style::Display::Flex,flex_direction: taffy::FlexDirection::Row,- align_items: Some(taffy::AlignItems::FlexStart),+ align_items: Some(taffy::AlignItems::FLEX_START),..Default::default()};let row_children: Vec<taffy::NodeId> = match float_side {@@ -628,7 +1753,7 @@ fn build_children_with_float_zone(result.extend(dom_children[zone_end..].iter()- .flat_map(|&cid| build_any(tree, cid, taffy_tree, id_map, words, styles)),+ .flat_map(|&cid| build_any(tree, cid, taffy_tree, id_map, words, engine, ifc_items, styles)),);result}diff --git a/crates/obscura-render/src/inline.rs b/crates/obscura-render/src/inline.rsnew file mode 100644index 00000000..ef648f95--- /dev/null+++ b/crates/obscura-render/src/inline.rs@@ -0,0 +1,532 @@+//! Real inline text layout via cosmic-text (HarfBuzz-class shaping through+//! rustybuzz + UAX#14 line breaking), replacing the earlier approximation+//! that split each text node into one taffy flex item per word.+//!+//! The model matches how real browsers separate formatting contexts: taffy+//! lays out the *block/flex/grid* boxes, and an *inline formatting context*+//! (a box whose children are all inline-level text/spans) collapses to a+//! single taffy leaf whose measure function line-breaks its shaped text at+//! whatever width taffy offers. Line wrapping, alignment, and intrinsic+//! sizing then come from a real text engine instead of flexbox tricks.+//!+//! Fonts are loaded from embedded bytes only, never the OS, so layout is+//! byte-for-byte deterministic across hosts (the whole engine's guarantee).++use std::sync::Arc;++use cosmic_text::{Align, Attrs, Buffer, Color, Family, FontSystem, Metrics, Shaping, Style, SwashCache, Weight, Wrap};++use obscura_dom::tree::{DomTree, NodeId};++use crate::{Display, LayoutStyle, Rect, TextTransform};++static REGULAR: &[u8] = include_bytes!("../assets/dejavu-sans.ttf");+static BOLD: &[u8] = include_bytes!("../assets/dejavu-sans-bold.ttf");+static OBLIQUE: &[u8] = include_bytes!("../assets/dejavu-sans-oblique.ttf");+static BOLD_OBLIQUE: &[u8] = include_bytes!("../assets/dejavu-sans-boldoblique.ttf");++const FAMILY: &str = "DejaVu Sans";+/// `line-height: normal` as a multiple of font-size. Browsers derive this+/// from font metrics (~1.15-1.2 for DejaVu Sans); 1.2 matches closely.+const NORMAL_LINE_HEIGHT: f32 = 1.2;+/// Underline is flagged per glyph through cosmic-text's `metadata` field.+const META_UNDERLINE: usize = 1;++/// One inline formatting context: a shaped cosmic-text buffer plus where to+/// paint it (filled in after layout).+pub struct InlineItem {+ buffer: Buffer,+ /// Content-box top-left in viewport coordinates, set by `finalize`.+ origin: (f32, f32),+ /// Ancestor `overflow: hidden` clip, set by `finalize`.+ clip: Option<Rect>,+}++/// Owns the font set and shaping caches for one render pass, plus every+/// inline formatting context discovered while building the tree. Lives in+/// [`crate::DomLayout`] so paint can rasterize the shaped glyphs.+pub struct TextEngine {+ font_system: FontSystem,+ swash: SwashCache,+ items: Vec<InlineItem>,+}++impl Default for TextEngine {+ fn default() -> Self {+ Self::new()+ }+}++impl TextEngine {+ pub fn new() -> Self {+ // Build a database from our four embedded faces only. Never call+ // load_system_fonts: a host's font set would make layout differ+ // machine to machine and add a multi-millisecond startup scan.+ let mut db = cosmic_text::fontdb::Database::new();+ for bytes in [REGULAR, BOLD, OBLIQUE, BOLD_OBLIQUE] {+ db.load_font_source(cosmic_text::fontdb::Source::Binary(Arc::new(bytes)));+ }+ db.set_sans_serif_family(FAMILY);+ let font_system = FontSystem::new_with_locale_and_db("en-US".to_string(), db);+ TextEngine { font_system, swash: SwashCache::new(), items: Vec::new() }+ }++ /// Number of inline formatting contexts collected (for debug/stats).+ pub fn len(&self) -> usize {+ self.items.len()+ }+ pub fn is_empty(&self) -> bool {+ self.items.is_empty()+ }++ /// Build an inline formatting context for `id`'s subtree if it is one we+ /// can collapse to shaped text (see [`is_pure_text_ifc`]); returns the+ /// item index to store as the leaf's taffy context. `None` means the+ /// container is not a pure-text IFC and should build through the normal+ /// (block / flex / word-split) path.+ pub fn try_build(&mut self, tree: &DomTree, id: NodeId, styles: &std::collections::HashMap<NodeId, LayoutStyle>) -> Option<usize> {+ if !is_pure_text_ifc(tree, id, styles) {+ return None;+ }+ let base = styles.get(&id)?;+ let base_size = base.font_size.unwrap_or(16.0);+ let default_color = base.color.unwrap_or([0, 0, 0, 255]);++ let root_transform = base.text_transform.unwrap_or(TextTransform::None);+ let root_underline = base.underline.unwrap_or(false);+ let root_italic = base.font_style_italic.unwrap_or(false);+ let root_bold = base.font_weight.as_deref() == Some("bold");+ let mut spans: Vec<(String, SpanAttrs)> = Vec::new();+ let mut collector = Collector { last_was_space: true };+ let ctx = SpanCtx { color: default_color, bold: root_bold, italic: root_italic, underline: root_underline, transform: root_transform };+ collect_spans(tree, id, styles, ctx, &mut spans, &mut collector);+ // Trim a single trailing space so it does not widen the last line.+ if let Some((text, _)) = spans.last_mut() {+ if text.ends_with(' ') {+ text.pop();+ }+ }+ if spans.iter().all(|(t, _)| t.trim().is_empty()) {+ return None;+ }++ // Real `line-height` drives vertical rhythm; a fixed ratio made+ // real-site prose (e.g. Wikipedia's 1.6) noticeably tighter than+ // Chromium. `normal` is font-relative; ~1.2 matches DejaVu closely.+ let line_h = match base.line_height {+ Some(crate::LineHeight::Px(px)) => px,+ Some(crate::LineHeight::Ratio(r)) => base_size * r,+ _ => base_size * NORMAL_LINE_HEIGHT,+ };+ // cosmic-text asserts (an uncatchable process abort) if font size OR+ // line height is 0. `font-size:0` is a common whitespace-collapse trick+ // and drives both to 0, so floor both at 1px here. The glyphs stay+ // ~invisible, matching the intent, and one page can never abort a worker.+ let cosmic_size = base_size.max(1.0);+ let metrics = Metrics::new(cosmic_size, line_h.max(cosmic_size).ceil());+ let mut buffer = Buffer::new(&mut self.font_system, metrics);+ // Break only at word boundaries, never mid-word. This keeps the+ // min-content width (measured at width 0) equal to the longest word,+ // so a table/flex column never squeezes narrower than a whole word+ // and forces an ugly mid-word break; a single word wider than its+ // column overflows instead, matching normal `overflow-wrap: normal`.+ buffer.set_wrap(&mut self.font_system, Wrap::Word);+ // Always Advanced shaping: Basic mis-maps per-span attribute+ // boundaries in cosmic-text 0.12 (a multi-color run like body text+ // with links ends up coloring the wrong glyphs), and shaping is a+ // small fraction of a page's CSS-cascade-dominated render time.+ let rich = spans.iter().map(|(t, a)| (t.as_str(), a.to_attrs()));+ buffer.set_rich_text(&mut self.font_system, rich, Attrs::new().family(Family::Name(FAMILY)), Shaping::Advanced);++ let align = match base.align_items {+ Some(taffy::AlignItems::CENTER) => Some(Align::Center),+ Some(taffy::AlignItems::FLEX_END) => Some(Align::End),+ _ => None,+ };+ if let Some(a) = align {+ for line in buffer.lines.iter_mut() {+ line.set_align(Some(a));+ }+ }++ let idx = self.items.len();+ self.items.push(InlineItem { buffer, origin: (0.0, 0.0), clip: None });+ Some(idx)+ }++ /// Measure the inline context `idx` at `width` (content-box width, or+ /// None for max-content), returning its shaped (width, height). Called by+ /// taffy's measure function during layout.+ pub fn measure(&mut self, idx: usize, width: Option<f32>) -> (f32, f32) {+ let TextEngine { font_system, items, .. } = self;+ let item = &mut items[idx];+ item.buffer.set_size(font_system, width.map(|w| w.max(0.0)), None);+ item.buffer.shape_until_scroll(font_system, false);+ buffer_size(&item.buffer)+ }++ /// After layout, pin each context to its final content-box origin and+ /// clip, reshaping once at the resolved width so paint draws the same+ /// line breaks the box was sized for.+ pub fn finalize(&mut self, idx: usize, content_origin: (f32, f32), content_width: f32, clip: Option<Rect>) {+ let TextEngine { font_system, items, .. } = self;+ let item = &mut items[idx];+ item.buffer.set_size(font_system, Some(content_width.max(0.0)), None);+ item.buffer.shape_until_scroll(font_system, false);+ item.origin = content_origin;+ item.clip = clip;+ }+}++/// A run of same-styled inline text.+#[derive(Clone, PartialEq)]+struct SpanAttrs {+ bold: bool,+ italic: bool,+ underline: bool,+ color: [u8; 4],+}++impl SpanAttrs {+ fn to_attrs(&self) -> Attrs<'_> {+ let mut a = Attrs::new().family(Family::Name(FAMILY));+ a = a.weight(if self.bold { Weight::BOLD } else { Weight::NORMAL });+ a = a.style(if self.italic { Style::Italic } else { Style::Normal });+ a = a.color(Color::rgba(self.color[0], self.color[1], self.color[2], self.color[3]));+ // Underline has no native cosmic-text attribute; carry it through the+ // per-glyph metadata so paint can stroke it (see `paint_item`).+ a = a.metadata(if self.underline { META_UNDERLINE } else { 0 });+ a+ }+}++/// Inherited inline context threaded down the subtree while collecting spans.+#[derive(Clone, Copy)]+struct SpanCtx {+ color: [u8; 4],+ bold: bool,+ italic: bool,+ underline: bool,+ transform: TextTransform,+}++struct Collector {+ last_was_space: bool,+}++/// DFS the inline subtree, appending whitespace-collapsed text runs. Adjacent+/// runs with identical attributes are merged so cosmic-text sees the fewest+/// spans. Collapsing spans HTML's insignificant whitespace (runs of spaces,+/// tabs, and newlines fold to one space; leading space at the start of the+/// context is dropped) exactly as `white-space: normal` requires.+fn collect_spans(+ tree: &DomTree,+ id: NodeId,+ styles: &std::collections::HashMap<NodeId, LayoutStyle>,+ ctx: SpanCtx,+ out: &mut Vec<(String, SpanAttrs)>,+ c: &mut Collector,+) {+ for cid in tree.children(id) {+ let Some(node) = tree.get_node(cid) else { continue };+ match &node.data {+ obscura_dom::tree::NodeData::Text { contents } => {+ let attrs = SpanAttrs { bold: ctx.bold, italic: ctx.italic, underline: ctx.underline, color: ctx.color };+ push_text(contents, ctx.transform, &attrs, out, c);+ }+ _ => {+ let Some(elem) = node.as_element() else { continue };+ let style = styles.get(&cid);+ if style.map(|s| s.display == Display::None).unwrap_or(false) {+ continue;+ }+ if elem.local.as_ref() == "br" {+ out.push(("\n".to_string(), SpanAttrs { bold: ctx.bold, italic: ctx.italic, underline: ctx.underline, color: ctx.color }));+ c.last_was_space = true;+ continue;+ }+ let child = SpanCtx {+ color: style.and_then(|s| s.color).unwrap_or(ctx.color),+ bold: ctx.bold || style.map(|s| s.font_weight.as_deref() == Some("bold")).unwrap_or(false),+ italic: ctx.italic || style.and_then(|s| s.font_style_italic).unwrap_or(false),+ // Underline propagates in: an ancestor's underline covers+ // descendant text; an element only sets its own via CSS.+ underline: ctx.underline || style.and_then(|s| s.underline).unwrap_or(false),+ transform: style.and_then(|s| s.text_transform).unwrap_or(ctx.transform),+ };+ collect_spans(tree, cid, styles, child, out, c);+ }+ }+ }+}++fn push_text(raw: &str, transform: TextTransform, attrs: &SpanAttrs, out: &mut Vec<(String, SpanAttrs)>, c: &mut Collector) {+ let mut buf = String::new();+ let mut at_word_start = c.last_was_space;+ for ch in raw.chars() {+ if ch.is_whitespace() {+ if !c.last_was_space {+ buf.push(' ');+ c.last_was_space = true;+ }+ at_word_start = true;+ } else {+ match transform {+ TextTransform::Uppercase => buf.extend(ch.to_uppercase()),+ TextTransform::Lowercase => buf.extend(ch.to_lowercase()),+ TextTransform::Capitalize if at_word_start => buf.extend(ch.to_uppercase()),+ _ => buf.push(ch),+ }+ c.last_was_space = false;+ at_word_start = false;+ }+ }+ if buf.is_empty() {+ return;+ }+ if let Some((last_text, last_attrs)) = out.last_mut() {+ if last_attrs == attrs {+ last_text.push_str(&buf);+ return;+ }+ }+ out.push((buf, attrs.clone()));+}++/// Total shaped size of a buffer: widest line, and the bottom of the last line.+fn buffer_size(buffer: &Buffer) -> (f32, f32) {+ let mut w = 0.0f32;+ let mut h = 0.0f32;+ for run in buffer.layout_runs() {+ w = w.max(run.line_w);+ h = h.max(run.line_top + run.line_height);+ }+ (w.ceil(), h.ceil())+}++/// Does `id` establish an inline formatting context made purely of text and+/// plain inline formatting (no atomic inline boxes, no block children, no+/// inline element carrying its own box)? Such a container collapses cleanly+/// to one shaped buffer; anything else keeps the general build path.+fn is_pure_text_ifc(tree: &DomTree, id: NodeId, styles: &std::collections::HashMap<NodeId, LayoutStyle>) -> bool {+ let Some(style) = styles.get(&id) else { return false };+ // Only containers that lay their children out in normal flow (block, or+ // the flex-column stand-ins our UA sheet uses for td/th/center). A real+ // flex/grid row with inline children is rare and better left to taffy.+ let flow = style.display == Display::Block+ || (style.display == Display::Flex && style.flex_direction == Some(taffy::FlexDirection::Column));+ if !flow {+ return false;+ }+ let mut has_text = false;+ let children = tree.children(id);+ if children.is_empty() {+ return false;+ }+ for cid in &children {+ if !inline_child_ok(tree, *cid, styles, &mut has_text) {+ return false;+ }+ }+ has_text+}++/// Replaced / atomic-inline tags: their box does not contain text, so folding+/// one into a shaped buffer would drop its content entirely. A subtree that+/// contains one is never a pure-text IFC (it keeps the general build path,+/// where the element gets a real taffy box). This is by tag, not display, so a+/// stylesheet setting `img{display:inline}` cannot trick us into folding it.+fn is_replaced(local: &str) -> bool {+ matches!(+ local,+ "img" | "svg" | "canvas" | "video" | "audio" | "iframe" | "embed"+ | "object" | "input" | "textarea" | "select" | "button" | "progress"+ | "meter"+ )+}++/// Is `cid` (and its whole subtree) inline-level, in-flow content safe to fold+/// into a shaped buffer? Sets `has_text` if it contributes any non-whitespace+/// text. Inline wrappers (`<a>`, `<span>`, `<b>`, `<code>`, `<sup>`, ...) are+/// accepted and recursed into even when they carry a background or border of+/// their own: keeping the whole paragraph as one shaped run (correct wrapping+/// plus per-span color/weight/style/underline that `collect_spans` threads) is+/// worth losing an inline decoration, and it avoids the taffy-discouraged+/// flex word-promotion path that breaks real prose wrapping. Only boxes that+/// genuinely cannot fold are rejected: replaced/atomic elements, block-level+/// children, floats, out-of-flow positioned boxes, and elements with generated+/// content (which would be lost).+fn inline_child_ok(tree: &DomTree, cid: NodeId, styles: &std::collections::HashMap<NodeId, LayoutStyle>, has_text: &mut bool) -> bool {+ let Some(node) = tree.get_node(cid) else { return true };+ match &node.data {+ obscura_dom::tree::NodeData::Text { contents } => {+ if !contents.trim().is_empty() {+ *has_text = true;+ }+ true+ }+ obscura_dom::tree::NodeData::Element { .. } => {+ let Some(elem) = node.as_element() else { return true };+ let Some(style) = styles.get(&cid) else { return false };+ if style.display == Display::None {+ return true; // removed from flow; ignore its subtree+ }+ if elem.local.as_ref() == "br" {+ return true;+ }+ // A replaced element or an atomic inline-block has its own box with+ // non-text content; it must stay a real taffy box (keep flex path).+ if is_replaced(elem.local.as_ref()) || style.is_inline_block {+ return false;+ }+ // Only genuinely inline-level, in-flow boxes fold. A block-level+ // child, a float, or an out-of-flow positioned box each needs the+ // general path; so does an element with generated ::before/::after+ // content (lost if folded) or an overflow clip of its own.+ let foldable_inline = style.display == Display::Inline+ && style.position.is_none()+ && style.float.is_none()+ && !style.overflow_hidden+ && style.before_content.is_none()+ && style.after_content.is_none();+ if !foldable_inline {+ return false;+ }+ for gc in tree.children(cid) {+ if !inline_child_ok(tree, gc, styles, has_text) {+ return false;+ }+ }+ true+ }+ _ => true,+ }+}++/// Content-box origin for a container whose border box is `rect`, i.e. inside+/// its border and padding: where inline text actually starts.+pub fn content_origin(rect: &Rect, style: &LayoutStyle) -> (f32, f32) {+ (rect.x + style.border.left + style.padding.left, rect.y + style.border.top + style.padding.top)+}++pub fn content_width(rect: &Rect, style: &LayoutStyle) -> f32 {+ (rect.width - style.border.left - style.border.right - style.padding.left - style.padding.right).max(0.0)+}++impl TextEngine {+ /// Rasterize inline context `idx` into `pixmap`, honoring its clip. Uses+ /// cosmic-text's swash-backed rasterizer (anti-aliased, per-glyph color+ /// from the span attributes).+ pub fn paint_item(&mut self, idx: usize, pixmap: &mut tiny_skia::Pixmap) {+ let TextEngine { font_system, swash, items } = self;+ let Some(item) = items.get_mut(idx) else { return };+ let (ox, oy) = item.origin;+ let clip = item.clip;+ let pw = pixmap.width() as i32;+ let ph = pixmap.height() as i32;+ let clip_bounds = clip.map(|c| (c.x, c.y, c.x + c.width, c.y + c.height));++ // Collect underline segments before drawing glyphs (both borrow the+ // buffer). Underline is carried per glyph via metadata; group runs of+ // consecutive underlined glyphs on a line into one stroke below the+ // baseline. Done first so the draw() mutable borrow does not overlap.+ let mut underlines: Vec<(f32, f32, f32, f32, [u8; 4])> = Vec::new(); // x0, x1, y, thickness, color+ for run in item.buffer.layout_runs() {+ let base_y = run.line_y;+ let mut seg: Option<(f32, f32, f32, [u8; 4])> = None; // x0, x1, font_size, color+ for g in run.glyphs {+ let underlined = g.metadata == META_UNDERLINE as usize;+ let col = g.color_opt.map(|c| [c.r(), c.g(), c.b(), c.a()]).unwrap_or([0, 0, 0, 255]);+ if underlined {+ match &mut seg {+ Some((_, x1, fs, c)) if *c == col => {+ *x1 = g.x + g.w;+ *fs = fs.max(g.font_size);+ }+ _ => {+ if let Some((x0, x1, fs, c)) = seg.take() {+ underlines.push((x0, x1, base_y + (fs * 0.12).max(1.0), (fs / 14.0).max(1.0), c));+ }+ seg = Some((g.x, g.x + g.w, g.font_size, col));+ }+ }+ } else if let Some((x0, x1, fs, c)) = seg.take() {+ underlines.push((x0, x1, base_y + (fs * 0.12).max(1.0), (fs / 14.0).max(1.0), c));+ }+ }+ if let Some((x0, x1, fs, c)) = seg.take() {+ underlines.push((x0, x1, base_y + (fs * 0.12).max(1.0), (fs / 14.0).max(1.0), c));+ }+ }++ // Fallback color if a glyph carries none (shouldn't happen: every span+ // sets one), black.+ let default = Color::rgba(0, 0, 0, 255);+ let pixels = pixmap.pixels_mut();+ item.buffer.draw(font_system, swash, default, |gx, gy, gw, gh, color| {+ let a = color.a() as u32;+ if a == 0 {+ return;+ }+ let (r, g, b) = (color.r(), color.g(), color.b());+ for dy in 0..gh as i32 {+ for dx in 0..gw as i32 {+ let px = ox as i32 + gx + dx;+ let py = oy as i32 + gy + dy;+ if let Some((cx0, cy0, cx1, cy1)) = clip_bounds {+ if (px as f32) < cx0 || (px as f32) >= cx1 || (py as f32) < cy0 || (py as f32) >= cy1 {+ continue;+ }+ }+ if px < 0 || px >= pw || py < 0 || py >= ph {+ continue;+ }+ let idx = (py * pw + px) as usize;+ let dst = pixels[idx];+ let sa = a;+ let sr = (r as u32 * sa) / 255;+ let sg = (g as u32 * sa) / 255;+ let sb = (b as u32 * sa) / 255;+ let inv = 255 - sa;+ let out_a = sa + (dst.alpha() as u32 * inv / 255);+ if out_a == 0 {+ continue;+ }+ let out_r = sr + (dst.red() as u32 * inv / 255);+ let out_g = sg + (dst.green() as u32 * inv / 255);+ let out_b = sb + (dst.blue() as u32 * inv / 255);+ pixels[idx] = tiny_skia::PremultipliedColorU8::from_rgba(out_r as u8, out_g as u8, out_b as u8, out_a as u8)+ .unwrap_or(dst);+ }+ }+ });++ // Stroke the underline segments (opaque; text is already drawn above).+ for (x0, x1, y, thick, col) in underlines {+ let t = thick.max(1.0).round() as i32;+ for dt in 0..t {+ let py = oy as i32 + y as i32 + dt;+ if py < 0 || py >= ph {+ continue;+ }+ if let Some((_, cy0, _, cy1)) = clip_bounds {+ if (py as f32) < cy0 || (py as f32) >= cy1 {+ continue;+ }+ }+ for px in (ox + x0) as i32..(ox + x1) as i32 {+ if px < 0 || px >= pw {+ continue;+ }+ if let Some((cx0, _, cx1, _)) = clip_bounds {+ if (px as f32) < cx0 || (px as f32) >= cx1 {+ continue;+ }+ }+ let i = (py * pw + px) as usize;+ pixels[i] = tiny_skia::PremultipliedColorU8::from_rgba(col[0], col[1], col[2], 255).unwrap_or(pixels[i]);+ }+ }+ }+ }+}diff --git a/crates/obscura-render/src/lib.rs b/crates/obscura-render/src/lib.rsindex 87f66103..560f2c60 100644--- a/crates/obscura-render/src/lib.rs+++ b/crates/obscura-render/src/lib.rs@@ -20,13 +20,40 @@ pub mod style;pub use style::compute_style;pub mod dom;-pub use dom::{layout_dom, DomLayout};+pub use dom::{layout_dom, layout_dom_with_images, DomLayout};#[cfg(feature = "paint")]mod paint;#[cfg(feature = "paint")]pub use paint::{paint_dom, screenshot_png};+// Real inline text layout (cosmic-text) lives behind the paint feature; the+// layout-only build keeps the lighter word-split geometry. The stub lets+// `dom.rs` name `inline::TextEngine` and call `try_build` unconditionally.+#[cfg(feature = "paint")]+pub mod inline;++#[cfg(not(feature = "paint"))]+pub mod inline {+ use obscura_dom::tree::{DomTree, NodeId};+ use std::collections::HashMap;++ #[derive(Default)]+ pub struct TextEngine;++ impl TextEngine {+ pub fn new() -> Self {+ TextEngine+ }+ /// Layout-only builds have no shaper, so no container is ever treated+ /// as a cosmic-text inline formatting context: the word-split path+ /// handles text geometry for `getBoundingClientRect`.+ pub fn try_build(&mut self, _tree: &DomTree, _id: NodeId, _styles: &HashMap<NodeId, crate::LayoutStyle>) -> Option<usize> {+ None+ }+ }+}+/// An axis-aligned rectangle in CSS pixels, relative to the containing block.#[derive(Debug, Clone, Copy, Default, PartialEq)]pub struct Rect {@@ -51,6 +78,16 @@ impl Rect {None}}++ /// The smallest rect covering both. Used to derive a table row/section box+ /// from its cells, since `<tr>`/`<tbody>` are not laid out as taffy boxes.+ pub fn union(&self, other: &Rect) -> Rect {+ let x0 = self.x.min(other.x);+ let y0 = self.y.min(other.y);+ let x1 = (self.x + self.width).max(other.x + other.width);+ let y1 = (self.y + self.height).max(other.y + other.height);+ Rect { x: x0, y: y0, width: x1 - x0, height: y1 - y0 }+ }}/// Per-edge box values (margin / padding / border) in CSS pixels.@@ -80,7 +117,37 @@ pub enum Dimension {#[default]Auto,Px(f32),+ /// 0.0-1.0 fraction of the containing block.Percent(f32),+ /// Font-relative and viewport-relative units, kept unresolved at parse+ /// time (the element font-size and viewport are not known then) and+ /// resolved to `Px` during `dom::layout_dom`'s top-down pass via+ /// [`Dimension::resolve`]. Resolving em/rem/vw against a hardcoded 16px at+ /// parse time (the old behavior) silently corrupted every relative length.+ Em(f32),+ Rem(f32),+ Vw(f32),+ Vh(f32),+ Vmin(f32),+ Vmax(f32),+}++impl Dimension {+ /// Resolve font/viewport-relative units to `Px`. `em_px` is the element's+ /// own font-size, `rem_px` the root's, and `vw`/`vh` are one hundredth of+ /// the viewport width/height. `Px`, `Percent`, and `Auto` pass through+ /// (`Percent` stays for taffy to resolve against the containing block).+ pub fn resolve(self, em_px: f32, rem_px: f32, vw: f32, vh: f32) -> Dimension {+ match self {+ Dimension::Em(v) => Dimension::Px(v * em_px),+ Dimension::Rem(v) => Dimension::Px(v * rem_px),+ Dimension::Vw(v) => Dimension::Px(v * vw),+ Dimension::Vh(v) => Dimension::Px(v * vh),+ Dimension::Vmin(v) => Dimension::Px(v * vw.min(vh)),+ Dimension::Vmax(v) => Dimension::Px(v * vw.max(vh)),+ other => other,+ }+ }}/// The subset of CSS that influences box layout. Expanded in later phases.@@ -89,15 +156,38 @@ pub struct LayoutStyle {pub display: Display,pub width: Dimension,pub height: Dimension,+ /// Whether `width`/`height` was set by an author rule (including an explicit+ /// `auto`). Presentational `width`/`height` HTML attributes are a lower+ /// priority than author CSS, so they apply only when these are false; an+ /// explicit `width:auto` must still suppress a `width="408"` attribute so+ /// the element keeps its aspect-ratio size instead of the intrinsic one.+ pub width_set: bool,+ pub height_set: bool,pub min_width: Dimension,pub min_height: Dimension,pub max_width: Dimension,pub max_height: Dimension,+ /// `aspect-ratio` as width/height, or an image's intrinsic ratio resolved+ /// at layout. Lets a replaced element (or a padding-box card) derive the+ /// missing dimension from the given one, so a `width:100%` image gets a+ /// real height instead of collapsing to zero.+ pub aspect_ratio: Option<f32>,pub margin: Edges,+ /// Which margin sides are `auto` (top, right, bottom, left). `margin: 0+ /// auto` / `margin-inline: auto` centering needs a real Auto margin, which+ /// the f32 `margin` cannot express; this flag drives it at taffy mapping.+ pub margin_auto: [bool; 4],pub padding: Edges,pub border: Edges,+ /// `border-radius` (uniform; the first value of the shorthand). Rounds the+ /// background fill and border. In px after resolution.+ pub border_radius: f32,/// RGBA for the paint step. Parsed always (cheap), used only with `paint`.pub background_color: Option<[u8; 4]>,+ /// `linear-gradient(...)` background: (angle in degrees clockwise from 12+ /// o'clock per CSS, list of (rgba, optional 0..1 stop position)). Modern+ /// hero sections use gradients heavily; without this they paint white.+ pub background_gradient: Option<(f32, Vec<([u8; 4], Option<f32>)>)>,/// The first `url(...)` reference from `background`/`background-image`/// (gradients and repeat keywords in the same shorthand are ignored: we/// paint the referenced image, not the gradient layer).@@ -122,6 +212,10 @@ pub struct LayoutStyle {pub color: Option<[u8; 4]>,pub border_color: Option<[u8; 4]>,pub font_size: Option<f32>,+ /// `font-size` given in a font/viewport-relative unit, resolved to+ /// `font_size` (px) during the inheritance pass against the parent and+ /// root font-sizes. `None` when font-size was absolute or unset.+ pub font_size_raw: Option<Dimension>,pub font_weight: Option<String>,pub align_items: Option<taffy::AlignItems>,pub flex_direction: Option<taffy::FlexDirection>,@@ -129,6 +223,10 @@ pub struct LayoutStyle {pub justify_content: Option<taffy::JustifyContent>,pub flex_grow: Option<f32>,pub flex_shrink: Option<f32>,+ /// `flex-basis` (longhand, or the length in a `flex:` shorthand). `Auto`+ /// is the default. Fixed-basis sidebars/columns (`flex: 0 0 260px`)+ /// collapse to content width without it.+ pub flex_basis: Dimension,// CSS Grid. Tracks are stored as taffy sizing functions; `grid_areas` is the// parsed `grid-template-areas` matrix (one Vec per row, `.` for a null cell),@@ -139,12 +237,31 @@ pub struct LayoutStyle {pub grid_area_name: Option<String>,pub grid_column: Option<taffy::Line<taffy::GridPlacement>>,pub grid_row: Option<taffy::Line<taffy::GridPlacement>>,+ /// `[line-name]` -> 1-based grid line number, parsed from+ /// `grid-template-columns`/`-rows`. taffy has no native named-line support,+ /// so children placed by name (`grid-column: content-start / content-end`,+ /// widely used by the Guardian and other editorial grids) are resolved to+ /// numeric lines against these maps in `dom::resolve_grid_areas`.+ pub grid_col_line_names: Option<std::collections::HashMap<String, i16>>,+ pub grid_row_line_names: Option<std::collections::HashMap<String, i16>>,+ /// Raw `grid-column`/`grid-row` value when it references a named line (so it+ /// cannot be resolved to a `taffy::Line` until the parent's line-name map is+ /// known). Resolved in the same later pass; numeric/`span` values still fill+ /// `grid_column`/`grid_row` directly at cascade time.+ pub grid_column_raw: Option<String>,+ pub grid_row_raw: Option<String>,pub column_gap: Option<f32>,pub row_gap: Option<f32>,+ /// `border-spacing: <horizontal> <vertical>?` (or the `cellspacing`+ /// attribute). Only meaningful on a `<table>`; taffy has no native table+ /// display mode, so `dom::propagate_border_spacing` distributes this down+ /// as the table's own row gap and each descendant `<tr>`'s column gap.+ pub border_spacing: Option<(f32, f32)>,+// Positioning. `position: absolute|fixed` takes the box out of normal flow.pub position: Option<taffy::Position>,- pub inset: [Option<f32>; 4], // top, right, bottom, left+ pub inset: [Option<Dimension>; 4], // top, right, bottom, left/// `overflow`/-x/-y other than `visible`: clips this element's descendants/// to its border box during paint. This is what makes the ubiquitous@@ -157,6 +274,77 @@ pub struct LayoutStyle {/// float's shape, which taffy's block/flex/grid modes do not do; see/// `dom::group_float_zone` for the bounded approximation this drives.pub float: Option<Float>,++ /// `visibility: hidden|visible`, own value. `None` means "inherit the+ /// ancestor's computed value" (visibility, unlike most box properties, is+ /// a real inherited CSS property). Resolved into `effectively_invisible`+ /// during `dom::layout_dom`'s inheritance pass.+ pub visibility_hidden: Option<bool>,+ /// `opacity`, own (non-inherited) value in 0.0-1.0. `None` means the+ /// default of 1.0.+ pub opacity: Option<f32>,+ /// Resolved during the inheritance pass: true when this element should+ /// not be painted at all, either from its own or an inherited+ /// `visibility: hidden`, or because the product of its own and every+ /// ancestor's `opacity` has collapsed to (near) zero. Real `opacity`+ /// composites as translucent groups, which our paint step does not do;+ /// collapsing it to a binary paint/don't-paint decision is enough to+ /// make the extremely common "opacity:0 + visibility:hidden" collapsed+ /// dropdown/panel pattern actually invisible, without needing full alpha+ /// compositing.+ pub effectively_invisible: bool,++ /// Literal text injected by a `::before`/`::after` rule with a plain+ /// string-literal `content` (see `css::Stylesheet::pseudo_content`).+ /// Rendered as an extra word-run at the start/end of this element's+ /// children, same as if it were real text content.+ pub before_content: Option<String>,+ pub after_content: Option<String>,++ /// True for `inline-block`/`inline-flex`/`inline-grid`: participates in+ /// the surrounding inline flow from the outside, like plain `inline`+ /// (both currently collapse to `Display::Inline` — this engine has no+ /// separate inline-block layout mode), but unlike plain `inline` it must+ /// stay a single atomic box rather than have its own content merge into+ /// the parent's line-breaking. `dom::is_flattenable_inline` uses this to+ /// avoid flattening these away: doing so would lose the element as its+ /// own box (including any `::before`/`::after` content attached to it).+ pub is_inline_block: bool,++ /// `display: contents`: the element generates no box of its own; its+ /// children participate in the parent's formatting context directly+ /// (`dom::build_any` splices them into the parent's child list). Kept as a+ /// flag beside `display` because the element still carries inherited styles+ /// for its subtree and `display:none` must still win.+ pub display_contents: bool,++ /// `list-style-type` (or the `list-style` shorthand). Inherited, like in+ /// real CSS; `None` means "not set on this element, inherit". Resolved to+ /// a concrete value during the inheritance pass. Only `<li>` elements draw+ /// a marker from it, but it is carried on every element because it+ /// inherits (a `list-style: none` on a `<ul>` must reach its `<li>`+ /// children, which is how nav menus suppress bullets).+ pub list_style: Option<ListStyle>,++ /// `line-height`. Inherited. `None` means "not set, inherit"; resolved to+ /// a concrete value in the inheritance pass. Drives the vertical rhythm of+ /// shaped text (a fixed ratio made real-site prose noticeably tighter than+ /// Chromium).+ pub line_height: Option<LineHeight>,++ /// `text-transform`. Inherited. Applied to span text before shaping.+ pub text_transform: Option<TextTransform>,++ /// `text-decoration-line: underline` (or the `text-decoration` shorthand).+ /// Not inherited in CSS, but a decoration visually covers descendant inline+ /// text, so it is propagated into the shaped spans of the element's subtree+ /// (this is what underlines links, which are underlined by UA default).+ pub underline: Option<bool>,++ /// `font-style: italic|oblique`. Inherited. Selects the oblique face when+ /// shaping (we embed the DejaVu Sans oblique/bold-oblique faces). `None`+ /// means inherit.+ pub font_style_italic: Option<bool>,}#[derive(Debug, Clone, Copy, PartialEq, Eq)]@@ -165,6 +353,34 @@ pub enum Float {Right,}+/// `line-height`: `normal` (a font-relative default), a unitless multiple of+/// font-size, or an absolute pixel length.+#[derive(Debug, Clone, Copy, PartialEq)]+pub enum LineHeight {+ Normal,+ Ratio(f32),+ Px(f32),+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum TextTransform {+ None,+ Uppercase,+ Lowercase,+ Capitalize,+}++/// `list-style-type` values we render a marker for. `Decimal` numbers the+/// item by its position among sibling list items.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum ListStyle {+ None,+ Disc,+ Circle,+ Square,+ Decimal,+}+/// A node in the input layout tree. `text` is carried for the paint phase; it/// does not affect layout in phase 1 (inline/text layout comes later).#[derive(Debug, Clone)]@@ -245,7 +461,7 @@ pub(crate) fn to_taffy_style(style: &LayoutStyle) -> Style {// column, matching the same column-flex approximation already used for// elements like <td> and <center>.let promote_for_alignment = style.display == Display::Block- && matches!(style.align_items, Some(taffy::AlignItems::Center) | Some(taffy::AlignItems::FlexEnd));+ && matches!(style.align_items, Some(taffy::AlignItems::CENTER) | Some(taffy::AlignItems::FLEX_END));s.display = match style.display {Display::Block if promote_for_alignment => taffy::style::Display::Flex,@@ -273,6 +489,16 @@ pub(crate) fn to_taffy_style(style: &LayoutStyle) -> Style {width: dimension(style.width),height: dimension(style.height),};+ // Tell taffy's own layout algorithm about `overflow: hidden`, not just our+ // paint-time clip rects: per spec, a flex/grid item's automatic minimum+ // size is content-based only when its overflow is `visible`, and `0`+ // otherwise. Without this, an explicit `height: 0; overflow: hidden`+ // element (the common collapsed-dropdown-panel pattern: hidden until a+ // sibling checkbox is checked) still grows to fit its content, since+ // taffy has no way to know it should not.+ if style.overflow_hidden {+ s.overflow = taffy::Point { x: taffy::style::Overflow::Hidden, y: taffy::style::Overflow::Hidden };+ }s.min_size = taffy::Size {width: dimension(style.min_width),height: dimension(style.min_height),@@ -281,6 +507,11 @@ pub(crate) fn to_taffy_style(style: &LayoutStyle) -> Style {width: dimension(style.max_width),height: dimension(style.max_height),};+ if let Some(ar) = style.aspect_ratio {+ if ar.is_finite() && ar > 0.0 {+ s.aspect_ratio = Some(ar);+ }+ }if let Some(ai) = style.align_items {s.align_items = Some(ai);}@@ -293,29 +524,50 @@ pub(crate) fn to_taffy_style(style: &LayoutStyle) -> Style {if let Some(fs) = style.flex_shrink {s.flex_shrink = fs;}+ if style.flex_basis != Dimension::Auto {+ s.flex_basis = dimension(style.flex_basis);+ }- // Grid container tracks and gaps.+ // Grid container tracks and gaps. obscura expands `repeat()` itself during+ // parsing, so every stored track is a single (non-repeated) `MinMax`; wrap+ // each as a `GridTemplateComponent::Single` for taffy 0.12. The 0.7-era+ // fr->Auto row workaround (which stopped `minmax(0,1fr)` image rows from+ // collapsing to a sliver) is gone: taffy 0.12 treats an in-flow child's+ // vertical available space as indefinite, so fr rows of an auto-height grid+ // size to their content the way real CSS does.if style.display == Display::Grid {if !style.grid_template_columns.is_empty() {- s.grid_template_columns = style.grid_template_columns.clone();+ s.grid_template_columns = style+ .grid_template_columns+ .iter()+ .cloned()+ .map(taffy::GridTemplateComponent::Single)+ .collect();}if !style.grid_template_rows.is_empty() {- s.grid_template_rows = style.grid_template_rows.clone();+ s.grid_template_rows = style+ .grid_template_rows+ .iter()+ .cloned()+ .map(taffy::GridTemplateComponent::Single)+ .collect();}}let cg = style.column_gap.unwrap_or(0.0);let rg = style.row_gap.unwrap_or(0.0);s.gap = taffy::Size {- width: taffy::style::LengthPercentage::Length(cg),- height: taffy::style::LengthPercentage::Length(rg),+ width: taffy::style::LengthPercentage::length(cg),+ height: taffy::style::LengthPercentage::length(rg),};// Grid item placement (resolved from grid-area names or explicit lines).- if let Some(gc) = style.grid_column {- s.grid_column = gc;+ // `GridPlacement` is no longer `Copy` in taffy 0.12 (it can carry a named+ // line), so clone out of the borrowed style.+ if let Some(gc) = &style.grid_column {+ s.grid_column = gc.clone();}- if let Some(gr) = style.grid_row {- s.grid_row = gr;+ if let Some(gr) = &style.grid_row {+ s.grid_row = gr.clone();}// Positioning. Absolute/fixed take the box out of flow.@@ -329,42 +581,58 @@ pub(crate) fn to_taffy_style(style: &LayoutStyle) -> Style {};}- s.margin = rect_auto(style.margin);+ s.margin = rect_auto(style.margin, style.margin_auto);s.padding = rect_lp(style.padding);s.border = rect_lp(style.border);s}-fn inset_lpa(v: Option<f32>) -> taffy::style::LengthPercentageAuto {+fn inset_lpa(v: Option<Dimension>) -> taffy::style::LengthPercentageAuto {match v {- Some(px) => taffy::style::LengthPercentageAuto::Length(px),- None => taffy::style::LengthPercentageAuto::Auto,+ Some(Dimension::Px(px)) => taffy::style::LengthPercentageAuto::length(px),+ Some(Dimension::Percent(p)) => taffy::style::LengthPercentageAuto::percent(p),+ // Relative units are resolved to Px before layout; unresolved leftovers+ // and `auto`/absent both map to Auto.+ _ => taffy::style::LengthPercentageAuto::auto(),}}fn dimension(v: Dimension) -> taffy::style::Dimension {match v {- Dimension::Px(px) => taffy::style::Dimension::Length(px),- Dimension::Percent(p) => taffy::style::Dimension::Percent(p),- Dimension::Auto => taffy::style::Dimension::Auto,+ Dimension::Px(px) => taffy::style::Dimension::length(px),+ Dimension::Percent(p) => taffy::style::Dimension::percent(p),+ Dimension::Auto => taffy::style::Dimension::auto(),+ // Relative units are resolved to Px before layout; if one slips+ // through unresolved, fall back to its raw magnitude (em/rem ~16px)+ // rather than panicking.+ Dimension::Em(v) | Dimension::Rem(v) => taffy::style::Dimension::length(v * 16.0),+ Dimension::Vw(v) | Dimension::Vh(v) | Dimension::Vmin(v) | Dimension::Vmax(v) => taffy::style::Dimension::length(v),}}fn rect_lp(e: Edges) -> taffy::Rect<taffy::style::LengthPercentage> {taffy::Rect {- top: taffy::style::LengthPercentage::Length(e.top),- right: taffy::style::LengthPercentage::Length(e.right),- bottom: taffy::style::LengthPercentage::Length(e.bottom),- left: taffy::style::LengthPercentage::Length(e.left),+ top: taffy::style::LengthPercentage::length(e.top),+ right: taffy::style::LengthPercentage::length(e.right),+ bottom: taffy::style::LengthPercentage::length(e.bottom),+ left: taffy::style::LengthPercentage::length(e.left),}}-fn rect_auto(e: Edges) -> taffy::Rect<taffy::style::LengthPercentageAuto> {+fn rect_auto(e: Edges, auto: [bool; 4]) -> taffy::Rect<taffy::style::LengthPercentageAuto> {+ // NOTE: `margin: auto` is parsed (see `margin_auto`) but intentionally not+ // emitted as taffy `Auto` yet. In our architecture most text containers are+ // promoted to synthetic flex rows for inline layout, and an auto margin in+ // a flex row absorbs the row's free space and flings a wide child far to+ // one side (it mangled Wikipedia taxobox timelines). Honoring auto-margin+ // centering safely needs a real block formatting context; treat as 0 (the+ // element's normal-flow position) until then.+ let _ = auto;taffy::Rect {- top: taffy::style::LengthPercentageAuto::Length(e.top),- right: taffy::style::LengthPercentageAuto::Length(e.right),- bottom: taffy::style::LengthPercentageAuto::Length(e.bottom),- left: taffy::style::LengthPercentageAuto::Length(e.left),+ top: taffy::style::LengthPercentageAuto::length(e.top),+ right: taffy::style::LengthPercentageAuto::length(e.right),+ bottom: taffy::style::LengthPercentageAuto::length(e.bottom),+ left: taffy::style::LengthPercentageAuto::length(e.left),}}diff --git a/crates/obscura-render/src/paint.rs b/crates/obscura-render/src/paint.rsindex 4aa6befd..4d4dd85b 100644--- a/crates/obscura-render/src/paint.rs+++ b/crates/obscura-render/src/paint.rs@@ -6,12 +6,12 @@//! dependencies, so a screenshot is reproducible across hosts.use obscura_dom::tree::DomTree;-use tiny_skia::{Color, FillRule, Paint, PathBuilder, Pixmap, Rect, Transform};+use tiny_skia::{Color, FillRule, GradientStop, LinearGradient, Paint, PathBuilder, Pixmap, Point, Rect, SpreadMode, Transform};use ab_glyph::{Font, FontRef, PxScale, ScaleFont};static FONT_BYTES: &[u8] = include_bytes!("../assets/dejavu-sans.ttf");-use crate::layout_dom;+use crate::layout_dom_with_images;/// Render `tree` at `viewport` (width, height) in CSS pixels to a Pixmap, or/// None if the viewport is zero-sized. `base_url`, when given, resolves the@@ -23,12 +23,17 @@ pub fn paint_dom(tree: &DomTree, viewport: (f32, f32), base_url: Option<&str>) -let mut pixmap = Pixmap::new(w, h)?;pixmap.fill(Color::WHITE);- let laid = layout_dom(tree, viewport);// The same URL (an icon sprite, a repeated background image) commonly// backs many elements on one page; fetch each distinct URL at most once// per screenshot. `None` caches a failed fetch too, so a broken image// reference does not retry on every element that references it.let mut image_cache: std::collections::HashMap<String, Option<Vec<u8>>> = std::collections::HashMap::new();+ // Fetch <img> bytes up front to learn intrinsic sizes for layout (a+ // CSS-sized image with no width/height attribute would otherwise be 0x0+ // and never paint). This seeds the same cache the paint pass reads, so+ // each URL is still fetched at most once.+ let intrinsic = collect_image_intrinsics(tree, base_url, &mut image_cache);+ let mut laid = layout_dom_with_images(tree, viewport, &intrinsic);// Tree order so later elements paint over earlier ones (normal flow).for nid in tree.descendants(tree.document()) {let node = match tree.get_node(nid) {@@ -55,6 +60,10 @@ pub fn paint_dom(tree: &DomTree, viewport: (f32, f32), base_url: Option<&str>) -None => continue,};+ if style.effectively_invisible {+ continue;+ }+// Ancestor `overflow: hidden` clip, if any. Skip painting entirely// once the box has no visible overlap with it (this is what makes the// ubiquitous 1x1 clipped "visually hidden" accessibility pattern@@ -72,17 +81,32 @@ pub fn paint_dom(tree: &DomTree, viewport: (f32, f32), base_url: Option<&str>) -None => continue,};- // A masked element's background-color is the mask's fill color, not- // an ordinary box background: it must only show through the mask- // shape (painted below), not as a solid rect behind it.- if let (Some(bg), None) = (style.background_color, &style.mask_image) {- let mut path = PathBuilder::new();- path.push_rect(box_rect);- if let Some(path) = path.finish() {- let mut paint = Paint::default();- paint.set_color(Color::from_rgba8(bg[0], bg[1], bg[2], bg[3]));- paint.anti_alias = false;- pixmap.fill_path(&path, &paint, FillRule::Winding, Transform::identity(), None);+ // Box path (rounded if border-radius), reused for gradient/color fill.+ let r = style.border_radius;+ let bg_path = || if r > 0.5 {+ rounded_rect_path(visible_rect.x, visible_rect.y, visible_rect.width, visible_rect.height, r)+ } else {+ let mut pb = PathBuilder::new();+ pb.push_rect(box_rect);+ pb.finish()+ };+ // A linear-gradient background (heavily used by modern hero sections);+ // without this it paints white. Takes precedence over a solid color.+ if style.mask_image.is_none() {+ if let Some((angle, stops)) = &style.background_gradient {+ if let Some(path) = bg_path() {+ paint_linear_gradient(&mut pixmap, &path, &visible_rect, *angle, stops);+ }+ } else if let Some(bg) = style.background_color {+ // A masked element's background-color is the mask's fill color,+ // not an ordinary box background (handled below), so this only+ // runs for unmasked boxes.+ if let Some(path) = bg_path() {+ let mut paint = Paint::default();+ paint.set_color(Color::from_rgba8(bg[0], bg[1], bg[2], bg[3]));+ paint.anti_alias = r > 0.5;+ pixmap.fill_path(&path, &paint, FillRule::Winding, Transform::identity(), None);+ }}}@@ -116,7 +140,23 @@ pub fn paint_dom(tree: &DomTree, viewport: (f32, f32), base_url: Option<&str>) -}}- if style.border.top > 0.0 || style.border.right > 0.0 || style.border.bottom > 0.0 || style.border.left > 0.0 {+ // Rounded, uniform border: stroke the rounded-rect outline instead of+ // four sharp edge rects.+ let uniform_border = style.border.top == style.border.right+ && style.border.right == style.border.bottom+ && style.border.bottom == style.border.left+ && style.border.top > 0.0;+ if style.border_radius > 0.5 && uniform_border {+ let bc = style.border_color.or(style.color).unwrap_or([0, 0, 0, 255]);+ let w = style.border.top;+ if let Some(path) = rounded_rect_path(rect.x + w / 2.0, rect.y + w / 2.0, rect.width - w, rect.height - w, (style.border_radius - w / 2.0).max(0.0)) {+ let mut paint = Paint::default();+ paint.set_color(Color::from_rgba8(bc[0], bc[1], bc[2], bc[3]));+ paint.anti_alias = true;+ let stroke = tiny_skia::Stroke { width: w, ..Default::default() };+ pixmap.stroke_path(&path, &paint, &stroke, Transform::identity(), None);+ }+ } else if style.border.top > 0.0 || style.border.right > 0.0 || style.border.bottom > 0.0 || style.border.left > 0.0 {let bc = style.border_color.or(style.color).unwrap_or([0, 0, 0, 255]);let mut paint = Paint::default();paint.set_color(Color::from_rgba8(bc[0], bc[1], bc[2], bc[3]));@@ -150,10 +190,20 @@ pub fn paint_dom(tree: &DomTree, viewport: (f32, f32), base_url: Option<&str>) -}if name.local.as_ref() == "img" {- if let Some(src) = node.get_attribute("src") {- let painted = paint_image(src, base_url, &rect, &mut pixmap, &mut image_cache);+ if let Some(src) = resolve_img_url(tree, nid) {+ let painted = paint_image(&src, base_url, &rect, &mut pixmap, &mut image_cache);// Fall back to alt text only when the image itself did not paint.if !painted {+ // A fetch/decode failure paints a neutral grey box (like a+ // browser's lazy/broken-image placeholder) so a missing+ // image reads as "not loaded", not as a broken render.+ // box_rect/visible_rect are already clip-intersected, so+ // this never paints outside an overflow:hidden clip.+ if visible_rect.width >= 4.0 && visible_rect.height >= 4.0 {+ let mut ph = Paint::default();+ ph.set_color(Color::from_rgba8(0xE9, 0xEA, 0xEC, 0xFF));+ pixmap.fill_rect(box_rect, &ph, Transform::identity(), None);+ }if let Some(alt) = node.get_attribute("alt") {if !alt.is_empty() {draw_text(&mut pixmap, alt, rect.x, rect.y, [0, 0, 0, 255], 12.0, false, clip);@@ -162,10 +212,114 @@ pub fn paint_dom(tree: &DomTree, viewport: (f32, f32), base_url: Option<&str>) -}}}++ // List-item marker (bullet or number), drawn in the indent to the left+ // of the item's content box. `list_style` is inherited and resolved,+ // so `None` (e.g. a nav `<ul style="list-style:none">`) suppresses it.+ if name.local.as_ref() == "li" {+ if let Some(marker) = list_marker_text(tree, nid, style.list_style) {+ let fsize = style.font_size.unwrap_or(16.0);+ let color = style.color.unwrap_or([0, 0, 0, 255]);+ let mw = measure_text(&marker, fsize, false);+ let mx = rect.x + style.padding.left - mw - 6.0;+ let my = rect.y + style.border.top + style.padding.top;+ draw_text(&mut pixmap, &marker, mx, my, color, fsize, false, clip);+ }+ }++ // `::before`/`::after` generated text (see `dom::build_pseudo_content`)+ // has no DOM text node of its own; its word runs are registered under+ // the host element's own id instead, so paint them here rather than+ // through `paint_text_node` (which only runs for real text nodes).+ if let Some(runs) = laid.text_runs.get(&nid) {+ let color = style.color.unwrap_or([0, 0, 0, 255]);+ let fsize = style.font_size.unwrap_or(16.0);+ let is_bold = style.font_weight.as_deref() == Some("bold");+ for (word_rect, word) in runs {+ draw_text(&mut pixmap, word, word_rect.x, word_rect.y, color, fsize, is_bold, clip);+ }+ }++ // An empty text `<input>`/`<textarea>` shows its `placeholder`+ // attribute as muted text; there is no DOM text node for it (it is+ // not real content), so paint it directly from the attribute instead+ // of going through `paint_text_node`.+ if name.local.as_ref() == "input" || name.local.as_ref() == "textarea" {+ let has_value = node.get_attribute("value").map(|v| !v.is_empty()).unwrap_or(false);+ if !has_value {+ if let Some(placeholder) = node.get_attribute("placeholder") {+ if !placeholder.is_empty() {+ let fsize = style.font_size.unwrap_or(16.0);+ let text_x = rect.x + style.padding.left + style.border.left;+ let text_y = rect.y + style.padding.top + style.border.top;+ draw_text(&mut pixmap, placeholder, text_x, text_y, [117, 117, 117, 255], fsize, false, clip);+ }+ }+ }+ }}++ // Inline formatting contexts shaped by cosmic-text (paragraphs, headings,+ // cells, labels) draw last, in tree order, so their glyphs sit above the+ // box backgrounds/borders painted in the loop above. Each item already+ // carries its final origin and clip from `TextEngine::finalize`.+ for nid in tree.descendants(tree.document()) {+ if let Some(&idx) = laid.ifc_items.get(&nid) {+ if laid.styles.get(&nid).map(|s| s.effectively_invisible).unwrap_or(false) {+ continue;+ }+ laid.text_engine.paint_item(idx, &mut pixmap);+ }+ }+Some(pixmap)}+/// A closed rounded-rectangle path, corners approximated by quadratic curves+/// (visually indistinguishable from true arcs at typical UI radii). `r` is+/// clamped so it never exceeds half the shorter side.+fn rounded_rect_path(x: f32, y: f32, w: f32, h: f32, r: f32) -> Option<tiny_skia::Path> {+ if w <= 0.0 || h <= 0.0 {+ return None;+ }+ let r = r.min(w / 2.0).min(h / 2.0).max(0.0);+ let mut pb = PathBuilder::new();+ pb.move_to(x + r, y);+ pb.line_to(x + w - r, y);+ pb.quad_to(x + w, y, x + w, y + r);+ pb.line_to(x + w, y + h - r);+ pb.quad_to(x + w, y + h, x + w - r, y + h);+ pb.line_to(x + r, y + h);+ pb.quad_to(x, y + h, x, y + h - r);+ pb.line_to(x, y + r);+ pb.quad_to(x, y, x + r, y);+ pb.close();+ pb.finish()+}++/// The marker text for a list item, or `None` when markers are suppressed+/// (`list-style: none`). `Decimal` numbers the item by its position among+/// sibling list items so `<ol>`s count 1, 2, 3.+fn list_marker_text(tree: &DomTree, nid: obscura_dom::tree::NodeId, style: Option<crate::ListStyle>) -> Option<String> {+ match style {+ Some(crate::ListStyle::Disc) => Some("\u{2022}".to_string()),+ Some(crate::ListStyle::Circle) => Some("\u{25E6}".to_string()),+ Some(crate::ListStyle::Square) => Some("\u{25AA}".to_string()),+ Some(crate::ListStyle::Decimal) => {+ let mut n = 1usize;+ let mut cur = tree.get_node(nid).and_then(|node| node.prev_sibling);+ while let Some(sib) = cur {+ if tree.get_node(sib).and_then(|s| s.as_element().map(|e| e.local.to_string())).as_deref() == Some("li") {+ n += 1;+ }+ cur = tree.get_node(sib).and_then(|s| s.prev_sibling);+ }+ Some(format!("{}.", n))+ }+ Some(crate::ListStyle::None) | None => None,+ }+}+/// Render `tree` at `viewport` to PNG bytes (RGBA 8-bit). Returns None if the/// viewport is zero-sized. Convenience over `paint_dom` + `encode_png`.pub fn screenshot_png(tree: &DomTree, viewport: (f32, f32), base_url: Option<&str>) -> Option<Vec<u8>> {@@ -187,6 +341,9 @@ fn paint_text_node(let node = tree.get_node(nid)?;let parent = node.parent?;let style = laid.styles.get(&parent)?;+ if style.effectively_invisible {+ return Some(());+ }let color = style.color.unwrap_or([0, 0, 0, 255]);let fsize = style.font_size.unwrap_or(16.0);let is_bold = style.font_weight.as_deref() == Some("bold");@@ -331,15 +488,68 @@ fn fetch_bytes(let url = resolved?;cache.entry(url.clone())- .or_insert_with(|| {- ureq::get(&url).call().ok().and_then(|resp| {+ .or_insert_with(|| http_get_bytes(&url))+ .clone()+}++/// Fetch `url` with a descriptive User-Agent and a bounded timeout, retrying on+/// rate-limit / transient errors with backoff. Real pages pull dozens of images+/// from one CDN in a burst (a Wikipedia article references ~60); hosts like+/// Wikimedia answer a rapid burst with HTTP 429 after ~10 requests. Without a+/// retry the rate-limited images (e.g. an infobox photo montage fetched late in+/// the burst) came back blank, and the failure was cached permanently. The+/// backoff both recovers them and paces the burst back under the limit.+fn http_get_bytes(url: &str) -> Option<Vec<u8>> {+ let mut backoff = std::time::Duration::from_millis(200);+ for attempt in 0..3 {+ // A browser-like Accept advertises the modern image formats and is what+ // content-negotiating CDNs expect; some UA-gated hosts also reject a+ // request with no Accept header outright.+ let res = image_agent()+ .get(url)+ .set("Accept", "image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8")+ .call();+ match res {+ Ok(resp) => {let mut buf = Vec::new();use std::io::Read;- resp.into_reader().read_to_end(&mut buf).ok()?;- Some(buf)- })- })- .clone()+ return resp.into_reader().read_to_end(&mut buf).ok().map(|_| buf);+ }+ // 429 (rate limit) and 5xx are transient: back off and retry.+ Err(ureq::Error::Status(code, _)) if matches!(code, 429 | 500 | 502 | 503 | 504) && attempt < 2 => {+ std::thread::sleep(backoff);+ backoff *= 2;+ }+ // A network/transport error is also worth one more try.+ Err(ureq::Error::Transport(_)) if attempt < 2 => {+ std::thread::sleep(backoff);+ backoff *= 2;+ }+ Err(_) => return None,+ }+ }+ None+}++/// One shared HTTP agent for all image fetches in the process, with a browser+/// User-Agent and keep-alive connection pooling. A CDN's bot rate-limiter keys+/// on connection churn as much as on rate: a fresh TLS handshake per image (the+/// old per-call `ureq::get`) reads as a burst and gets 429'd, whereas reusing+/// one pooled connection to the same host (as a browser does) both avoids most+/// throttling and is much faster on an image-heavy page.+fn image_agent() -> &'static ureq::Agent {+ static AGENT: std::sync::OnceLock<ureq::Agent> = std::sync::OnceLock::new();+ AGENT.get_or_init(|| {+ ureq::AgentBuilder::new()+ .timeout(std::time::Duration::from_secs(10))+ // Present the same normal browser identity the engine uses for the+ // document. A bot-identifying UA got image requests filtered by CDNs+ // that gate on User-Agent (Akamai/Cloudflare image endpoints on+ // cnbc, techcrunch, arstechnica), so the images Chrome loads came+ // back blank; a real browser UA loads the same bytes Chrome does.+ .user_agent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36")+ .build()+ })}/// Decode a percent-escaped data: URI payload (`%23` -> `#`, etc). Bytes that@@ -386,6 +596,303 @@ fn raster_to_pixmap(bytes: &[u8], w: u32, h: u32) -> Option<Pixmap> {Pixmap::from_vec(raw, size)}+/// Read an image's intrinsic pixel dimensions from its header only, without+/// decoding the whole thing. Returns None for formats the raster decoder does+/// not recognize (e.g. SVG, which is sized elsewhere).+/// Fill `path` with a CSS `linear-gradient`. `angle` is degrees clockwise from+/// 12 o'clock (0 = to top). The gradient line length uses the CSS formula so+/// the stops land where a browser puts them. Positionless stops are spread+/// evenly; positions are clamped monotonic (tiny-skia requires ascending).+fn paint_linear_gradient(pixmap: &mut Pixmap, path: &tiny_skia::Path, rect: &crate::Rect, angle: f32, stops: &[([u8; 4], Option<f32>)]) {+ if stops.len() < 2 {+ return;+ }+ let rad = angle.to_radians();+ let dx = rad.sin();+ let dy = -rad.cos();+ let (cx, cy) = (rect.x + rect.width / 2.0, rect.y + rect.height / 2.0);+ let half = (dx.abs() * rect.width + dy.abs() * rect.height) / 2.0;+ let start = Point::from_xy(cx - dx * half, cy - dy * half);+ let end = Point::from_xy(cx + dx * half, cy + dy * half);+ let n = stops.len();+ let mut gs: Vec<GradientStop> = Vec::with_capacity(n);+ let mut last = 0.0f32;+ for (i, (c, pos)) in stops.iter().enumerate() {+ let p = pos.unwrap_or(i as f32 / (n - 1) as f32).clamp(0.0, 1.0).max(last);+ last = p;+ gs.push(GradientStop::new(p, Color::from_rgba8(c[0], c[1], c[2], c[3])));+ }+ if let Some(shader) = LinearGradient::new(start, end, gs, SpreadMode::Pad, Transform::identity()) {+ let mut paint = Paint::default();+ paint.shader = shader;+ paint.anti_alias = true;+ pixmap.fill_path(path, &paint, FillRule::Winding, Transform::identity(), None);+ }+}++fn image_dimensions(bytes: &[u8]) -> Option<(u32, u32)> {+ image::ImageReader::new(std::io::Cursor::new(bytes))+ .with_guessed_format()+ .ok()?+ .into_dimensions()+ .ok()+}++/// Fetch every `<img>` once (seeding `cache` for the paint pass) and record its+/// intrinsic (width, height) so layout can size replaced elements that have no+/// explicit dimensions. Keyed by the `<img>`'s NodeId.+fn collect_image_intrinsics(+ tree: &DomTree,+ base_url: Option<&str>,+ cache: &mut std::collections::HashMap<String, Option<Vec<u8>>>,+) -> std::collections::HashMap<obscura_dom::tree::NodeId, (f32, f32)> {+ let mut out = std::collections::HashMap::new();+ for nid in tree.descendants(tree.document()) {+ let Some(node) = tree.get_node(nid) else { continue };+ if node.as_element().map(|e| e.local.as_ref() != "img").unwrap_or(true) {+ continue;+ }+ let Some(url) = resolve_img_url(tree, nid) else { continue };+ let Some(bytes) = fetch_bytes(&url, base_url, cache) else { continue };+ if let Some((w, h)) = image_dimensions(&bytes) {+ if w > 0 && h > 0 {+ out.insert(nid, (w as f32, h as f32));+ }+ }+ }+ out+}++/// Choose the URL to paint for an `<img>`. Browsers do not use `src` alone:+/// a wrapping `<picture>`'s `<source>`s, `srcset`, and `sizes` select by+/// type/media/viewport/density, and lazy-loaded images keep the real URL in+/// `data-src`/`data-srcset` with `src` holding a 1x1 placeholder until script+/// swaps it in. Since obscura may not have run the site's lazy-load script,+/// resolve the same URL the browser would end up with: a matching `<picture>`+/// source first, then a real candidate from `srcset`/`data-srcset`, then a+/// non-inline `src`/`data-*` URL, then any `src` (an inlined data: image).+fn resolve_img_url(tree: &DomTree, nid: obscura_dom::tree::NodeId) -> Option<String> {+ let node = tree.get_node(nid)?;+ // A <picture>'s preceding, type/media-matching <source> wins over the+ // <img>'s own attributes (HTML "update the source set").+ if let Some(url) = picture_source_url(tree, nid) {+ return Some(url);+ }+ let sizes = node.get_attribute("sizes");+ for a in ["srcset", "data-srcset"] {+ if let Some(v) = node.get_attribute(a) {+ if let Some(u) = best_srcset_candidate(v, sizes) {+ return Some(u);+ }+ }+ }+ let url_attrs = ["src", "data-src", "data-lazy-src", "data-original", "data-fallback-src", "data-lazy"];+ // A non-inline URL first (a data: src is usually the lazy-load placeholder).+ for a in url_attrs {+ if let Some(v) = node.get_attribute(a) {+ let v = v.trim();+ if !v.is_empty() && !v.starts_with("data:") {+ return Some(v.to_string());+ }+ }+ }+ // Otherwise fall back to whatever is there (an inlined data: image).+ for a in url_attrs {+ if let Some(v) = node.get_attribute(a) {+ let v = v.trim();+ if !v.is_empty() {+ return Some(v.to_string());+ }+ }+ }+ None+}++/// When `img_nid` is an `<img>` inside a `<picture>`, walk its preceding+/// `<source>` siblings in document order and return the selected URL of the+/// first supported one (matching `type` and `media`), per WebKit's+/// `HTMLImageElement::bestFitSourceFromPictureElement`. `None` means no source+/// applied and the caller should fall back to the `<img>`'s own attributes.+fn picture_source_url(tree: &DomTree, img_nid: obscura_dom::tree::NodeId) -> Option<String> {+ let img = tree.get_node(img_nid)?;+ let parent = img.parent?;+ let is_picture = tree+ .get_node(parent)+ .and_then(|p| p.as_element().map(|e| e.local.as_ref() == "picture"))+ .unwrap_or(false);+ if !is_picture {+ return None;+ }+ for cid in tree.children(parent) {+ // Only sources that precede the <img> contribute.+ if cid == img_nid {+ break;+ }+ let Some(child) = tree.get_node(cid) else { continue };+ if child.as_element().map(|e| e.local.as_ref() != "source").unwrap_or(true) {+ continue;+ }+ let Some(srcset) = child.get_attribute("srcset") else { continue };+ if srcset.trim().is_empty() {+ continue;+ }+ if let Some(t) = child.get_attribute("type") {+ if !source_type_supported(t) {+ continue;+ }+ }+ if let Some(m) = child.get_attribute("media") {+ if !m.trim().is_empty() && !crate::css::media_query_applies(m) {+ continue;+ }+ }+ let sizes = child.get_attribute("sizes");+ if let Some(u) = best_srcset_candidate(srcset, sizes) {+ return Some(u);+ }+ }+ None+}++/// Whether a `<source type=...>` names an image format this build can decode.+/// AVIF/JPEG-XL are intentionally excluded: the `image` crate cannot decode+/// them here, so a decodable `<img>` fallback must win over such a source.+fn source_type_supported(t: &str) -> bool {+ matches!(+ t.trim().to_ascii_lowercase().as_str(),+ "image/jpeg" | "image/jpg" | "image/png" | "image/gif" | "image/webp"+ | "image/bmp" | "image/svg+xml" | "image/x-icon" | "image/vnd.microsoft.icon"+ )+}++/// Assumed layout viewport width (matches the desktop width the `@media`+/// cascade evaluates against in `css.rs`). Used to turn `w` descriptors and+/// `vw`/`%` source sizes into effective pixel densities.+const SRCSET_VIEWPORT_W: f32 = 1280.0;++/// Pick one URL from a `srcset` list, matching the WebKit/Blink selection:+/// normalize each `w` descriptor to an effective density (`w / source-size`,+/// with the source-size taken from `sizes` or falling back to the viewport+/// width), treat `x` descriptors as-is and a bare candidate as `1x`, then pick+/// the smallest density at least the device pixel ratio (1 at DPR 1), else the+/// largest available.+fn best_srcset_candidate(srcset: &str, sizes: Option<&str>) -> Option<String> {+ const DPR: f32 = 1.0;+ let source_size = source_size_px(sizes);+ let mut cands: Vec<(f32, String)> = Vec::new();+ // Parse candidates WHATWG-style: a URL is a run of non-whitespace (so a+ // data: URI's internal commas stay part of it, unlike a naive split on+ // ','), optionally followed by a descriptor up to the next comma.+ let is_ws = |c: char| c.is_whitespace();+ let mut rest = srcset.trim_start_matches(|c: char| is_ws(c) || c == ',');+ while !rest.is_empty() {+ let url_end = rest.find(is_ws).unwrap_or(rest.len());+ let raw_url = &rest[..url_end];+ rest = &rest[url_end..];+ // Trailing commas on the URL mean the candidate had no descriptor.+ let url = raw_url.trim_end_matches(',');+ let no_desc = url.len() != raw_url.len();+ rest = rest.trim_start_matches(is_ws);+ let desc = if no_desc {+ ""+ } else {+ let d_end = rest.find(',').unwrap_or(rest.len());+ let d = rest[..d_end].trim();+ rest = &rest[d_end..];+ d+ };+ rest = rest.trim_start_matches(|c: char| c == ',' || is_ws(c));+ if url.is_empty() {+ continue;+ }+ let density = if desc.is_empty() {+ 1.0+ } else if let Some(w) = desc.strip_suffix('w').and_then(|s| s.parse::<f32>().ok()) {+ if source_size > 0.0 { w / source_size } else { continue }+ } else if let Some(x) = desc.strip_suffix('x').and_then(|s| s.parse::<f32>().ok()) {+ x+ } else {+ // An `h` (height) descriptor or malformed token: skip the candidate.+ continue;+ };+ cands.push((density, url.to_string()));+ }+ if cands.is_empty() {+ return None;+ }+ cands.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal));+ let pick = cands+ .iter()+ .find(|(d, _)| *d >= DPR)+ .map(|(_, u)| u.clone())+ .unwrap_or_else(|| cands.last().unwrap().1.clone());+ Some(pick)+}++/// Approximate the CSS px size an image will be displayed at, from its `sizes`+/// attribute: the first entry whose media condition holds at our assumed+/// desktop viewport (a bare entry always holds), else the viewport width. Used+/// only to convert `w` descriptors to densities, so a coarse value is fine.+fn source_size_px(sizes: Option<&str>) -> f32 {+ let Some(sizes) = sizes else { return SRCSET_VIEWPORT_W };+ for entry in sizes.split(',') {+ let entry = entry.trim();+ if entry.is_empty() {+ continue;+ }+ let (cond, len) = split_size_entry(entry);+ if let Some(cond) = cond {+ if !crate::css::media_query_applies(&cond) {+ continue;+ }+ }+ if let Some(px) = length_to_px(&len) {+ return px;+ }+ }+ SRCSET_VIEWPORT_W+}++/// Split one `sizes` entry into its optional leading media condition and its+/// trailing `<length>`. Tokenizes on whitespace at paren depth 0 so a+/// `calc(...)` length or a parenthesized condition stays intact; the last+/// token is the length, anything before it is the condition.+fn split_size_entry(entry: &str) -> (Option<String>, String) {+ let mut tokens: Vec<String> = Vec::new();+ let mut cur = String::new();+ let mut depth = 0i32;+ for c in entry.chars() {+ match c {+ '(' => { depth += 1; cur.push(c); }+ ')' => { depth -= 1; cur.push(c); }+ c if c.is_whitespace() && depth == 0 => {+ if !cur.is_empty() { tokens.push(std::mem::take(&mut cur)); }+ }+ c => cur.push(c),+ }+ }+ if !cur.is_empty() {+ tokens.push(cur);+ }+ let len = tokens.pop().unwrap_or_default();+ let cond = if tokens.is_empty() { None } else { Some(tokens.join(" ")) };+ (cond, len)+}++/// Resolve a `sizes` length to px against the assumed viewport. `vw`/`%` scale+/// by the viewport width; `px` is literal; `em`/`rem` use the 16px root.+/// `calc()` and other forms return `None` (the caller tries the next entry).+fn length_to_px(len: &str) -> Option<f32> {+ let t = len.trim().to_ascii_lowercase();+ let num = |s: &str| s.trim().parse::<f32>().ok();+ if let Some(v) = t.strip_suffix("vw").and_then(num) { return Some(v / 100.0 * SRCSET_VIEWPORT_W); }+ if let Some(v) = t.strip_suffix('%').and_then(num) { return Some(v / 100.0 * SRCSET_VIEWPORT_W); }+ if let Some(v) = t.strip_suffix("px").and_then(num) { return Some(v); }+ if let Some(v) = t.strip_suffix("rem").and_then(num) { return Some(v * 16.0); }+ if let Some(v) = t.strip_suffix("em").and_then(num) { return Some(v * 16.0); }+ num(&t)+}+fn paint_image(src: &str,base_url: Option<&str>,diff --git a/crates/obscura-render/src/style.rs b/crates/obscura-render/src/style.rsindex 650f913d..eccd9b2d 100644--- a/crates/obscura-render/src/style.rs+++ b/crates/obscura-render/src/style.rs@@ -29,16 +29,47 @@ pub fn ua_style(tag: &str) -> LayoutStyle {}style.display = match tag {- "span" | "a" | "b" | "i" | "strong" | "em" | "font" => Display::Inline,+ // Phrasing / inline-level content defaults to inline so a paragraph+ // that mixes these with text stays one inline formatting context that+ // cosmic-text can shape and wrap as a whole, instead of each element+ // becoming its own block box (which forces the flex word-promotion+ // fallback and its fragile one-word-per-line wrapping). Author CSS+ // (e.g. `code{display:block}`) still overrides this in the cascade.+ "span" | "a" | "b" | "i" | "strong" | "em" | "font" | "code" | "small"+ | "sub" | "sup" | "mark" | "abbr" | "cite" | "var" | "dfn" | "kbd"+ | "samp" | "q" | "time" | "s" | "u" | "del" | "ins" | "tt" | "big"+ | "bdi" | "bdo" | "wbr" | "data" | "output" | "label" | "ruby" | "rt"+ | "rp" => Display::Inline,"tr" => Display::Flex,_ => Display::Block,};if tag == "center" {style.display = Display::Flex;style.flex_direction = Some(taffy::FlexDirection::Column);- style.align_items = Some(taffy::AlignItems::Center);- } else if tag == "head" || tag == "script" || tag == "style" || tag == "title" || tag == "meta" || tag == "link" {+ style.align_items = Some(taffy::AlignItems::CENTER);+ } else if tag == "head" || tag == "script" || tag == "style" || tag == "title" || tag == "meta" || tag == "link" || tag == "noscript" || tag == "template"+ || tag == "desc" || tag == "metadata" || tag == "option" || tag == "optgroup"+ || tag == "source" || tag == "track" || tag == "param" || tag == "area" {+ // `noscript` content is only for scripting-disabled agents; with JS on+ // (as here) the parser keeps it as raw text and the browser hides it,+ // so a site's no-JS nav fallback must not paint as literal markup.+ // `template` content is inert and never rendered. svg `title`/`desc`/+ // `metadata` are AX/tooltip metadata, never rendered in flow (an inline+ // <svg> we cannot rasterize would otherwise leak its `<desc>` text).+ // `option`/`optgroup` render only inside the native select popup, so a+ // closed <select> must not paint every option label stacked.+ // `source`/`track`/`param`/`area` are metadata-only children of+ // picture/video/object/map; a `<picture><source width= height=>` must+ // not lay out as a real box (news CDNs put dimensions on `<source>`,+ // which otherwise paints an empty box the size of the image).style.display = crate::Display::None;+ } else if tag == "br" {+ // Forces a line break inside our flex-row-wrap approximation of+ // inline flow (see `dom::build`'s "stacks_children_vertically"+ // promotion): a full-width, zero-height item leaves no room for+ // anything else on its line, so the next inline item wraps.+ style.width = crate::Dimension::Percent(1.0);+ style.height = crate::Dimension::Px(0.0);} else if tag == "body" {style.margin = Edges { top: 8.0, right: 8.0, bottom: 8.0, left: 8.0 };} else if tag == "h1" {@@ -59,21 +90,57 @@ pub fn ua_style(tag: &str) -> LayoutStyle {style.margin = Edges { top: 21.0, bottom: 21.0, left: 0.0, right: 0.0 };} else if tag == "p" || tag == "ul" || tag == "ol" {style.margin = Edges { top: 16.0, bottom: 16.0, left: 0.0, right: 0.0 };+ if tag == "ul" {+ style.list_style = Some(crate::ListStyle::Disc);+ } else if tag == "ol" {+ style.list_style = Some(crate::ListStyle::Decimal);+ }} else if tag == "li" {style.margin = Edges { top: 0.0, bottom: 0.0, left: 40.0, right: 0.0 };- } else if tag == "b" || tag == "strong" || tag == "th" {+ } else if tag == "b" || tag == "strong" {style.font_weight = Some("bold".to_string());+ } else if tag == "i" || tag == "em" || tag == "cite" || tag == "var" || tag == "dfn" || tag == "address" {+ style.font_style_italic = Some(true);} else if tag == "a" {style.color = Some([0, 0, 238, 255]); // blue+ style.underline = Some(true); // UA default: links are underlined} else if tag == "table" || tag == "tbody" {style.display = Display::Flex;style.flex_direction = Some(taffy::FlexDirection::Column);- style.align_items = Some(taffy::AlignItems::Stretch); // stretch rows to fill table width+ style.align_items = Some(taffy::AlignItems::STRETCH); // stretch rows to fill table width+ // Rows fill the table width and may shrink below their content's+ // min-content size (the flexbox automatic-minimum-size gotcha), so a+ // width-constrained taxobox contains its content instead of blowing+ // out sideways. (Fully matching CSS auto table layout, where a table+ // grows to fit unshrinkable content, needs real table layout.)+ style.min_width = crate::Dimension::Px(0.0);+ if tag == "tbody" {+ style.width = crate::Dimension::Percent(1.0);+ }+ } else if tag == "tr" {+ // Rows fill the table width and can shrink below content min-content;+ // this is exactly why Wikipedia's own responsive CSS uses+ // `tr{min-width:100%}`. `align-items:stretch` alone did not pin them+ // once a cell's content (a 250px no-wrap widget) exceeded the box.+ style.min_width = crate::Dimension::Px(0.0);+ style.width = crate::Dimension::Percent(1.0);} else if tag == "td" || tag == "th" {style.display = Display::Flex;style.flex_direction = Some(taffy::FlexDirection::Column);- style.align_items = Some(taffy::AlignItems::FlexStart);+ style.align_items = Some(taffy::AlignItems::FLEX_START);style.padding = Edges { top: 0.0, right: 5.0, bottom: 0.0, left: 0.0 };+ style.min_width = crate::Dimension::Px(0.0);+ if tag == "th" {+ style.font_weight = Some("bold".to_string());+ }+ } else if tag == "img" || tag == "figure" {+ // Near-universal reset: images fit their container instead of+ // overflowing. Wikipedia (and most sites) set `img{max-width:100%}`;+ // making it a UA default prevents a fixed-width thumbnail (e.g. a+ // 250px infobox image) from spilling out of a narrower box (a 200px+ // taxobox) when we have not applied the site's own rule.+ style.max_width = crate::Dimension::Percent(1.0);+ style.flex_shrink = Some(1.0);}style}@@ -86,14 +153,18 @@ pub fn apply_inline(style: &mut LayoutStyle, css: &str) {}let Some((name, value)) = decl.split_once(':') else { continue };let name = name.trim().to_ascii_lowercase();- // Drop `!important`: it does not change the computed value here.- let value: String = value- .trim()- .split_whitespace()- .take_while(|t| !t.eq_ignore_ascii_case("!important") && *t != "!")- .collect::<Vec<_>>()- .join(" ");- apply_value(style, &name, &value);+ // Drop a trailing `!important` (priority does not change the computed+ // value here). Strip by position, not by whitespace token: minified CSS+ // writes it with no space (`width:281px!important`), and splitting on+ // whitespace left that glued onto the value so the whole declaration+ // failed to parse and was lost.+ let mut value = value.trim();+ if let Some(bang) = value.rfind('!') {+ if value[bang + 1..].trim().eq_ignore_ascii_case("important") {+ value = value[..bang].trim_end();+ }+ }+ apply_value(style, &name, value);}}@@ -103,7 +174,7 @@ pub fn apply_inline(style: &mut LayoutStyle, css: &str) {/// (`content: "a; b"`) routinely contains a literal semicolon that is not a/// declaration separator; splitting on every `;` blindly corrupts the/// declaration into two malformed halves and silently drops it.-fn split_declarations(css: &str) -> Vec<&str> {+pub(crate) fn split_declarations(css: &str) -> Vec<&str> {let mut parts = Vec::new();let mut depth = 0i32;let mut in_quote: Option<char> = None;@@ -117,8 +188,13 @@ fn split_declarations(css: &str) -> Vec<&str> {}match c {'\'' | '"' => in_quote = Some(c),- '(' => depth += 1,- ')' => depth -= 1,+ // Track `{...}` too: once @layer bodies are admitted, CSS-nested+ // rules (`&:hover{a:b}`, nested @media) appear inside declaration+ // lists. Keeping a nested block as one chunk makes it a single+ // unparseable declaration that is dropped, rather than leaking its+ // inner declarations into the parent rule at the first `;`.+ '(' | '{' => depth += 1,+ ')' | '}' => depth = (depth - 1).max(0),';' if depth == 0 => {parts.push(&css[start..i]);start = i + 1;@@ -132,33 +208,69 @@ fn split_declarations(css: &str) -> Vec<&str> {fn apply_value(style: &mut LayoutStyle, name: &str, value: &str) {match name {- "display" => match value {- "none" => style.display = crate::Display::None,- "flex" => style.display = crate::Display::Flex,- "inline-flex" => style.display = crate::Display::Flex,- "inline" => style.display = crate::Display::Inline,- "inline-block" => style.display = crate::Display::Inline,- "grid" => style.display = crate::Display::Grid,- "inline-grid" => style.display = crate::Display::Grid,- "block" => style.display = crate::Display::Block,- _ => {}- },- "width" => style.width = dimension_value(value),- "height" => style.height = dimension_value(value),+ "display" => {+ if value != "contents" {+ style.display_contents = false;+ }+ match value {+ "none" => style.display = crate::Display::None,+ "flex" => style.display = crate::Display::Flex,+ "inline-flex" => style.display = crate::Display::Flex,+ "inline" => style.display = crate::Display::Inline,+ "inline-block" => {+ style.display = crate::Display::Inline;+ style.is_inline_block = true;+ }+ "grid" => style.display = crate::Display::Grid,+ "inline-grid" => style.display = crate::Display::Grid,+ "block" => style.display = crate::Display::Block,+ "contents" => style.display_contents = true,+ _ => {}+ }+ }+ "width" => {+ style.width = dimension_value(value);+ style.width_set = true;+ }+ "height" => {+ style.height = dimension_value(value);+ style.height_set = true;+ }"min-width" => style.min_width = dimension_value(value),"min-height" => style.min_height = dimension_value(value),"max-width" => style.max_width = dimension_value(value),"max-height" => style.max_height = dimension_value(value),- "margin" => { if let Some(e) = edges(value) { style.margin = e; } }- "margin-top" => set_edge(&mut style.margin, Side::Top, px(value)),- "margin-right" => set_edge(&mut style.margin, Side::Right, px(value)),- "margin-bottom" => set_edge(&mut style.margin, Side::Bottom, px(value)),- "margin-left" => set_edge(&mut style.margin, Side::Left, px(value)),+ "aspect-ratio" => style.aspect_ratio = parse_aspect_ratio(value),+ "margin" => apply_margin_shorthand(style, value),+ "margin-top" => set_margin_side(style, 0, value),+ "margin-right" => set_margin_side(style, 1, value),+ "margin-bottom" => set_margin_side(style, 2, value),+ "margin-left" => set_margin_side(style, 3, value),+ // Logical margins (LTR: inline = left/right, block = top/bottom).+ "margin-inline" => { let (s, e) = two(value); set_margin_side(style, 3, s); set_margin_side(style, 1, e); }+ "margin-inline-start" => set_margin_side(style, 3, value),+ "margin-inline-end" => set_margin_side(style, 1, value),+ "margin-block" => { let (s, e) = two(value); set_margin_side(style, 0, s); set_margin_side(style, 2, e); }+ "margin-block-start" => set_margin_side(style, 0, value),+ "margin-block-end" => set_margin_side(style, 2, value),"padding" => { if let Some(e) = edges(value) { style.padding = e; } }"padding-top" => set_edge(&mut style.padding, Side::Top, px(value)),"padding-right" => set_edge(&mut style.padding, Side::Right, px(value)),"padding-bottom" => set_edge(&mut style.padding, Side::Bottom, px(value)),"padding-left" => set_edge(&mut style.padding, Side::Left, px(value)),+ "padding-inline" => { let (s, e) = two(value); set_edge(&mut style.padding, Side::Left, px(s)); set_edge(&mut style.padding, Side::Right, px(e)); }+ "padding-inline-start" => set_edge(&mut style.padding, Side::Left, px(value)),+ "padding-inline-end" => set_edge(&mut style.padding, Side::Right, px(value)),+ "padding-block" => { let (s, e) = two(value); set_edge(&mut style.padding, Side::Top, px(s)); set_edge(&mut style.padding, Side::Bottom, px(e)); }+ "padding-block-start" => set_edge(&mut style.padding, Side::Top, px(value)),+ "padding-block-end" => set_edge(&mut style.padding, Side::Bottom, px(value)),+ "border-radius" => {+ // Uniform radius from the first value (ignore per-corner / the+ // `/` vertical-radius form; the common case is one length).+ if let Some(r) = value.split(['/', ' ']).next().and_then(|t| px(t)) {+ style.border_radius = r;+ }+ }"border" => {for p in value.split_whitespace() {if let Some(c) = parse_color(p) {@@ -175,46 +287,75 @@ fn apply_value(style: &mut LayoutStyle, name: &str, value: &str) {"border-left-width" | "border-left" => set_edge(&mut style.border, Side::Left, px(value)),"background-color" => style.background_color = parse_color(value),"background" => {- style.background_color = parse_color(value);+ style.background_gradient = parse_linear_gradient(value);+ if style.background_gradient.is_none() {+ style.background_color = parse_color(value);+ }+ style.background_image = parse_url(value);+ }+ "background-image" => {+ style.background_gradient = parse_linear_gradient(value);style.background_image = parse_url(value);}- "background-image" => style.background_image = parse_url(value),"background-size" => style.background_size = parse_background_size(value),"background-position" => style.background_position = parse_background_position(value),"mask-image" | "-webkit-mask-image" => style.mask_image = parse_url(value),"color" => style.color = parse_color(value),"border-color" => style.border_color = parse_color(value),- "font-size" => style.font_size = px(value),- "font-weight" => style.font_weight = Some(value.to_string()),+ "font-size" => {+ // Absolute lengths resolve now; font/viewport-relative ones defer+ // to the inheritance pass (they need parent/root font-size).+ match dimension_value(value) {+ crate::Dimension::Px(p) => {+ style.font_size = Some(p);+ style.font_size_raw = None;+ }+ crate::Dimension::Auto => {+ // Keyword sizes (medium/small/large/...) or unknown; map the+ // common ones, else leave to inherit.+ if let Some(px) = font_size_keyword(value.trim()) {+ style.font_size = Some(px);+ }+ }+ rel => style.font_size_raw = Some(rel),+ }+ }+ "font-weight" => {+ // Normalize to "bold"/"normal" (consumers test for "bold"). Numeric+ // >= 600 and `bold`/`bolder` are bold; others normal.+ let v = value.trim().to_ascii_lowercase();+ let bold = v == "bold" || v == "bolder" || v.parse::<u32>().map(|n| n >= 600).unwrap_or(false);+ style.font_weight = Some(if bold { "bold".to_string() } else { "normal".to_string() });+ }// Our engine has no real inline formatting context, so text-align is// approximated the same way as align-items: it positions a block's// (or column-flex's) children along the cross axis. See// `to_taffy_style`'s block-to-flex-column promotion, which is what// makes this actually take effect on plain block elements."text-align" => match value {- "right" => style.align_items = Some(taffy::AlignItems::FlexEnd),- "center" => style.align_items = Some(taffy::AlignItems::Center),- "left" | "start" | "justify" => style.align_items = Some(taffy::AlignItems::FlexStart),+ "right" => style.align_items = Some(taffy::AlignItems::FLEX_END),+ "center" => style.align_items = Some(taffy::AlignItems::CENTER),+ "left" | "start" | "justify" => style.align_items = Some(taffy::AlignItems::FLEX_START),_ => {}},"align-items" => {match value {- "center" => style.align_items = Some(taffy::AlignItems::Center),- "flex-start" | "start" => style.align_items = Some(taffy::AlignItems::FlexStart),- "flex-end" | "end" => style.align_items = Some(taffy::AlignItems::FlexEnd),- "stretch" => style.align_items = Some(taffy::AlignItems::Stretch),- "baseline" => style.align_items = Some(taffy::AlignItems::Baseline),+ "center" => style.align_items = Some(taffy::AlignItems::CENTER),+ "flex-start" | "start" => style.align_items = Some(taffy::AlignItems::FLEX_START),+ "flex-end" | "end" => style.align_items = Some(taffy::AlignItems::FLEX_END),+ "stretch" => style.align_items = Some(taffy::AlignItems::STRETCH),+ "baseline" => style.align_items = Some(taffy::AlignItems::BASELINE),_ => {}}},"justify-content" => {match value {- "center" => style.justify_content = Some(taffy::JustifyContent::Center),- "flex-start" | "start" | "left" => style.justify_content = Some(taffy::JustifyContent::FlexStart),- "flex-end" | "end" | "right" => style.justify_content = Some(taffy::JustifyContent::FlexEnd),- "space-between" => style.justify_content = Some(taffy::JustifyContent::SpaceBetween),- "space-around" => style.justify_content = Some(taffy::JustifyContent::SpaceAround),- "space-evenly" => style.justify_content = Some(taffy::JustifyContent::SpaceEvenly),+ "center" => style.justify_content = Some(taffy::JustifyContent::CENTER),+ "flex-start" | "start" | "left" => style.justify_content = Some(taffy::JustifyContent::FLEX_START),+ "flex-end" | "end" | "right" => style.justify_content = Some(taffy::JustifyContent::FLEX_END),+ "space-between" => style.justify_content = Some(taffy::JustifyContent::SPACE_BETWEEN),+ "space-around" => style.justify_content = Some(taffy::JustifyContent::SPACE_AROUND),+ "space-evenly" => style.justify_content = Some(taffy::JustifyContent::SPACE_EVENLY),_ => {}}},@@ -237,6 +378,8 @@ fn apply_value(style: &mut LayoutStyle, name: &str, value: &str) {},"flex-grow" => { if let Some(v) = token(value).and_then(|t| t.parse::<f32>().ok()) { style.flex_grow = Some(v); } }"flex-shrink" => { if let Some(v) = token(value).and_then(|t| t.parse::<f32>().ok()) { style.flex_shrink = Some(v); } }+ "flex-basis" => { style.flex_basis = dimension_value(value.trim()); }+ "flex" => parse_flex_shorthand(style, value),"position" => {match value {"absolute" | "fixed" => style.position = Some(taffy::Position::Absolute),@@ -252,21 +395,98 @@ fn apply_value(style: &mut LayoutStyle, name: &str, value: &str) {_ => {}}},- "top" => style.inset[0] = px(value),- "right" => style.inset[1] = px(value),- "bottom" => style.inset[2] = px(value),- "left" => style.inset[3] = px(value),+ "top" => style.inset[0] = inset_dim(value),+ "right" => style.inset[1] = inset_dim(value),+ "bottom" => style.inset[2] = inset_dim(value),+ "left" => style.inset[3] = inset_dim(value),+ "inset" => {+ // 1-4 values, CSS shorthand order: all / v h / t h b / t r b l.+ let parts: Vec<crate::Dimension> = value.split_whitespace().map(dimension_value).collect();+ let (t, r, b, l) = match parts.as_slice() {+ [a] => (*a, *a, *a, *a),+ [v, h] => (*v, *h, *v, *h),+ [t, h, b] => (*t, *h, *b, *h),+ [t, r, b, l, ..] => (*t, *r, *b, *l),+ [] => return,+ };+ style.inset = [Some(t), Some(r), Some(b), Some(l)];+ }"overflow" | "overflow-x" | "overflow-y" => {style.overflow_hidden = value != "visible";}+ "visibility" => style.visibility_hidden = Some(value.eq_ignore_ascii_case("hidden")),+ "opacity" => style.opacity = value.trim().parse::<f32>().ok(),+ "list-style-type" => {+ style.list_style = Some(list_style_keyword(value.trim()).unwrap_or(crate::ListStyle::Disc));+ }+ "list-style" => {+ // Shorthand: type | position | image in any order. We only track+ // the type keyword (and `none`, which suppresses the marker, the+ // common way nav `<ul>`s drop their bullets).+ for tok in value.split_whitespace() {+ if let Some(ls) = list_style_keyword(tok) {+ style.list_style = Some(ls);+ }+ }+ }+ "line-height" => {+ let v = value.trim();+ style.line_height = if v.eq_ignore_ascii_case("normal") {+ Some(crate::LineHeight::Normal)+ } else if let Some(pct) = v.strip_suffix('%') {+ pct.trim().parse::<f32>().ok().map(|n| crate::LineHeight::Ratio(n / 100.0))+ } else if v.ends_with("rem") || v.ends_with("em") {+ // em/rem in line-height are relative to font-size, i.e. a ratio.+ v.trim_end_matches("rem").trim_end_matches("em").trim().parse::<f32>().ok().map(crate::LineHeight::Ratio)+ } else if v.ends_with("px") || v.ends_with("pt") {+ px_value(v).map(crate::LineHeight::Px)+ } else {+ // Unitless number: a multiple of font-size (the common case).+ v.parse::<f32>().ok().map(crate::LineHeight::Ratio)+ };+ }+ "font-style" => {+ let v = value.trim().to_ascii_lowercase();+ style.font_style_italic = Some(v.starts_with("italic") || v.starts_with("oblique"));+ }+ "text-transform" => {+ style.text_transform = Some(match value.trim().to_ascii_lowercase().as_str() {+ "uppercase" => crate::TextTransform::Uppercase,+ "lowercase" => crate::TextTransform::Lowercase,+ "capitalize" => crate::TextTransform::Capitalize,+ _ => crate::TextTransform::None,+ });+ }+ "text-decoration" | "text-decoration-line" => {+ // Shorthand can carry color/style/thickness; we only model the+ // underline line (the dominant case, and the UA default for links).+ let toks: Vec<String> = value.split_whitespace().map(|t| t.to_ascii_lowercase()).collect();+ let underline = toks.iter().any(|t| t == "underline");+ let none = toks.iter().any(|t| t == "none");+ style.underline = Some(underline && !none);+ }"gap" | "grid-gap" => {let dims: Vec<f32> = value.split_whitespace().filter_map(px_value).collect();if let Some(&r) = dims.first() { style.row_gap = Some(r); style.column_gap = Some(*dims.get(1).unwrap_or(&r)); }}"row-gap" | "grid-row-gap" => style.row_gap = px(value),"column-gap" | "grid-column-gap" => style.column_gap = px(value),- "grid-template-columns" => style.grid_template_columns = parse_track_list(value),- "grid-template-rows" => style.grid_template_rows = parse_track_list(value),+ "border-spacing" => {+ let dims: Vec<f32> = value.split_whitespace().filter_map(px_value).collect();+ if let Some(&h) = dims.first() {+ style.border_spacing = Some((h, *dims.get(1).unwrap_or(&h)));+ }+ }+ "grid-template-columns" => {+ let (tracks, names) = parse_track_list_named(value);+ style.grid_template_columns = tracks;+ style.grid_col_line_names = (!names.is_empty()).then(|| build_line_map(names));+ }+ "grid-template-rows" => {+ let (tracks, names) = parse_track_list_named(value);+ style.grid_template_rows = tracks;+ style.grid_row_line_names = (!names.is_empty()).then(|| build_line_map(names));+ }"grid-template-areas" => style.grid_areas = Some(parse_grid_areas(value)),"grid-template" => parse_grid_template(style, value),"grid-area" => {@@ -277,8 +497,8 @@ fn apply_value(style: &mut LayoutStyle, name: &str, value: &str) {style.grid_area_name = Some(v.to_string());}}- "grid-column" => style.grid_column = parse_grid_line(value),- "grid-row" => style.grid_row = parse_grid_line(value),+ "grid-column" => set_grid_placement(style, value, true),+ "grid-row" => set_grid_placement(style, value, false),_ => {}}}@@ -286,20 +506,77 @@ fn apply_value(style: &mut LayoutStyle, name: &str, value: &str) {/// Parse a CSS grid track list (`min-content 1fr min-content`, `12.25rem/// minmax(0,1fr)`) into taffy sizing functions. Tokenizes respecting the/// parentheses in `minmax(...)` / `fit-content(...)`.-pub(crate) fn parse_track_list(value: &str) -> Vec<taffy::TrackSizingFunction> {- tokenize_tracks(value).iter().map(|t| track(t)).collect()+/// Parse a track list into taffy sizing functions plus the `[line-name]` map+/// (name -> 1-based grid line number). `repeat(n, ...)` is expanded to n copies+/// (it was previously collapsed to a single phantom `Auto` track, which broke+/// every `repeat()`-based grid) and `[name]` annotations are captured, not+/// turned into tracks. First occurrence of a name wins.+pub(crate) fn parse_track_list_named(value: &str) -> (Vec<taffy::TrackSizingFunction>, Vec<(String, i16)>) {+ let mut tracks = Vec::new();+ let mut names = Vec::new();+ let mut line: i16 = 1;+ for tok in tokenize_tracks(value) {+ expand_track_token(&tok, &mut tracks, &mut names, &mut line);+ }+ (tracks, names)+}++fn expand_track_token(+ tok: &str,+ tracks: &mut Vec<taffy::TrackSizingFunction>,+ names: &mut Vec<(String, i16)>,+ line: &mut i16,+) {+ let t = tok.trim();+ if t.starts_with('[') {+ let inner = t.trim_start_matches('[').trim_end_matches(']');+ for name in inner.split_whitespace() {+ names.push((name.to_string(), *line));+ }+ return;+ }+ let lower = t.to_ascii_lowercase();+ if lower.starts_with("repeat(") && t.ends_with(')') {+ let inner = &t["repeat(".len()..t.len() - 1];+ if let Some((cnt, sub)) = inner.split_once(',') {+ // `auto-fill`/`auto-fit` counts need the container width; fall back+ // to one repetition (a reasonable minimum) rather than dropping it.+ let count = cnt.trim().parse::<usize>().unwrap_or(1).min(1000);+ let subtoks = tokenize_tracks(sub.trim());+ for _ in 0..count {+ for st in &subtoks {+ expand_track_token(st, tracks, names, line);+ }+ }+ }+ return;+ }+ tracks.push(track(t));+ *line += 1;}-/// Split a track list on whitespace while keeping `func(a, b)` groups intact.+pub(crate) fn build_line_map(pairs: Vec<(String, i16)>) -> std::collections::HashMap<String, i16> {+ let mut m = std::collections::HashMap::new();+ for (name, line) in pairs {+ m.entry(name).or_insert(line);+ }+ m+}++/// Split a track list on whitespace while keeping `func(a, b)` groups and+/// `[line-name lists]` intact.fn tokenize_tracks(value: &str) -> Vec<String> {let mut out = Vec::new();let mut cur = String::new();let mut depth = 0i32;+ let mut in_bracket = false;for c in value.chars() {match c {+ '[' => { in_bracket = true; cur.push(c); }+ ']' => { in_bracket = false; cur.push(c); }'(' => { depth += 1; cur.push(c); }')' => { depth -= 1; cur.push(c); }- c if c.is_whitespace() && depth == 0 => {+ c if c.is_whitespace() && depth == 0 && !in_bracket => {if !cur.is_empty() { out.push(std::mem::take(&mut cur)); }}c => cur.push(c),@@ -315,38 +592,36 @@ fn track(tok: &str) -> taffy::TrackSizingFunction {let lower = t.to_ascii_lowercase();if let Some(inner) = lower.strip_prefix("minmax(").and_then(|s| s.strip_suffix(')')) {if let Some((a, b)) = inner.split_once(',') {- return taffy::TrackSizingFunction::Single(MinMax {- min: min_track(a.trim()),- max: max_track(b.trim()),- });+ return MinMax { min: min_track(a.trim()), max: max_track(b.trim()) };}}if let Some(inner) = lower.strip_prefix("fit-content(").and_then(|s| s.strip_suffix(')')) {- let lp = px_value(inner.trim())- .map(taffy::style::LengthPercentage::Length)- .unwrap_or(taffy::style::LengthPercentage::Length(0.0));- return taffy::TrackSizingFunction::Single(MinMax {- min: taffy::MinTrackSizingFunction::Auto,- max: taffy::MaxTrackSizingFunction::FitContent(lp),- });+ let px = px_value(inner.trim()).unwrap_or(0.0);+ return MinMax {+ min: taffy::MinTrackSizingFunction::auto(),+ max: taffy::MaxTrackSizingFunction::fit_content_px(px),+ };}- taffy::TrackSizingFunction::Single(MinMax { min: min_track(t), max: max_track(t) })+ MinMax { min: min_track(t), max: max_track(t) }}fn min_track(tok: &str) -> taffy::MinTrackSizingFunction {use taffy::MinTrackSizingFunction as M;- match tok.to_ascii_lowercase().as_str() {- "min-content" => M::MinContent,- "max-content" => M::MaxContent,- "auto" => M::Auto,+ let lower = tok.to_ascii_lowercase();+ match lower.as_str() {+ "min-content" => M::min_content(),+ "max-content" => M::max_content(),+ "auto" => M::auto(),other => {if other.ends_with("fr") {// Flexible tracks have an automatic minimum.- M::Auto- } else if let Some(px) = dim_lp(other) {- M::Fixed(px)+ M::auto()+ } else if let Some(p) = other.strip_suffix('%').and_then(|n| n.trim().parse::<f32>().ok()) {+ M::percent(p / 100.0)+ } else if let Some(px) = px_value(other) {+ M::length(px)} else {- M::Auto+ M::auto()}}}@@ -356,30 +631,23 @@ fn max_track(tok: &str) -> taffy::MaxTrackSizingFunction {use taffy::MaxTrackSizingFunction as M;let lower = tok.to_ascii_lowercase();match lower.as_str() {- "min-content" => M::MinContent,- "max-content" => M::MaxContent,- "auto" => M::Auto,+ "min-content" => M::min_content(),+ "max-content" => M::max_content(),+ "auto" => M::auto(),other => {if let Some(fr) = other.strip_suffix("fr").and_then(|n| n.trim().parse::<f32>().ok()) {- M::Fraction(fr)- } else if let Some(px) = dim_lp(other) {- M::Fixed(px)+ M::fr(fr)+ } else if let Some(p) = other.strip_suffix('%').and_then(|n| n.trim().parse::<f32>().ok()) {+ M::percent(p / 100.0)+ } else if let Some(px) = px_value(other) {+ M::length(px)} else {- M::Auto+ M::auto()}}}}-/// A length or percentage as a taffy `LengthPercentage`.-fn dim_lp(tok: &str) -> Option<taffy::style::LengthPercentage> {- let t = tok.trim();- if let Some(p) = t.strip_suffix('%') {- return p.parse::<f32>().ok().map(|v| taffy::style::LengthPercentage::Percent(v / 100.0));- }- px_value(t).map(taffy::style::LengthPercentage::Length)-}-/// Parse `grid-template-areas: 'a a' 'b c'` into a matrix of cell names.fn parse_grid_areas(value: &str) -> Vec<Vec<String>> {let mut rows = Vec::new();@@ -415,13 +683,56 @@ fn parse_grid_template(style: &mut LayoutStyle, value: &str) {// Rows side carries area strings interleaved with row track sizes.style.grid_areas = Some(parse_grid_areas(rows_part));} else if !rows_part.is_empty() {- style.grid_template_rows = parse_track_list(rows_part);+ let (tracks, names) = parse_track_list_named(rows_part);+ style.grid_template_rows = tracks;+ style.grid_row_line_names = (!names.is_empty()).then(|| build_line_map(names));}if let Some(cols) = cols_part {- style.grid_template_columns = parse_track_list(cols);+ let (tracks, names) = parse_track_list_named(cols);+ style.grid_template_columns = tracks;+ style.grid_col_line_names = (!names.is_empty()).then(|| build_line_map(names));+ }+}++/// Store a `grid-column`/`grid-row` value. Numeric/`span` forms resolve to a+/// `taffy::Line` now; a value that names a grid line (`content-start /+/// content-end`, or the `grid-column: content` area shorthand) is kept raw and+/// resolved against the parent's line-name map in `dom::resolve_grid_areas`.+/// Whichever representation is set, the other is cleared so a later cascade+/// rule of the opposite kind fully overrides it.+fn set_grid_placement(style: &mut LayoutStyle, value: &str, is_col: bool) {+ if grid_line_has_name(value) {+ let raw = Some(value.trim().to_string());+ if is_col {+ style.grid_column_raw = raw;+ style.grid_column = None;+ } else {+ style.grid_row_raw = raw;+ style.grid_row = None;+ }+ } else {+ let line = parse_grid_line(value);+ if is_col {+ style.grid_column = line;+ style.grid_column_raw = None;+ } else {+ style.grid_row = line;+ style.grid_row_raw = None;+ }}}+/// True when a `grid-column`/`grid-row` value references a named line (any+/// alphabetic token that is not a bare `span <n>` count), so it must defer to+/// the parent's line-name map.+fn grid_line_has_name(value: &str) -> bool {+ value.split('/').any(|part| {+ let p = part.trim();+ let rest = p.strip_prefix("span").map(str::trim).unwrap_or(p);+ rest.chars().any(|c| c.is_ascii_alphabetic())+ })+}+/// Parse `grid-column`/`grid-row` values: `2`, `1 / 3`, `span 2`.fn parse_grid_line(value: &str) -> Option<taffy::Line<taffy::GridPlacement>> {let place = |tok: &str| -> taffy::GridPlacement {@@ -480,6 +791,99 @@ pub(crate) fn parse_color(value: &str) -> Option<[u8; 4]> {}return None;}+ // hsl()/hsla() functional notation.+ if let Some(rest) = lower_full.strip_prefix("hsl(").or_else(|| lower_full.strip_prefix("hsla(")) {+ let inner = rest.strip_suffix(')').unwrap_or(rest);+ let parts: Vec<&str> = inner.split([',', '/', ' ']).filter(|p| !p.trim().is_empty()).collect();+ if parts.len() >= 3 {+ let h = parts[0].trim().trim_end_matches("deg").parse::<f32>().ok()?;+ let s = parts[1].trim().trim_end_matches('%').parse::<f32>().ok()? / 100.0;+ let l = parts[2].trim().trim_end_matches('%').parse::<f32>().ok()? / 100.0;+ let a = parts.get(3)+ .and_then(|s| s.trim().trim_end_matches('%').parse::<f32>().ok())+ .map(|v| if parts[3].contains('%') { (v * 2.55).round() } else { (v * 255.0).round() }.clamp(0.0, 255.0) as u8)+ .unwrap_or(255);+ return Some(hsl_to_rgba(h, s.clamp(0.0, 1.0), l.clamp(0.0, 1.0), a));+ }+ return None;+ }+ // oklch()/oklab() - Tailwind v4's entire palette. Convert through OKLab to+ // sRGB; without this every modern-framework color resolved to nothing.+ if lower_full.starts_with("oklch(") || lower_full.starts_with("oklab(") {+ let is_lch = lower_full.starts_with("oklch(");+ let inner = &lower_full[if is_lch { 6 } else { 6 }..];+ let inner = inner.strip_suffix(')').unwrap_or(inner);+ let (main, alpha) = match inner.split_once('/') {+ Some((m, a)) => (m, Some(a)),+ None => (inner, None),+ };+ let comps: Vec<&str> = main.split([',', ' ']).filter(|p| !p.trim().is_empty()).collect();+ if comps.len() >= 3 {+ let num = |s: &str| -> Option<f32> {+ let s = s.trim();+ s.strip_suffix('%').map(|p| p.parse::<f32>().map(|v| v / 100.0)).unwrap_or_else(|| s.parse::<f32>())+ .ok()+ };+ let l = num(comps[0])?;+ let c = num(comps[1])?;+ let a = alpha+ .and_then(|s| {+ let s = s.trim();+ s.strip_suffix('%').map(|p| p.parse::<f32>().map(|v| v / 100.0)).unwrap_or_else(|| s.parse::<f32>()).ok()+ })+ .unwrap_or(1.0);+ let (oa, ob) = if is_lch {+ let h = comps[2].trim().trim_end_matches("deg").parse::<f32>().ok()?;+ let hr = h.to_radians();+ (c * hr.cos(), c * hr.sin())+ } else {+ (c, comps[2].trim().parse::<f32>().ok()?)+ };+ return Some(oklab_to_rgba(l, oa, ob, (a * 255.0).round().clamp(0.0, 255.0) as u8));+ }+ return None;+ }+ // color-mix(in <space>, c1 p1%, c2 p2%) - Tailwind v4 uses this pervasively,+ // usually `color-mix(in oklab, <color> N%, transparent)` to apply opacity.+ if lower_full.starts_with("color-mix(") {+ let inner = raw[raw.to_ascii_lowercase().find("color-mix(").unwrap() + "color-mix(".len()..].trim_end();+ let inner = inner.strip_suffix(')').unwrap_or(inner);+ let args = split_top_commas(inner);+ if args.len() >= 3 {+ let parse_arg = |s: &str| -> Option<([u8; 4], Option<f32>)> {+ let s = s.trim();+ if let Some(idx) = s.rfind(char::is_whitespace) {+ let tail = s[idx + 1..].trim();+ if let Some(p) = tail.strip_suffix('%').and_then(|x| x.parse::<f32>().ok()) {+ return parse_color(s[..idx].trim()).map(|c| (c, Some(p / 100.0)));+ }+ }+ parse_color(s).map(|c| (c, None))+ };+ if let (Some((c1, p1)), Some((c2, p2))) = (parse_arg(args[1]), parse_arg(args[2])) {+ let (w1, w2) = match (p1, p2) {+ (Some(a), Some(b)) => (a, b),+ (Some(a), None) => (a, 1.0 - a),+ (None, Some(b)) => (1.0 - b, b),+ (None, None) => (0.5, 0.5),+ };+ let tot = (w1 + w2).max(1e-6);+ let (w1, w2) = (w1 / tot, w2 / tot);+ // Mixing with a fully transparent color is the opacity idiom:+ // keep the visible color, scale its alpha (not toward black).+ if c2[3] == 0 {+ return Some([c1[0], c1[1], c1[2], (c1[3] as f32 * w1).round().clamp(0.0, 255.0) as u8]);+ }+ if c1[3] == 0 {+ return Some([c2[0], c2[1], c2[2], (c2[3] as f32 * w2).round().clamp(0.0, 255.0) as u8]);+ }+ let m = |i: usize| (c1[i] as f32 * w1 + c2[i] as f32 * w2).round().clamp(0.0, 255.0) as u8;+ return Some([m(0), m(1), m(2), m(3)]);+ }+ }+ return None;+ }+let v = value.split_whitespace().next()?.to_ascii_lowercase();if let Some(h) = v.strip_prefix('#') {let (r, g, b, a) = match h.len() {@@ -534,10 +938,184 @@ pub(crate) fn parse_color(value: &str) -> Option<[u8; 4]> {"fuchsia" | "magenta" => Some([255, 0, 255, 255]),"olive" => Some([128, 128, 0, 255]),"transparent" => Some([0, 0, 0, 0]),- _ => None,+ _ => named_color(&v),}}+/// The remaining common CSS named colors (the hot ones from real sites) beyond+/// the handful spelled out above.+fn named_color(v: &str) -> Option<[u8; 4]> {+ let rgb = match v {+ "darkblue" => [0, 0, 139],+ "mediumblue" => [0, 0, 205],+ "royalblue" => [65, 105, 225],+ "dodgerblue" => [30, 144, 255],+ "cornflowerblue" => [100, 149, 237],+ "steelblue" => [70, 130, 180],+ "deepskyblue" => [0, 191, 255],+ "skyblue" => [135, 206, 235],+ "lightskyblue" => [135, 206, 250],+ "lightblue" => [173, 216, 230],+ "powderblue" => [176, 224, 230],+ "cadetblue" => [95, 158, 160],+ "slateblue" => [106, 90, 205],+ "darkslateblue" => [72, 61, 139],+ "midnightblue" => [25, 25, 112],+ "indigo" => [75, 0, 130],+ "darkgreen" => [0, 100, 0],+ "forestgreen" => [34, 139, 34],+ "seagreen" => [46, 139, 87],+ "mediumseagreen" => [60, 179, 113],+ "limegreen" => [50, 205, 50],+ "yellowgreen" => [154, 205, 50],+ "olivedrab" => [107, 142, 35],+ "darkolivegreen" => [85, 107, 47],+ "greenyellow" => [173, 255, 47],+ "lightgreen" => [144, 238, 144],+ "palegreen" => [152, 251, 152],+ "springgreen" => [0, 255, 127],+ "mediumaquamarine" => [102, 205, 170],+ "aquamarine" => [127, 255, 212],+ "turquoise" => [64, 224, 208],+ "mediumturquoise" => [72, 209, 204],+ "darkcyan" => [0, 139, 139],+ "crimson" => [220, 20, 60],+ "firebrick" => [178, 34, 34],+ "darkred" => [139, 0, 0],+ "indianred" => [205, 92, 92],+ "tomato" => [255, 99, 71],+ "orangered" => [255, 69, 0],+ "coral" => [255, 127, 80],+ "salmon" => [250, 128, 114],+ "lightsalmon" => [255, 160, 122],+ "darksalmon" => [233, 150, 122],+ "hotpink" => [255, 105, 180],+ "deeppink" => [255, 20, 147],+ "pink" => [255, 192, 203],+ "lightpink" => [255, 182, 193],+ "palevioletred" => [219, 112, 147],+ "mediumvioletred" => [199, 21, 133],+ "violet" => [238, 130, 238],+ "orchid" => [218, 112, 214],+ "plum" => [221, 160, 221],+ "mediumpurple" => [147, 112, 219],+ "blueviolet" => [138, 43, 226],+ "darkviolet" => [148, 0, 211],+ "darkorchid" => [153, 50, 204],+ "darkmagenta" => [139, 0, 139],+ "lavender" => [230, 230, 250],+ "thistle" => [216, 191, 216],+ "gold" => [255, 215, 0],+ "goldenrod" => [218, 165, 32],+ "darkgoldenrod" => [184, 134, 11],+ "khaki" => [240, 230, 140],+ "darkkhaki" => [189, 183, 107],+ "peachpuff" => [255, 218, 185],+ "moccasin" => [255, 228, 181],+ "papayawhip" => [255, 239, 213],+ "wheat" => [245, 222, 179],+ "tan" => [210, 180, 140],+ "burlywood" => [222, 184, 135],+ "sandybrown" => [244, 164, 96],+ "peru" => [205, 133, 63],+ "chocolate" => [210, 105, 30],+ "sienna" => [160, 82, 45],+ "saddlebrown" => [139, 69, 19],+ "brown" => [165, 42, 42],+ "rosybrown" => [188, 143, 143],+ "darkorange" => [255, 140, 0],+ "lightyellow" => [255, 255, 224],+ "lightgoldenrodyellow" => [250, 250, 210],+ "lemonchiffon" => [255, 250, 205],+ "beige" => [245, 245, 220],+ "ivory" => [255, 255, 240],+ "azure" => [240, 255, 255],+ "mintcream" => [245, 255, 250],+ "honeydew" => [240, 255, 240],+ "snow" => [255, 250, 250],+ "seashell" => [255, 245, 238],+ "linen" => [250, 240, 230],+ "oldlace" => [253, 245, 230],+ "floralwhite" => [255, 250, 240],+ "ghostwhite" => [248, 248, 255],+ "aliceblue" => [240, 248, 255],+ "lavenderblush" => [255, 240, 245],+ "mistyrose" => [255, 228, 225],+ "cornsilk" => [255, 248, 220],+ "antiquewhite" => [250, 235, 215],+ "bisque" => [255, 228, 196],+ "blanchedalmond" => [255, 235, 205],+ "navajowhite" => [255, 222, 173],+ "dimgray" | "dimgrey" => [105, 105, 105],+ "slategray" | "slategrey" => [112, 128, 144],+ "lightslategray" | "lightslategrey" => [119, 136, 153],+ "darkslategray" | "darkslategrey" => [47, 79, 79],+ _ => return None,+ };+ Some([rgb[0], rgb[1], rgb[2], 255])+}++/// Convert `hsl()`/`hsla()` to RGBA. `h` in degrees, `s`/`l` as 0-1.+/// Convert an OKLab color (L in 0..1, a/b unbounded) to sRGB rgba bytes.+/// (oklch is converted to oklab by the caller.) Standard Björn Ottosson matrix.+fn oklab_to_rgba(l: f32, a: f32, b: f32, alpha: u8) -> [u8; 4] {+ let l_ = l + 0.3963377774 * a + 0.2158037573 * b;+ let m_ = l - 0.1055613458 * a - 0.0638541728 * b;+ let s_ = l - 0.0894841775 * a - 1.2914855480 * b;+ let (lc, mc, sc) = (l_ * l_ * l_, m_ * m_ * m_, s_ * s_ * s_);+ let lr = 4.0767416621 * lc - 3.3077115913 * mc + 0.2309699292 * sc;+ let lg = -1.2684380046 * lc + 2.6097574011 * mc - 0.3413193965 * sc;+ let lb = -0.0041960863 * lc - 0.7034186147 * mc + 1.7076147010 * sc;+ let enc = |x: f32| {+ let x = x.clamp(0.0, 1.0);+ let s = if x <= 0.0031308 { 12.92 * x } else { 1.055 * x.powf(1.0 / 2.4) - 0.055 };+ (s * 255.0).round().clamp(0.0, 255.0) as u8+ };+ [enc(lr), enc(lg), enc(lb), alpha]+}++/// Split on top-level commas, respecting nested `()` (so a `color-mix` argument+/// like `oklch(0.7 0.1 20)` or `var(--x, y)` is not shattered).+fn split_top_commas(s: &str) -> Vec<&str> {+ let mut out = Vec::new();+ let mut depth = 0i32;+ let mut start = 0;+ for (i, c) in s.char_indices() {+ match c {+ '(' => depth += 1,+ ')' => depth = (depth - 1).max(0),+ ',' if depth == 0 => {+ out.push(&s[start..i]);+ start = i + 1;+ }+ _ => {}+ }+ }+ out.push(&s[start..]);+ out+}++fn hsl_to_rgba(h: f32, s: f32, l: f32, a: u8) -> [u8; 4] {+ let h = ((h % 360.0) + 360.0) % 360.0;+ let c = (1.0 - (2.0 * l - 1.0).abs()) * s;+ let x = c * (1.0 - (((h / 60.0) % 2.0) - 1.0).abs());+ let m = l - c / 2.0;+ let (r, g, b) = match h as u32 / 60 {+ 0 => (c, x, 0.0),+ 1 => (x, c, 0.0),+ 2 => (0.0, c, x),+ 3 => (0.0, x, c),+ 4 => (x, 0.0, c),+ _ => (c, 0.0, x),+ };+ [+ (((r + m) * 255.0).round().clamp(0.0, 255.0)) as u8,+ (((g + m) * 255.0).round().clamp(0.0, 255.0)) as u8,+ (((b + m) * 255.0).round().clamp(0.0, 255.0)) as u8,+ a,+ ]+}+enum Side { Top, Right, Bottom, Left }fn set_edge(edges: &mut Edges, side: Side, v: Option<f32>) {@@ -595,8 +1173,21 @@ fn resolve_length(value: &str) -> Option<f32> {}return Some(best);}+ if let Some(rest) = v.strip_prefix("clamp(") {+ // clamp(min, preferred, max) == max(min, min(preferred, max)). Widely+ // used for responsive widths/font-sizes/gaps; returning None here made+ // any `width: clamp(...)` element collapse (svelte.dev's hero grid).+ let end = find_matching_paren(rest)?;+ let args = split_top_level(&rest[..end], ',');+ if args.len() == 3 {+ let lo = resolve_length(args[0].trim())?;+ let mid = resolve_length(args[1].trim())?;+ let hi = resolve_length(args[2].trim())?;+ return Some(mid.min(hi).max(lo));+ }+ }if v.contains('(') {- return None; // an unhandled function (clamp(), env(), ...): no safe fallback+ return None; // an unhandled function (env(), ...): no safe fallback}px_value(v).or_else(|| v.parse::<f32>().ok())}@@ -710,16 +1301,72 @@ fn eval_product(term: &str) -> Option<f32> {result}+/// Recognize a `list-style-type` / `list-style` keyword. Returns `None` for+/// tokens that are not list-style types (positions like `inside`, `url(...)`,+/// or unknown type names), so a shorthand scan can skip them.+fn list_style_keyword(tok: &str) -> Option<crate::ListStyle> {+ match tok.trim() {+ "none" => Some(crate::ListStyle::None),+ "disc" => Some(crate::ListStyle::Disc),+ "circle" => Some(crate::ListStyle::Circle),+ "square" => Some(crate::ListStyle::Square),+ "decimal" | "decimal-leading-zero" => Some(crate::ListStyle::Decimal),+ _ => None,+ }+}++/// An inset component (top/right/bottom/left). `auto` and absent both become+/// `None`; everything else keeps its (possibly relative) dimension for the+/// resolution pass.+fn inset_dim(value: &str) -> Option<crate::Dimension> {+ match dimension_value(value) {+ crate::Dimension::Auto => None,+ d => Some(d),+ }+}++/// Absolute keyword font-sizes (the `medium`-anchored scale), for the handful+/// of pages that still use them.+fn font_size_keyword(v: &str) -> Option<f32> {+ Some(match v.to_ascii_lowercase().as_str() {+ "xx-small" => 9.6,+ "x-small" => 12.0,+ "small" => 13.3,+ "medium" => 16.0,+ "large" => 18.0,+ "x-large" => 24.0,+ "xx-large" => 32.0,+ _ => return None,+ })+}+fn dimension_value(tok: &str) -> crate::Dimension {+ use crate::Dimension;let n = tok.trim();- if n.ends_with("%") {- if let Ok(v) = n[..n.len()-1].parse::<f32>() {- return crate::Dimension::Percent(v / 100.0);- }- } else if let Some(px) = px(tok) {- return crate::Dimension::Px(px);+ if n.eq_ignore_ascii_case("auto") || n.is_empty() {+ return Dimension::Auto;+ }+ // calc()/min()/max()/var(): resolve context-free to px where possible+ // (relative units inside are approximated; rare for these properties).+ if n.contains('(') {+ return px(n).map(Dimension::Px).unwrap_or(Dimension::Auto);}- crate::Dimension::Auto+ let lower = n.to_ascii_lowercase();+ let parse = |s: &str| s.trim().parse::<f32>().ok();+ if let Some(v) = lower.strip_suffix('%').and_then(parse) {+ return Dimension::Percent(v / 100.0);+ }+ // Order matters: check `rem` before `em`, `vmin`/`vmax` before `vw`/`vh`.+ if let Some(v) = lower.strip_suffix("rem").and_then(parse) { return Dimension::Rem(v); }+ if let Some(v) = lower.strip_suffix("em").and_then(parse) { return Dimension::Em(v); }+ if let Some(v) = lower.strip_suffix("vmin").and_then(parse) { return Dimension::Vmin(v); }+ if let Some(v) = lower.strip_suffix("vmax").and_then(parse) { return Dimension::Vmax(v); }+ if let Some(v) = lower.strip_suffix("vw").and_then(parse) { return Dimension::Vw(v); }+ if let Some(v) = lower.strip_suffix("vh").and_then(parse) { return Dimension::Vh(v); }+ if let Some(v) = lower.strip_suffix("px").and_then(parse) { return Dimension::Px(v); }+ if let Some(v) = lower.strip_suffix("pt").and_then(parse) { return Dimension::Px(v * 1.333); }+ if let Some(v) = parse(&lower) { return Dimension::Px(v); }+ Dimension::Auto}/// Parse every length token in a value as px (for box shorthands).@@ -728,6 +1375,47 @@ fn edges(value: &str) -> Option<Edges> {edges_from(dims)}+/// Split a 1-or-2 value shorthand into (start, end); a single value applies to+/// both. Used by the logical-property axes (`margin-inline`, `padding-block`).+fn two(value: &str) -> (&str, &str) {+ let mut it = value.split_whitespace();+ let a = it.next().unwrap_or("0");+ let b = it.next().unwrap_or(a);+ (a, b)+}++/// Set one margin side (0=top,1=right,2=bottom,3=left), tracking `auto`.+fn set_margin_side(style: &mut LayoutStyle, idx: usize, value: &str) {+ let v = value.trim();+ let is_auto = v.eq_ignore_ascii_case("auto");+ let px = if is_auto { 0.0 } else { px(value).unwrap_or(0.0) };+ match idx {+ 0 => style.margin.top = px,+ 1 => style.margin.right = px,+ 2 => style.margin.bottom = px,+ 3 => style.margin.left = px,+ _ => {}+ }+ style.margin_auto[idx] = is_auto;+}++/// `margin: <t> <r>? <b>? <l>?` with per-side `auto` (so `margin: 0 auto`+/// centers).+fn apply_margin_shorthand(style: &mut LayoutStyle, value: &str) {+ let toks: Vec<&str> = value.split_whitespace().collect();+ let (t, r, b, l) = match toks.as_slice() {+ [a] => (*a, *a, *a, *a),+ [v, h] => (*v, *h, *v, *h),+ [t, h, b] => (*t, *h, *b, *h),+ [t, r, b, l, ..] => (*t, *r, *b, *l),+ [] => return,+ };+ set_margin_side(style, 0, t);+ set_margin_side(style, 1, r);+ set_margin_side(style, 2, b);+ set_margin_side(style, 3, l);+}+fn px_value(tok: &str) -> Option<f32> {let mut n = tok;let mut scale = 1.0;@@ -757,6 +1445,123 @@ fn token(value: &str) -> Option<&str> {value.split_whitespace().next()}+/// Parse a `linear-gradient(...)` (also `repeating-`/`-webkit-`/`-moz-`) into+/// (angle-degrees, color stops). Angle is CSS convention (0deg = to top, grows+/// clockwise); `to <side>` keywords map to their angle. Color stops keep their+/// optional 0..1 position. Returns None if it is not a linear-gradient or has+/// no parseable colors. Radial/conic gradients are not handled (None).+fn parse_linear_gradient(value: &str) -> Option<(f32, Vec<([u8; 4], Option<f32>)>)> {+ let v = value.trim();+ let lower = v.to_ascii_lowercase();+ let start = lower.find("linear-gradient(")?;+ let open = start + "linear-gradient(".len();+ // Match the closing paren for this function.+ let bytes = v.as_bytes();+ let mut depth = 1;+ let mut end = open;+ while end < bytes.len() && depth > 0 {+ match bytes[end] {+ b'(' => depth += 1,+ b')' => depth -= 1,+ _ => {}+ }+ end += 1;+ }+ let inner = &v[open..end.saturating_sub(1)];+ // Split on top-level commas (respect rgb()/rgba()/hsl() parens).+ let mut parts: Vec<String> = Vec::new();+ let mut cur = String::new();+ let mut d = 0i32;+ for c in inner.chars() {+ match c {+ '(' => { d += 1; cur.push(c); }+ ')' => { d -= 1; cur.push(c); }+ ',' if d == 0 => { parts.push(std::mem::take(&mut cur)); }+ _ => cur.push(c),+ }+ }+ if !cur.trim().is_empty() {+ parts.push(cur);+ }+ if parts.is_empty() {+ return None;+ }+ // Leading angle / direction, if present.+ let mut angle = 180.0f32; // default: to bottom+ let first = parts[0].trim().to_ascii_lowercase();+ let mut stop_start = 0;+ if first.ends_with("deg") {+ if let Ok(a) = first.trim_end_matches("deg").trim().parse::<f32>() {+ angle = a;+ }+ stop_start = 1;+ } else if first.starts_with("to ") {+ angle = match first.as_str() {+ "to top" => 0.0, "to right" => 90.0, "to bottom" => 180.0, "to left" => 270.0,+ "to top right" | "to right top" => 45.0, "to bottom right" | "to right bottom" => 135.0,+ "to bottom left" | "to left bottom" => 225.0, "to top left" | "to left top" => 315.0,+ _ => 180.0,+ };+ stop_start = 1;+ } else if first.starts_with("turn") || first.ends_with("turn") {+ stop_start = 1;+ }+ let mut stops: Vec<([u8; 4], Option<f32>)> = Vec::new();+ for p in &parts[stop_start..] {+ let t = p.trim();+ if t.is_empty() {+ continue;+ }+ // "color [pos%]" - the color may itself contain spaces (rgb( ... )) so+ // split off a trailing percentage token if present.+ let (color_str, pos) = if let Some(idx) = t.rfind(char::is_whitespace) {+ let tail = t[idx + 1..].trim();+ if let Some(pct) = tail.strip_suffix('%').and_then(|s| s.parse::<f32>().ok()) {+ (t[..idx].trim(), Some((pct / 100.0).clamp(0.0, 1.0)))+ } else {+ (t, None)+ }+ } else {+ (t, None)+ };+ if let Some(c) = parse_color(color_str) {+ stops.push((c, pos));+ }+ }+ if stops.len() < 2 {+ // A single-color "gradient" is just that color; let the caller fall back+ // to background_color instead (return None so parse_color runs).+ return None;+ }+ Some((angle, stops))+}++/// Parse `aspect-ratio` to a width/height ratio. Accepts `16 / 9`, `1.5`, and+/// the `auto <ratio>` form (the `auto` keyword alone yields `None`, meaning the+/// intrinsic ratio, which for images is filled in at layout).+fn parse_aspect_ratio(value: &str) -> Option<f32> {+ let v = value.trim();+ if v.eq_ignore_ascii_case("auto") {+ return None;+ }+ // Drop a leading/trailing `auto` keyword from the `auto <ratio>` form.+ let ratio_part: String = v+ .split_whitespace()+ .filter(|t| !t.eq_ignore_ascii_case("auto"))+ .collect::<Vec<_>>()+ .join(" ");+ if let Some((w, h)) = ratio_part.split_once('/') {+ let w: f32 = w.trim().parse().ok()?;+ let h: f32 = h.trim().parse().ok()?;+ if h > 0.0 && w > 0.0 {+ return Some(w / h);+ }+ return None;+ }+ let r: f32 = ratio_part.trim().parse().ok()?;+ (r.is_finite() && r > 0.0).then_some(r)+}+/// Extract the first `url(...)` reference from a `background`/`background-image`/// value, unquoted. Ignores any other layers in the same shorthand (gradients,/// `no-repeat`, etc.): we paint the referenced image, not the gradient.@@ -772,6 +1577,76 @@ fn parse_url(value: &str) -> Option<String> {}}+/// `flex: none|auto|<grow>|<grow> <shrink>|<grow> <shrink> <basis>`. This is+/// the shorthand form almost all real-world flexbox CSS actually uses (far+/// more often than the flex-grow/flex-shrink longhands); leaving it+/// unhandled silently drops grow/shrink from every rule written this way.+/// flex-basis is not modeled as a distinct field from width, so a basis+/// length in the shorthand is parsed (to keep the number-only forms working)+/// but otherwise not separately applied; auto is a reasonable approximation+/// for the common case where basis is 0 or unspecified.+fn parse_flex_shorthand(style: &mut LayoutStyle, value: &str) {+ match value.trim() {+ "none" => {+ style.flex_grow = Some(0.0);+ style.flex_shrink = Some(0.0);+ style.flex_basis = crate::Dimension::Auto;+ return;+ }+ "auto" => {+ style.flex_grow = Some(1.0);+ style.flex_shrink = Some(1.0);+ style.flex_basis = crate::Dimension::Auto;+ return;+ }+ "initial" => {+ style.flex_grow = Some(0.0);+ style.flex_shrink = Some(1.0);+ style.flex_basis = crate::Dimension::Auto;+ return;+ }+ _ => {}+ }+ // Grammar: `flex: <grow> <shrink>? || <basis>`. Bare numbers are grow then+ // shrink; a token with a unit / `auto` / a third numeric is the basis+ // (e.g. `flex: 0 0 260px`, the fixed-width sidebar idiom).+ let mut numbers: Vec<f32> = Vec::new();+ let mut basis: Option<crate::Dimension> = None;+ for tok in value.split_whitespace() {+ if let Ok(n) = tok.parse::<f32>() {+ if numbers.len() < 2 {+ numbers.push(n);+ } else {+ basis = Some(dimension_value(tok));+ }+ } else {+ basis = Some(dimension_value(tok));+ }+ }+ match numbers.as_slice() {+ [grow] => {+ style.flex_grow = Some(*grow);+ style.flex_shrink = Some(1.0);+ }+ [grow, shrink, ..] => {+ style.flex_grow = Some(*grow);+ style.flex_shrink = Some(*shrink);+ }+ [] => {}+ }+ // Explicit basis wins; otherwise numbers-only shorthand implies basis 0+ // (per spec `flex: 1` == `1 1 0%`), while a bare basis keeps grow/shrink 1.+ style.flex_basis = match basis {+ Some(b) => b,+ None if !numbers.is_empty() => crate::Dimension::Px(0.0),+ None => {+ style.flex_grow = Some(1.0);+ style.flex_shrink = Some(1.0);+ crate::Dimension::Auto+ }+ };+}+/// `background-size: 10px` / `0.857em` / `10px 20px` -> explicit px pair./// Keyword values (`cover`, `contain`, `auto`) are left unhandled (`None`, the/// "stretch to fill the box" fallback) since evaluating them needs the@@ -909,4 +1784,33 @@ mod tests {let s = compute_style("div", Some("width: calc(var(--x, 10px) + 5px)"));assert_eq!(s.width, crate::Dimension::Px(15.0));}++ #[test]+ fn flex_shorthand_two_numbers() {+ // The exact form Wikipedia's infobox uses for its label/value cells+ // (`.infobox tbody > tr > th/td{flex:1 0}`): without shorthand+ // support this was silently dropped, leaving both columns+ // shrink-to-fit instead of sharing the row's width.+ let s = compute_style("div", Some("flex: 1 0"));+ assert_eq!(s.flex_grow, Some(1.0));+ assert_eq!(s.flex_shrink, Some(0.0));+ }++ #[test]+ fn flex_shorthand_keywords() {+ let none = compute_style("div", Some("flex: none"));+ assert_eq!(none.flex_grow, Some(0.0));+ assert_eq!(none.flex_shrink, Some(0.0));++ let auto = compute_style("div", Some("flex: auto"));+ assert_eq!(auto.flex_grow, Some(1.0));+ assert_eq!(auto.flex_shrink, Some(1.0));+ }++ #[test]+ fn flex_shorthand_single_number_defaults_shrink_to_one() {+ let s = compute_style("div", Some("flex: 2"));+ assert_eq!(s.flex_grow, Some(2.0));+ assert_eq!(s.flex_shrink, Some(1.0));+ }}diff --git a/crates/obscura-render/tests/layout_test.rs b/crates/obscura-render/tests/layout_test.rsindex 4fb58f28..6049ef06 100644--- a/crates/obscura-render/tests/layout_test.rs+++ b/crates/obscura-render/tests/layout_test.rs@@ -3,7 +3,6 @@//! no per-site hardcoded selectors. This guards against reintroducing the//! site-specific hacks that used to live in obscura-render for this exact markup.-use obscura_dom::tree::NodeData;use obscura_dom::tree_sink::parse_html;use obscura_render::layout_dom;@@ -34,28 +33,28 @@ const HN_HTML: &str = r##"</table>"##;-/// The top-left corner of a text node's overall bounding box: a text node-/// lays out as one taffy leaf per word (see `dom::build_text_words`), so its-/// geometry lives in `text_runs` as several (box, word) pairs rather than a-/// single rect. `needle` is matched against the node's whole original-/// content, not a single word.+/// Top-left of the tightest laid-out element box whose text contains+/// `needle`. Text geometry is no longer a per-word list: a pure-text+/// container collapses to a single cosmic-text inline formatting context+/// (see `inline`), and even in the word-split path the wrapping `<a>`/`<span>`+/// are flattened into their block, so the smallest element rect enclosing the+/// text is the meaningful, mode-independent anchor. Picking the smallest-area+/// match skips the giant ancestor tables that also "contain" the text.fn find_by_text(tree: &obscura_dom::tree::DomTree,layout: &obscura_render::DomLayout,needle: &str,) -> Option<(f32, f32)> {- for (id, runs) in &layout.text_runs {- if let Some(node) = tree.get_node(*id) {- if let NodeData::Text { contents } = &node.data {- if contents.trim() == needle {- let x = runs.iter().map(|(r, _)| r.x).fold(f32::INFINITY, f32::min);- let y = runs.iter().map(|(r, _)| r.y).fold(f32::INFINITY, f32::min);- return Some((x, y));- }+ let mut best: Option<(f32, obscura_render::Rect)> = None;+ for (id, rect) in &layout.rects {+ if tree.text_content(*id).contains(needle) {+ let area = rect.width * rect.height;+ if best.as_ref().map(|(a, _)| area < *a).unwrap_or(true) {+ best = Some((area, *rect));}}}- None+ best.map(|(_, r)| (r.x, r.y))}#[test]@@ -90,29 +89,43 @@ fn hn_shaped_table_lays_out_without_site_hardcoding() {);}+#[test]+fn relative_units_resolve_against_viewport_and_font_size() {+ // 50vw of a 1000px viewport = 500px; 10em at the default 16px = 160px.+ // Both were previously mis-resolved (vw kept as raw px, em hardcoded to 16+ // regardless of context), so this guards the deferred-resolution pass.+ let html = r##"<div style="width:50vw;height:10em"></div>"##;+ let tree = parse_html(html);+ let layout = layout_dom(&tree, (1000.0, 800.0));+ let hit = layout.rects.values().any(|r| (r.width - 500.0).abs() < 1.0 && (r.height - 160.0).abs() < 1.0);+ assert!(hit, "expected a 500x160 box from 50vw/10em, rects: {:?}", layout.rects.values().map(|r| (r.width, r.height)).collect::<Vec<_>>());+}+#[test]fn long_text_run_wraps_across_multiple_lines() {- // A single text node with no inline elements breaking it up must still- // wrap word by word within a narrow container: this is the regression- // case for treating a whole text node as one indivisible layout box,- // which cannot wrap internally and instead overflows straight past the- // container's edge.+ // A long single text node with no inline elements breaking it up must+ // wrap within a narrow container instead of overflowing on one line. The+ // container's height is the mode-independent proof: several wrapped lines+ // make it much taller than one line, whether text is shaped by cosmic-text+ // (paint) or split into word boxes (layout-only).let html = r##"<div style="width:100px">This sentence has plenty of words to wrap across several lines</div>"##;let tree = parse_html(html);let layout = layout_dom(&tree, (1000.0, 1000.0));- let text_id = tree- .descendants(tree.document())- .into_iter()- .find(|id| matches!(tree.get_node(*id).map(|n| n.data.clone()), Some(NodeData::Text { .. })))- .expect("text node exists");- let runs = layout.text_runs.get(&text_id).expect("text node has word runs");- assert!(runs.len() > 5, "expected the sentence to split into several word leaves, got {}", runs.len());-- let distinct_y: std::collections::BTreeSet<i32> = runs.iter().map(|(r, _)| r.y.round() as i32).collect();+ // Tightest element enclosing the text: the 100px div itself.+ let mut div_rect: Option<obscura_render::Rect> = None;+ for (id, rect) in &layout.rects {+ if tree.text_content(*id).contains("several lines") {+ if div_rect.as_ref().map(|d| rect.width * rect.height < d.width * d.height).unwrap_or(true) {+ div_rect = Some(*rect);+ }+ }+ }+ let div_rect = div_rect.expect("text container laid out");+ assert!(div_rect.width <= 101.0, "container should hold its 100px width, got {}", div_rect.width);assert!(- distinct_y.len() > 1,- "words should wrap onto more than one line within a 100px-wide container, got y positions {:?}",- distinct_y+ div_rect.height > 60.0,+ "text should wrap onto several lines in a 100px-wide box (tall container), got height {}",+ div_rect.height);}