From d017e838c81d4935bbb1e3d1842940dc4b9f08ef Mon Sep 17 00:00:00 2001 From: ide-agent Date: Sun, 15 Nov 2026 08:28:28 -0800 Subject: [PATCH] Runtime custom properties: typed lengths resolved where declared MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Why === LLP 1123 D5 (expo/exact-llp#82, amended by expo/exact-llp#87) has an author declare a custom property on a node, `--gap="8px"`, and read it in a length below, `padding="var(--gap)"`, with CSS Variables 1's unregistered semantics: `var()` in a declaration is substituted at the declaring node and its subtree inherits the result. A capture, `--hero-top="var(--exact-safe-area-inset-top)"`, hands a box's own inset to its subtree, which is how a box inside a nested content owner reads an outer owner's inset (D5, D9). Only a length reads one, so the kernel holds each value as a calculation tree and resolves a reader by substituting trees, with no text parsed while it lays out. How === The kernel holds a node's declarations as one rare row, `safe_area_properties` (bit 255), whose CSS is `--a: ; --b: `: each value a length a calculation tree holds (`SafeAreaProperties::value`), with `em`, text styles, platform lengths and an `env()` with a fallback refused. A calculation tree has a `var()` leaf with its name and an optional fallback, which is one value wherever the call stands; the wire carries it as tag 10. `Env::properties` holds what one node's lengths read, made by `owner::properties_at`. Its resolver first walks every declaration a reader reaches, fallback references included, and marks each dependency cycle invalid (Tarjan); it then substitutes the rest where each is declared, a capture taking the declaring node's local inset. A value that reads an undefined `env()`, or exceeds the tree limits of 32 values and 32 levels once expanded (CSS Values 4 §10.8), is invalid; so is every value of a node whose reads reach more than 1,024 declarations. A reader's fallback applies to each. A change rederives only what it reaches: a declaration change, the readers in the subtree of names whose values changed, below the nodes that declare them again and through the declarations that read them; an inset change, the readers that read an inset or whose properties reach one, in the owner's subtree; a move, the moved subtree's readers when any node declares a property (`NodeArena::declaring_slots`). Each goes through `txn::style_changed` with the rows that read, so a paragraph holding an inline image is measured again, and a reader whose engine style comes out the same lays nothing out. A root font size change rederives property readers, which a `rem` value reaches. Lowering admits `--name` attributes (the lexer takes every CSS name character), merges a node's, its classes' included, into one row of `--name: value; ` fragments, empty where a class choice, a binding or an option leaves a value `none`, and checks each literal value as one length. Before that, a design token that is a length with one value in every mode is written as its value, read as a length row reads one: through `var()`, which the loader leaves as written in a declaration, or by its name where the text is literal whole, a template whose holes are literal once a component is expanded included. In a template with a hole computed at run time only a `var()` is a token, since the hole's text is unknown; a call in a comment, or of a host's `--exact-` name, is no token. A `var()` in a length row names a design token, a property some node declares, or, with a fallback, a name nothing declares (`lower-var-undeclared`, naming a close match). A fallback is checked as a value of its own: a `var()` in it of a token that has one value in every mode is written as that value, and one of a token that varies by mode, or of another kind than a length, is refused. Exact reserves dotted names for tokens. A property a design token names is refused, and so is a property in an inset override. The wasm host writes each declaration and the readers' `var()`s for the browser to substitute, names escaped. The JS target writes a bound row one declaration at a time (`declarations.js`), past comments, strings and functions, and removes the ones a node no longer declares. The Apple host sends no row, since the kernel resolves its readers; its calculation bridge carries the root font size, which a `rem` value needs. The runner's agent rows show the declarations. D5's limits hold: a substituted value clamps to its row's range in the kernel, where a browser makes a lone `var()` of such a literal invalid; a row that takes no percentage refuses one in a fallback too; a bound value's top-level `;` declares what follows it. Runtime custom properties are live once this lands: they add syntax main refused and change nothing an app writes today. Test Plan ========= `bun scripts/gate.mjs` passes. `bun scripts/known.mjs -- cargo test --tests --no-fail-fast`, `cargo clippy --all-targets --keep-going -- -D warnings`, `cargo check --workspace --all-targets --keep-going`, `bun scripts/caps.mjs`, `bun scripts/boot.mjs` and `bun scripts/wasm-check.mjs` pass on this commit. `cargo clippy --workspace --all-targets` fails only on two lints in `host/painted` (`src/paint/native.rs`, `src/text/shaping.rs`), which this branch does not touch and main has too. The behavior is covered by `kernel/src/kernel/property_tests.rs` (declaration changes, removal and shadowing, cycles through used and unused fallbacks, the expansion and walk bounds in both row orders, undefined `env()` in both directions, `VAR(` in any case, moves with no local insets, percentages against each reader's basis, `rem` and the root font size, an inline image measured again), `kernel/src/style/safe_area_properties_tests.rs`, `contract/cli/tests/it/custom_properties.rs` (class choices and an option switched in one runner, tokens in declarations and fallbacks, every refusal), `host/web/src/element_tests.rs`, `host/web-js/custom-properties.test.mjs`, and `host/web/tests/local-insets.test.mjs`, where Chromium computes what the kernel does: a fallback 22px, a capture 47 where a nearer override is 30, a percentage the reader's own, and `declarations.js` writing a row with a comment and an escaped name. Each of these fails its test when the code behind it is removed: moves with no local insets, the paragraph measured again, the root font size, a defined property whatever its fallback reads, class and option fragments, nested fallback checks, the loader leaving a token's `var()` as written, literal templates folded, and comments, host names and escapes in token scanning. `bun host/apple/build.mjs --test --only BoxLayerMacTests` and the iOS class `BoxLayerIOSTests` on the iPhone Duo (iOS 27.1) pass with the bridge's new field. `bun scripts/known.mjs -- bun test --isolate` over `host/web-js/{custom-properties,dom,tree,lower,modes,cleared-styles,build,lower-equal}.test.mjs` and `host/web/tests/local-insets.test.mjs`, with a Caltrain wasm build as `EXACT_WEB_DIST`, passes except the Firefox case of `cleared-styles.test.mjs`: Firefox does not launch on this Mac ("Could not find profile folder", also from `suiteBrowser('firefox')` alone). `cargo test --release -p exact-kernel --test it property_cost -- --ignored --nocapture --test-threads=1`, 2,000 readers each eight boxes below the declaring root, on an M5 Pro Mac mini: build and first layout 24.4 ms with literal `8px`, 27.9 ms with `var(--pad)`, 27.6 ms with a capture, 25.5 ms with a plain local-inset reader; a steady relayout 0.25 µs in each; a change every reader sees 6.6 to 7.1 ms with its layout, of which 1.5 ms is the commit (2,001 nodes) and 5.6 ms the layout (18,000 frames). Changes no reader's value depends on lay out no frame: an unread declaration 0.38 ms of commit, an inset under readers of a literal property 0.45 ms, a change below nearer declarations 0.04 ms. A declaration chain doubling at each level costs 50 to 59 ms for 2,000 readers at 8 to 16 levels, the author limits ending it at the fifth. Review records: expo/exact-llp's `reviews/code-2026-11-15-1123-stage-2a-r*`. --- contract/cli/src/lib.rs | 14 +- contract/cli/src/sources.rs | 17 +- contract/cli/tests/it/custom_properties.rs | 268 +++++++++++ contract/cli/tests/it/forma_var.rs | 3 + contract/cli/tests/it/main.rs | 1 + contract/lower/src/custom_props.rs | 179 ++++++++ contract/lower/src/length_tokens.rs | 304 +++++++++++++ contract/lower/src/lib.rs | 4 +- contract/lower/src/nodes.rs | 28 ++ contract/lower/src/tags.rs | 4 + contract/lower/src/values.rs | 63 +-- contract/lower/src/var_tokens.rs | 409 ++++++++++++++--- contract/syntax/src/lexer.rs | 62 +-- host/apple/include/exact.h | 2 +- host/apple/src/calc.rs | 75 ++- host/apple/src/style.rs | 2 + .../ExactKitTests/BoxLayerIOSTests.swift | 6 +- .../ExactKitTests/BoxLayerMacTests.swift | 2 +- host/web-js/build.mjs | 2 +- host/web-js/custom-properties.test.mjs | 19 + host/web-js/declarations.js | 48 ++ host/web-js/src/style.rs | 3 + host/web-js/tree.js | 2 + host/web/src/css.rs | 12 + host/web/src/css/clears.rs | 11 +- host/web/src/element_tests.rs | 40 ++ host/web/tests/local-insets.test.mjs | 41 +- kernel/build.rs | 2 +- kernel/build/codec.rs | 6 + kernel/src/arena.rs | 50 +- kernel/src/arena/styles.rs | 55 +++ kernel/src/error.rs | 6 + kernel/src/kernel/owner.rs | 429 ++++++++++++++++-- kernel/src/kernel/owner_tests.rs | 12 +- kernel/src/kernel/property_tests.rs | 381 ++++++++++++++++ kernel/src/style.rs | 3 + kernel/src/style/calc/mod.rs | 250 ++++++++-- kernel/src/style/calc/parse.rs | 60 ++- kernel/src/style/calc/simplify.rs | 10 +- kernel/src/style/calc/text.rs | 27 +- kernel/src/style/calc/wire.rs | 17 +- kernel/src/style/env.rs | 57 ++- kernel/src/style/finite.rs | 1 + kernel/src/style/safe_area_properties.rs | 143 ++++++ .../src/style/safe_area_properties_tests.rs | 53 +++ kernel/src/txn.rs | 14 +- kernel/src/wire/codec.rs | 2 +- kernel/tables/schema.json | 8 + kernel/tests/it/compare.rs | 2 +- kernel/tests/it/main.rs | 1 + kernel/tests/it/property_cost.rs | 269 +++++++++++ kernel/tests/it/style_dynamic.rs | 1 + runner/src/agent/row.rs | 1 + 53 files changed, 3145 insertions(+), 336 deletions(-) create mode 100644 contract/cli/tests/it/custom_properties.rs create mode 100644 contract/lower/src/custom_props.rs create mode 100644 contract/lower/src/length_tokens.rs create mode 100644 host/web-js/custom-properties.test.mjs create mode 100644 host/web-js/declarations.js create mode 100644 kernel/src/arena/styles.rs create mode 100644 kernel/src/kernel/property_tests.rs create mode 100644 kernel/src/style/safe_area_properties.rs create mode 100644 kernel/src/style/safe_area_properties_tests.rs create mode 100644 kernel/tests/it/property_cost.rs diff --git a/contract/cli/src/lib.rs b/contract/cli/src/lib.rs index b71a87c7e..8ecebbf62 100644 --- a/contract/cli/src/lib.rs +++ b/contract/cli/src/lib.rs @@ -296,13 +296,19 @@ pub(crate) fn params(file: &mut contract_syntax::File) -> Result<(), CompileErro /// writes them for a file, from the one design a text has, its inline /// `theme`: the first row refused, or the warning for a fallback dropped. fn vars(file: &mut contract_syntax::File) -> Result, CompileError> { - let tokens = contract_lower::var_tokens::Tokens::of(None, &[], file.theme.as_ref()); + let tokens = contract_lower::var_tokens::Tokens::of(None, &[], file.theme.as_ref()) + .with_runtime([&*file]); let found = contract_lower::var_tokens::rewrite(file, &tokens); if let Some(e) = found.refused.into_iter().next() { return Err(e.into()); } - let warning = contract_lower::var_tokens::fallback_warning(&found.fallbacks); - Ok(warning.map(CompileError::warning).into_iter().collect()) + let fallback = contract_lower::var_tokens::fallback_warning(&found.fallbacks); + let undeclared = contract_lower::var_tokens::undeclared_warning(&found.undeclared); + Ok(fallback + .into_iter() + .chain(undeclared) + .map(CompileError::warning) + .collect()) } /// Compile one source text to a validated plan. A text has no path, so a /// `use … from "./file.contract"` in it cannot be resolved: compile a file @@ -964,6 +970,8 @@ fn compile_loaded( own.extend(shortcut_warnings(&file, &app_root)); let fallbacks = contract_lower::var_tokens::fallback_warning(&sources.var_fallbacks); own.extend(fallbacks.map(CompileError::warning)); + let undeclared = contract_lower::var_tokens::undeclared_warning(&sources.var_undeclared); + own.extend(undeclared.map(CompileError::warning)); } let compiled = compile_file_warned( &file, diff --git a/contract/cli/src/sources.rs b/contract/cli/src/sources.rs index c320c135a..7a95aa917 100644 --- a/contract/cli/src/sources.rs +++ b/contract/cli/src/sources.rs @@ -62,6 +62,8 @@ pub(crate) struct Sources { /// Each `var()` whose fallback the loader dropped (LLP 1153 D6): one /// warning says them. pub(crate) var_fallbacks: Vec<(Span, String)>, + /// Each `var()` of a runtime custom property nothing declares (LLP 1123 D5). + pub(crate) var_undeclared: Vec<(Span, contract_lower::var_tokens::Undeclared)>, } /// One name a `use` brought: where it is written, and the declaration it @@ -275,11 +277,14 @@ impl Loader<'_> { ¶ms, &identities, ); - self.vars = Some(contract_lower::var_tokens::Tokens::of( - design.as_ref().map(|d| d.text.as_str()), - &package_designs, - self.units.first().and_then(|u| u.file.theme.as_ref()), - )); + self.vars = Some( + contract_lower::var_tokens::Tokens::of( + design.as_ref().map(|d| d.text.as_str()), + &package_designs, + self.units.first().and_then(|u| u.file.theme.as_ref()), + ) + .with_runtime(self.units.iter().map(|u| &u.file)), + ); let library = library::read(&self.sources, self.app_root); match self.scope() { Ok((mut file, scopes)) => { @@ -681,6 +686,7 @@ impl<'a> Loader<'a> { consulted: Vec::new(), motion: Vec::new(), var_fallbacks: Vec::new(), + var_undeclared: Vec::new(), }, active: vec![root_key.to_path_buf()], units: Vec::new(), @@ -875,6 +881,7 @@ impl Loader<'_> { let refused = found.refused.into_iter(); (self.refused.errors).extend(refused.map(|e| sources.resolve(e.into()))); self.sources.var_fallbacks.extend(found.fallbacks); + self.sources.var_undeclared.extend(found.undeclared); } /// Give every declaration its program-unique name (D4), rewrite each diff --git a/contract/cli/tests/it/custom_properties.rs b/contract/cli/tests/it/custom_properties.rs new file mode 100644 index 000000000..f24a6914a --- /dev/null +++ b/contract/cli/tests/it/custom_properties.rs @@ -0,0 +1,268 @@ +//! LLP 1123 D5 as an app writes it: `--name` declared on a node, its own or +//! a class's, read by a length below it through `var()`; and what the +//! compiler refuses or warns of. + +use crate::scratch::Scratch; +use exact_kernel::{Kernel, Offer}; +use exact_plan::Plan; +use exact_runner::Runner; + +const APP: &str = r#"style Spaced + --gap="8px" + +component App + view + column class=Spaced --pad="calc(var(--gap) * 2)" height=844 testId="root" + column padding-top="var(--pad)" testId="padded" + column height=10 testId="probe" + column --gap="20px" testId="inner" + column height="var(--gap)" testId="gap" + column height="var(--pad)" testId="pad" + column height="var(--none, 5px)" testId="fallback" + column height=`calc(var(--gap) + ${2 + 1}px)` testId="computed" +"#; + +fn boot(source: &str) -> Runner<()> { + let plan = contract::compile(source).unwrap_or_else(|e| panic!("{e}")); + boot_plan(&plan) +} + +fn boot_plan(plan: &Plan) -> Runner<()> { + let plan = Plan::decode(&plan.encode()).unwrap(); + let mut runner = + Runner::boot(plan, (), Kernel::with_monospace(), Default::default(), "/").unwrap(); + runner + .kernel_mut() + .compute_layout(1, Offer::definite(390.0, 844.0)) + .unwrap(); + runner +} + +fn frame(runner: &Runner<()>, test_id: &str) -> exact_kernel::Frame { + let kernel = runner.kernel(); + kernel + .node_by_key(kernel.find_by_test_id(test_id)[0]) + .unwrap() + .frame +} + +#[test] +fn a_length_reads_the_property_its_ancestors_declare() { + let runner = boot(APP); + assert_eq!( + frame(&runner, "probe").y, + 16.0, + "the class's --gap, doubled where --pad is declared" + ); + assert_eq!(frame(&runner, "gap").height, 20.0, "the nearer declaration"); + assert_eq!( + frame(&runner, "pad").height, + 16.0, + "substituted where it was declared" + ); + assert_eq!( + frame(&runner, "computed").height, + 23.0, + "a template's value" + ); +} + +#[test] +fn a_fallback_of_an_undeclared_name_is_admitted_and_warned() { + let (plan, warnings) = contract::compile_warned(APP); + assert!( + warnings + .iter() + .any(|w| w.to_string().contains("lower-var-undeclared") + && w.to_string().contains("--none")), + "{warnings:?}" + ); + assert_eq!(frame(&boot_plan(&plan.unwrap()), "fallback").height, 5.0); + // A misspelling is named + let misspelt = APP.replace("var(--none, 5px)", "var(--gpa, 5px)"); + let (_, warnings) = contract::compile_warned(&misspelt); + assert!( + warnings + .iter() + .any(|w| w.to_string().contains("did you mean `--gap`?")), + "{warnings:?}" + ); +} + +#[test] +fn the_compiler_refuses_what_cannot_resolve() { + let refused = |source: &str, says: &str| { + let e = contract::compile(source) + .err() + .unwrap_or_else(|| panic!("{source} compiled")); + assert!(e.to_string().contains(says), "{source}: {e}"); + }; + let view = |attrs: &str| format!("component App\n view\n column --gap=\"8px\" {attrs}\n"); + // A name nothing declares, without a fallback, can never resolve + refused( + &view(r#"height="var(--nope)""#), + "no node of the app declares it", + ); + refused(&view(r#"height="var(--gpa)""#), "did you mean `--gap`?"); + // Nor inside a fallback, which is a value of its own + refused(&view(r#"height="var(--gap, var(--typo))""#), "`--typo`"); + // One attribute declares one property + refused(&view(r#"--a="1px; --b: 8px""#), "is one length"); + // An owner's inset override is resolved before any custom property + refused( + &view(r#"--exact-safe-area-inset-top="var(--gap)""#), + "reads none", + ); + // A colour names a token, not a runtime property + refused(&view(r#"background-color="var(--gap)""#), "a length"); + // A declaration is a length, since only a length reads one + refused( + "component App\n view\n column --bad=\"red\"\n", + "is one length", + ); +} + +#[test] +fn a_design_token_and_a_custom_property_never_share_a_name() { + let dir = Scratch::new(format!("exact2-custom-token-{}", std::process::id())); + let design = "forma t\n\ntheme\n gap = 4px\n space.row = 12px\n"; + std::fs::write(dir.join("app.forma"), design).unwrap(); + let view = "component App\n view\n column --gap=\"8px\" --pad=\"2px\" padding=\"var(--space.rows, 4px)\"\n column height=\"var(--pad)\"\n"; + std::fs::write(dir.join("app.contract"), view).unwrap(); + let Err(all) = contract::compile_path_all(&dir.at("app.contract"), false) else { + panic!("compiled"); + }; + let says = |what: &str| all.iter().any(|e| e.message.contains(what)); + // `var(--gap)` reads the token, so no node declares `--gap` + assert!(says("`gap` is a token of this app's design"), "{all:#?}"); + // A name with a `.` is no property name, so a misspelt token keeps its refusal + assert!(says("`--space.rows` is no token"), "{all:#?}"); + assert_eq!( + all.len(), + 2, + "the property no token names compiles: {all:#?}" + ); +} + +#[test] +fn a_class_choice_or_an_absent_option_drops_one_declaration_and_keeps_the_rest() { + // `on` chooses a class that declares --gap or one that does not; `pad` is + // an option a button clears + let app = "style Spaced\n --gap=\"8px\"\n\nstyle Plain\n color=\"#000000\"\n\ncomponent App\n state on = true\n state pad = some(\"6px\")\n action flip\n on = !on\n action clear\n pad = none\n view\n column class=(on ? Spaced : Plain) --keep-2=\"2px\" --pad=pad height=844\n button \"Flip\" press=flip testId=\"flip\"\n button \"Clear\" press=clear testId=\"clear\"\n column height=\"var(--gap, 5px)\" testId=\"gap\"\n column height=\"var(--keep-2)\" testId=\"keep\"\n column height=\"var(--pad, 3px)\" testId=\"pad\"\n"; + let mut runner = boot(app); + let press = |runner: &mut Runner<()>, test_id: &str| { + let kernel = runner.kernel(); + let view = kernel + .node_by_key(kernel.find_by_test_id(test_id)[0]) + .unwrap() + .id; + runner.dispatch(view, exact_runner::Event::Press).unwrap(); + assert!(!runner.is_poisoned(), "{test_id}"); + runner + .kernel_mut() + .compute_layout(1, Offer::definite(390.0, 844.0)) + .unwrap(); + }; + let heights = |runner: &Runner<()>| ["gap", "keep", "pad"].map(|t| frame(runner, t).height); + assert_eq!(heights(&runner), [8.0, 2.0, 6.0]); + press(&mut runner, "flip"); + assert_eq!(heights(&runner), [5.0, 2.0, 6.0]); + press(&mut runner, "flip"); + assert_eq!(heights(&runner), [8.0, 2.0, 6.0]); + press(&mut runner, "clear"); + assert_eq!(heights(&runner), [8.0, 2.0, 3.0]); +} + +#[test] +fn a_declaration_holds_a_design_tokens_length() { + let dir = Scratch::new(format!("exact2-custom-design-{}", std::process::id())); + // `min` and `safe-area-inset-top` name tokens too: a function's name and an + // `env()` variable are never one + let design = "forma t\n\naxes\n density = regular | compact\n\ntheme\n space.md = 4px\n under = 4px\n px = 4px\n e2px = 4px\n ink = #111111\n exact-safe-area-inset-top = 9px\n min = 9px\n safe-area-inset-top = 5px\n space.row = 12px\n when density=compact: 8px\n"; + std::fs::write(dir.join("app.forma"), design).unwrap(); + let app = |rows: &str| { + std::fs::write(dir.join("app.contract"), format!("component App\n state extra = 1\n state prefix = \"\"\n view\n column --pad=\"calc(var(--space.md) * 2)\" --least=\"min(10px, 20px)\" --top=\"env(/**/safe-area-inset-top)\" --gap-2=\"2px\" --_under=\"8px\" --copy=\"var(--_under, 1px)\" --held=`calc(var(--space.md) + ${{extra}}px)` --unit=`${{extra}}px` --after-text=`${{prefix}}var(--space.md)` --unit-token=`${{prefix}}var(--px)` --scaled=`calc(${{extra}}e2px)` --remark=\"calc(4px /* var(--ink) */)\" --escaped=\"var(--space.md, '\\\\é')\" --hole-unit=`1${{\"px\"}}` height=844\n{rows}")).unwrap(); + contract::compile_path(&dir.join("app.contract")) + }; + let plan = app(" column height=\"var(--pad)\" testId=\"pad\"\n column height=\"VAR(--missing, var(--space.md))\" testId=\"fallback\"\n column padding=\"var(--missing, var(--space.md)) 0px\" testId=\"sides\"\n column height=\"var(--least)\" testId=\"least\"\n column height=\"var(--top, 1px)\" testId=\"top\"\n column padding=\"var(--gap-2) var(--missing, var(--space.md))\" testId=\"later\"\n column height=1 testId=\"later-child\"\n column height=\"var(--copy)\" testId=\"copy\"\n column height=\"var(--held)\" testId=\"held\"\n column height=\"var(--unit)\" testId=\"unit\"\n column height=\"var(--after-text, 7px)\" testId=\"after-text\"\n column height=\"var(--unit-token, 7px)\" testId=\"unit-token\"\n column height=\"var(--scaled)\" testId=\"scaled\"\n column height=\"var(--remark)\" testId=\"remark\"\n column height=\"var(--escaped)\" testId=\"escaped\"\n column height=\"var(--exact-safe-area-inset-top)\" testId=\"host\"\n column height=\"var(--hole-unit)\" testId=\"hole-unit\"\n column height=`calc(var(--missing, var(--space.md)) + ${2 + 1}px)` testId=\"template-fallback\"\n") + .unwrap_or_else(|e| panic!("{e}")); + let runner = boot_plan(&plan); + let heights = [ + "pad", + "fallback", + "sides", + "least", + "top", + "later", + "copy", + "held", + "template-fallback", + "unit", + "after-text", + "unit-token", + "scaled", + "remark", + "escaped", + "host", + "hole-unit", + ] + .map(|t| frame(&runner, t).height); + // A call with no fallback leaves the next one's for the scan; `--_under` + // is a name, not a token; in a template with a hole a token is one only + // through `var()`, so a unit after the hole stays a unit + assert_eq!( + heights, + [8.0, 4.0, 8.0, 10.0, 0.0, 5.0, 8.0, 5.0, 7.0, 1.0, 4.0, 4.0, 100.0, 4.0, 4.0, 0.0, 1.0] + ); + let (later, child) = (frame(&runner, "later"), frame(&runner, "later-child")); + assert_eq!( + child.x - later.x, + 4.0, + "the left padding is the fallback's token" + ); + // A comment names no token + app(" column height=\"var(--missing, /* space.row */ 4px)\" width=\"var(--missing, 4px /* space.row */)\"\n") + .unwrap_or_else(|e| panic!("{e}")); + // A component's argument that is one token's `var()` reaches a declaration as the token + std::fs::write(dir.join("app.contract"), "component App\n view\n column height=844\n Card(pad=\"var(--space.md)\")\n\ncomponent Card\n props\n pad: string\n view\n column --gap=pad --whole=`${pad}` --twice=`calc(${pad} * 2)` --nested=`calc(${`${pad}`} * 2)`\n column height=\"var(--gap)\" testId=\"card\"\n column height=\"var(--whole, 7px)\" testId=\"card-whole\"\n column height=\"var(--twice)\" testId=\"card-twice\"\n column height=\"var(--nested)\" testId=\"card-nested\"\n").unwrap(); + let plan = contract::compile_path(&dir.join("app.contract")).unwrap_or_else(|e| panic!("{e}")); + // A template whose holes are literal once the component is expanded is that literal + let runner = boot_plan(&plan); + assert_eq!( + ["card", "card-whole", "card-twice", "card-nested"].map(|t| frame(&runner, t).height), + [4.0, 4.0, 8.0, 8.0] + ); + // A declaration reads a token through `var()`, a length with one value in every mode + for (rows, says) in [ + ( + " column --pad=\"var(--space.row)\"\n", + "differs between the app's modes", + ), + ( + " column --pad=\"var(--ink)\"\n", + "of another kind than a length", + ), + ] { + let e = app(rows).unwrap_err(); + assert!(e.to_string().contains(says), "{rows}: {e}"); + } + // A fallback is read at run time, where nothing binds a token that varies by mode + let e = app(" column height=\"var(--missing, var(--space.row))\"\n").unwrap_err(); + assert!( + e.to_string().contains("differs between the app's modes"), + "{e}" + ); +} + +#[test] +fn an_option_is_declared_where_it_is_present() { + // A `match` arm's binding shadows the option it unwraps; a component's computed argument read + // more than once is bound once, an option still + let app = "component App\n state pad = some(\"6px\")\n state pads: string[] = []\n view\n column --alt=(match pad { case some(pad) => pad, case none => \"2px\" }) height=844\n column height=\"var(--alt)\" testId=\"alt\"\n Card(pad=pads.at(0))\n\ncomponent Card\n props\n pad: option\n view\n column --g=(match pad { case some(v) => pad, case none => pad }) --k=\"2px\"\n column height=\"var(--g, 5px)\" testId=\"g\"\n column height=\"var(--k)\" testId=\"k\""; + let runner = boot(app); + assert!(!runner.is_poisoned()); + assert_eq!( + ["alt", "g", "k"].map(|t| frame(&runner, t).height), + [6.0, 5.0, 2.0] + ); +} diff --git a/contract/cli/tests/it/forma_var.rs b/contract/cli/tests/it/forma_var.rs index 5be897858..237d86869 100644 --- a/contract/cli/tests/it/forma_var.rs +++ b/contract/cli/tests/it/forma_var.rs @@ -264,6 +264,9 @@ fn a_length_token_in_grid_tracks_is_its_value() { "{tracks}" ); } + // A comment separates a number from the token after it, as white space does + let plan = grid("0/**/var(--card.min)").unwrap_or_else(|e| panic!("{e}")); + assert!(plan.windows(b"9.5rem".len()).any(|w| w == b"9.5rem")); let varies = grid("repeat(2, var(--space.row))").unwrap_err(); assert!( varies.contains("with one value in every app mode"), diff --git a/contract/cli/tests/it/main.rs b/contract/cli/tests/it/main.rs index cc65c4ab3..902e33a80 100644 --- a/contract/cli/tests/it/main.rs +++ b/contract/cli/tests/it/main.rs @@ -53,6 +53,7 @@ mod control_roles; mod controls; mod corpus; mod current; +mod custom_properties; mod dataset; mod declared_source; mod delete_rows; diff --git a/contract/lower/src/custom_props.rs b/contract/lower/src/custom_props.rs new file mode 100644 index 000000000..321158e2f --- /dev/null +++ b/contract/lower/src/custom_props.rs @@ -0,0 +1,179 @@ +//! @ref LLP 1123 D5 — a node's runtime custom properties are one style row: +//! each `--name` attribute, its classes' among them, a declaration in the +//! order they stand, so a later one of a name replaces an earlier one as +//! CSS's cascade does. + +use crate::LowerError; +use contract_syntax::{Attr, Expr, Span, TemplatePart}; +use contract_types::{Ref, Scope, Shapes, Ty}; +use exact_kernel::style::safe_area_properties::{is_author_name, SafeAreaProperties}; + +/// The one attribute that writes `attrs`' custom properties: each +/// declaration `--name: value; `, none where its value is `none`, so a class +/// choice or an absent option drops one declaration and keeps the rest. +/// Each literal value that is no one length is refused at its own attribute +/// and left out. +pub(crate) fn merged( + attrs: &[Attr], + scope: &Scope, + shapes: &Shapes, +) -> (Option, Vec) { + let mut errors = Vec::new(); + let mut parts: Vec = Vec::new(); + let mut first: Option<&Attr> = None; + for a in attrs.iter().filter(|a| is_author_name(&a.name)) { + let mut value = a.value.clone(); + let mut varying = None; + crate::values::call_tokens(&mut value, &mut varying); + if let Some(token) = varying { + errors.push(LowerError { + id: "lower-attr-value", + message: format!("`{}`: the design token `{token}` differs between the app's modes, and a custom property's value is read at run time, where nothing binds a mode; read the token where the length is", a.name), + span: a.span, + }); + continue; + } + if let Some((literal, span)) = refused(&value) { + errors.push(LowerError { + id: "lower-attr-value", + message: format!( + "`{}=\"{literal}\"`: a custom property's value is one length: px, rem, a percentage, a viewport unit, env() without a fallback, var(), or calc(), min(), max() or clamp() of these", + a.name + ), + span, + }); + continue; + } + first.get_or_insert(a); + match fragment(&a.name, value, scope, shapes) { + Expr::Str(t, _) => text(&mut parts, &t), + e => parts.push(TemplatePart::Expr(e)), + } + } + let Some(first) = first else { + return (None, errors); + }; + let value = match parts.as_slice() { + [] => Expr::Str(String::new(), first.span), + [TemplatePart::Text(t)] => Expr::Str(t.clone(), first.span), + _ => Expr::Template(parts, first.span), + }; + let attr = Attr { + name: first.name.clone(), + value, + span: first.span, + written: first.written, + }; + (Some(attr), errors) +} + +/// The first literal of `value`, in any arm of a choice, that is no one +/// length, and where. +fn refused(value: &Expr) -> Option<(String, Span)> { + match value { + Expr::Str(s, span) => SafeAreaProperties::value(s) + .is_none() + .then(|| (s.clone(), *span)), + Expr::Ternary(_, yes, no, _) + | Expr::Match { + some: yes, + none: no, + .. + } => refused(yes).or_else(|| refused(no)), + Expr::Let { body, .. } | Expr::Typed(body, ..) => refused(body), + _ => None, + } +} + +/// The declaration `name: value; ` as an expression, through a choice's +/// arms and a binding's body, each typed in the scope it is in, and nothing +/// where `value` is `none`. +fn fragment(name: &str, value: Expr, scope: &Scope, shapes: &Shapes) -> Expr { + let declared = |e: Expr| { + let span = e.span(); + Expr::Template( + vec![ + TemplatePart::Text(format!("{name}: ")), + TemplatePart::Expr(e), + TemplatePart::Text("; ".into()), + ], + span, + ) + }; + let within = |bound: &str, ty: Ty| { + let mut inner = scope.clone(); + inner.push(vec![(bound.to_string(), Ref::Local(0), ty)]); + inner + }; + match value { + Expr::Str(s, span) => Expr::Str(format!("{name}: {s}; "), span), + Expr::None(span) => Expr::Str(String::new(), span), + Expr::Ternary(cond, yes, no, span) => Expr::Ternary( + cond, + Box::new(fragment(name, *yes, scope, shapes)), + Box::new(fragment(name, *no, scope, shapes)), + span, + ), + Expr::Match { + subject, + var, + some, + none, + span, + } => { + let ty = match contract_types::infer(&subject, scope, shapes) { + Ok(Ty::Option(inner)) => *inner, + _ => Ty::Unknown, + }; + Expr::Match { + some: Box::new(fragment(name, *some, &within(&var, ty), shapes)), + none: Box::new(fragment(name, *none, scope, shapes)), + subject, + var, + span, + } + } + Expr::Let { + name: bound, + value, + body, + span, + } => { + let ty = contract_types::infer(&value, scope, shapes).unwrap_or(Ty::Unknown); + Expr::Let { + body: Box::new(fragment(name, *body, &within(&bound, ty), shapes)), + name: bound, + value, + span, + } + } + // A literal a component's argument carries is the literal + Expr::Typed(inner, ..) if matches!(*inner, Expr::None(_) | Expr::Str(..)) => { + fragment(name, *inner, scope, shapes) + } + // An option's value is declared where it is present + e if matches!(contract_types::infer(&e, scope, shapes), Ok(Ty::Option(_))) => { + let span = e.span(); + Expr::Match { + subject: Box::new(e), + var: VALUE.into(), + some: Box::new(declared(Expr::Ident(VALUE.into(), span))), + none: Box::new(Expr::Str(String::new(), span)), + span, + } + } + e => declared(e), + } +} + +/// The name an option's present value is bound to in its declaration: one +/// no author can write. +const VALUE: &str = "declared$"; + +/// Append `t` to the template's text, joining it to the text before. +fn text(parts: &mut Vec, t: &str) { + match parts.last_mut() { + Some(TemplatePart::Text(last)) => last.push_str(t), + _ => parts.push(TemplatePart::Text(t.to_string())), + } +} diff --git a/contract/lower/src/length_tokens.rs b/contract/lower/src/length_tokens.rs new file mode 100644 index 000000000..ae1d125ed --- /dev/null +++ b/contract/lower/src/length_tokens.rs @@ -0,0 +1,304 @@ +//! Length tokens written as their values where the theme cannot bind one: +//! in grid tracks, which the kernel's track parser reads; in a custom +//! property's declaration, which the kernel holds as a tree; and in a +//! `var()`'s fallback, which a row reads at run time (LLP 1123 D5). A token +//! that varies by mode stays a name in grid tracks, and is refused in the +//! other two, where nothing binds a mode. + +use crate::LowerError; +use contract_syntax::{Attr, Expr, TemplatePart}; +use exact_kernel::StyleId; +use std::borrow::Cow; + +/// A grid track list with each length token it names written as the token's +/// value (`minmax(card-min-width, 1fr)`, the loader having written +/// `var(--card-min-width)` as the name), as a browser substitutes `var()` before +/// it parses the tracks (CSS Variables 1 §3). Only a token with one value in +/// every app mode is written in; the kernel's track parser refuses any other. +pub(crate) fn grid_tokens(a: &Attr, rows: &[StyleId]) -> Option { + if !rows + .iter() + .any(|r| matches!(r, StyleId::GridTemplateColumns | StyleId::GridTemplateRows)) + { + return None; + } + let mut out = a.clone(); + texts(&mut out.value, &mut |text, whole| { + whole && written_tokens(text, None) + }) + .then_some(out) +} + +/// A custom property's declared value `e` with each design token in it +/// written as its value where the token is a length with one value in every +/// app mode, as a length row reads a token: through `var()`, which the +/// loader leaves as written here (LLP 1123 D5), or by its name, where the +/// text is literal whole; whether any was. A template whose holes are all +/// literal once a component is expanded is that literal. In a template with +/// a hole computed at run time only a `var()` is a token, since the hole's +/// text is unknown here. `varying` takes the first length token with more +/// than one value, which nothing binds where a value is read at run time. +pub(crate) fn call_tokens(e: &mut Expr, varying: &mut Option) -> bool { + fold_literal_templates(e); + texts(e, &mut |text, whole| { + let explicit = token_calls(text, varying); + explicit | whole && written_tokens(text, Some(varying)) + }) +} + +/// Each template in `e`, through choices, bindings and typed values, whose +/// holes are all literal strings, written as the one string it makes. +fn fold_literal_templates(e: &mut Expr) { + let literal = |e: &Expr| match e { + Expr::Str(s, _) => Some(s.clone()), + Expr::Typed(inner, ..) => match &**inner { + Expr::Str(s, _) => Some(s.clone()), + _ => None, + }, + _ => None, + }; + match e { + Expr::Template(parts, span) => { + // A hole that is itself a literal template is its literal first + for part in parts.iter_mut() { + if let TemplatePart::Expr(hole) = part { + fold_literal_templates(hole); + } + } + let mut text = String::new(); + for part in parts.iter() { + match part { + TemplatePart::Text(t) => text.push_str(t), + TemplatePart::Expr(hole) => match literal(hole) { + Some(s) => text.push_str(&s), + None => return, + }, + } + } + *e = Expr::Str(text, *span); + } + Expr::Ternary(_, yes, no, _) + | Expr::Match { + some: yes, + none: no, + .. + } => { + fold_literal_templates(yes); + fold_literal_templates(no); + } + Expr::Let { body, .. } | Expr::Typed(body, ..) => fold_literal_templates(body), + _ => {} + } +} + +/// A length row's value with each token `var()` in it written as the +/// token's value, refused where the token varies by mode. The loader leaves +/// such a call as written only in a runtime fallback, having written every +/// other as the token's name, which the theme binds. A row's attribute goes +/// through this before a box shorthand splits its sides, so each side's +/// fallback is written too. +pub(crate) fn fallback_tokens<'a>( + a: &'a Attr, + rows: &[StyleId], +) -> Result, LowerError> { + if !rows + .iter() + .all(|r| r.codec() == exact_kernel::StyleCodec::Dimension) + { + return Ok(Cow::Borrowed(a)); + } + let mut out = a.clone(); + let mut varying = None; + let changed = texts(&mut out.value, &mut |text, _| { + token_calls(text, &mut varying) + }); + if let Some(token) = varying { + return Err(LowerError { + id: "lower-attr-value", + message: format!("`{}`: the design token `{token}` differs between the app's modes, and a custom property's fallback is read at run time, where nothing binds it; give the property a value, or write a fixed length as its fallback", a.name), + span: a.span, + }); + } + Ok(match changed { + true => Cow::Owned(out), + false => Cow::Borrowed(a), + }) +} + +/// `text` with each `var()` of a length token that has one value in every +/// app mode written as the value; whether any was. A call in a comment, of a +/// host's name (`--exact-`, LLP 1081 D5) or of a name no length token has +/// stays. +fn token_calls(text: &mut String, varying: &mut Option) -> bool { + let name_char = |c: char| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'); + let mut out = String::with_capacity(text.len()); + let (mut at, mut i, mut changed) = (0, 0, false); + while let Some(c) = text[i..].chars().next() { + if let Some(past) = comment_end(text, i) { + i = past; + continue; + } + let call = text[i..] + .get(..4) + .is_some_and(|s| s.eq_ignore_ascii_case("var(")) + && !text[..i].ends_with(name_char); + if !call { + i += c.len_utf8(); + continue; + } + let args = i + 4; + let rest = text[args..].trim_start(); + let name = rest.strip_prefix("--").unwrap_or_default(); + let name = &name[..name.find(|c| !name_char(c)).unwrap_or(name.len())]; + let Some(close) = call_end(text, args) else { + break; + }; + match crate::theme::measure_written(name).filter(|_| !name.starts_with("exact-")) { + Some((exact_forma::Kind::Length, values)) if values.len() == 1 => { + out.push_str(&text[at..i]); + out.push_str(&values[0]); + (at, i, changed) = (close + 1, close + 1, true); + } + Some((exact_forma::Kind::Length, _)) => { + varying.get_or_insert_with(|| name.to_string()); + i = args; + } + _ => i = args, + } + } + out.push_str(&text[at..]); + *text = out; + changed +} + +/// The byte of the `)` that closes a function whose arguments start at +/// `from`, past nested parentheses, strings and comments. +fn call_end(text: &str, from: usize) -> Option { + let (mut depth, mut quote, mut i) = (0usize, None, from); + while let Some(c) = text[i..].chars().next() { + if quote.is_none() { + if let Some(past) = comment_end(text, i) { + i = past; + continue; + } + } + match (quote, c) { + // An escape takes the whole character after it + (Some(_), '\\') => { + i += 1; + if let Some(escaped) = text[i..].chars().next() { + i += escaped.len_utf8(); + } + continue; + } + (Some(q), c) if c == q => quote = None, + (Some(_), _) => {} + (None, '"' | '\'') => quote = Some(c), + (None, '(') => depth += 1, + (None, ')') if depth == 0 => return Some(i), + (None, ')') => depth -= 1, + _ => {} + } + i += c.len_utf8(); + } + None +} + +/// Each literal text of `e`, in either arm of a choice, under a binding and +/// between a template's holes, passed to `f` with whether it is the whole +/// value; whether `f` changed any. +fn texts(e: &mut Expr, f: &mut dyn FnMut(&mut String, bool) -> bool) -> bool { + texts_in(e, f, true) +} + +/// [`texts`], `whole` where `e` is not inside a template, whose texts and +/// holes are each one part of the value. +fn texts_in(e: &mut Expr, f: &mut dyn FnMut(&mut String, bool) -> bool, whole: bool) -> bool { + match e { + Expr::Str(text, _) => f(text, whole), + Expr::Template(parts, _) => { + let mut changed = false; + for part in parts { + changed |= match part { + TemplatePart::Text(text) => f(text, false), + TemplatePart::Expr(e) => texts_in(e, f, false), + }; + } + changed + } + Expr::Ternary(_, yes, no, _) + | Expr::Match { + some: yes, + none: no, + .. + } => texts_in(yes, f, whole) | texts_in(no, f, whole), + Expr::Let { body, .. } | Expr::Typed(body, ..) => texts_in(body, f, whole), + _ => false, + } +} + +/// `text`, a whole literal value, with each word that names a length token +/// with one value in every app mode written as the value, as a length row +/// reads a token by name; whether any was. `varying`, where given, takes the +/// first length token with more than one value. A function's name, a custom +/// property's (after `-`), the variable `env()` names and a number's unit +/// are no token, and a comment is copied as it stands. +fn written_tokens(text: &mut String, mut varying: Option<&mut Option>) -> bool { + let mut out = String::with_capacity(text.len()); + let (mut changed, mut env, mut i) = (false, false, 0); + // What stands since the last word, comments aside + let mut between = String::new(); + while let Some(c) = text[i..].chars().next() { + if let Some(past) = comment_end(text, i) { + out.push_str(&text[i..past]); + // A comment separates what stands on either side, as white space does + between.push(' '); + i = past; + continue; + } + // A word starts with a letter or `_`, so `--_pad` is one name after `--` + if !c.is_ascii_alphabetic() && c != '_' { + out.push(c); + between.push(c); + i += c.len_utf8(); + continue; + } + let end = text[i..] + .find(|c: char| !(c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))) + .map_or(text.len(), |e| i + e); + let word = &text[i..end]; + // A word that follows a digit is the number's unit (`1fr`, `9.5rem`) + let unit = between.ends_with(|c: char| c.is_ascii_digit() || c == '.'); + let function = text[end..].starts_with('('); + let variable = env && between.trim() == "("; + let named = between.ends_with('-') || function || variable; + match crate::theme::measure_written(word).filter(|_| !unit && !named) { + Some((exact_forma::Kind::Length, values)) if values.len() == 1 => { + out.push_str(&values[0]); + changed = true; + } + Some((exact_forma::Kind::Length, _)) => { + if let Some(v) = varying.as_deref_mut() { + v.get_or_insert_with(|| word.to_string()); + } + out.push_str(word); + } + _ => out.push_str(word), + } + env = function && word.eq_ignore_ascii_case("env"); + between.clear(); + i = end; + } + *text = out; + changed +} + +/// Where a comment that opens at `i` ends, past its `*/` (or at the text's +/// end); `None` where none opens there. +fn comment_end(text: &str, i: usize) -> Option { + text[i..].starts_with("/*").then(|| { + text[i + 2..] + .find("*/") + .map_or(text.len(), |e| i + 2 + e + 2) + }) +} diff --git a/contract/lower/src/lib.rs b/contract/lower/src/lib.rs index b8a4222c1..cc99c23cf 100644 --- a/contract/lower/src/lib.rs +++ b/contract/lower/src/lib.rs @@ -172,8 +172,7 @@ pub use theme::retained::{ before_view, first_refusal, offer_design_scan, retention_only, take_design_scan, with_design_scan, DesignScan, }; -pub use theme::rows; -pub use theme::{retention, synthetic_candidates}; +pub use theme::{retention, rows, synthetic_candidates}; pub use warnings::{warnings, MAX_WARNINGS}; use contract_analyze::Analysis; @@ -1317,6 +1316,7 @@ impl<'a> Lowerer<'a> { } } tags::AttrTarget::Styles(rows) => { + let a = &*values::fallback_tokens(a, rows)?; if rows == [StyleId::FontFamily] { if self.family_token(a, scope, locals, bindings)? { return Ok(()); diff --git a/contract/lower/src/nodes.rs b/contract/lower/src/nodes.rs index 6547f36a3..be909ccf2 100644 --- a/contract/lower/src/nodes.rs +++ b/contract/lower/src/nodes.rs @@ -1,5 +1,7 @@ //! Element lowering keeps its large per-tag temporaries off the recursive view path. +#[path = "custom_props.rs"] +mod custom_props; use super::*; pub(super) struct ElementStep<'n> { @@ -598,7 +600,13 @@ impl Lowerer<'_> { } let flex = tags::flex_container(tag, expanded); self.element_children = !children.is_empty(); + let (custom, refused_custom) = custom_props::merged(expanded, scope, &self.types.shapes); + self.errors.extend(refused_custom); for (index, a) in expanded.iter().enumerate() { + // Its custom properties are bound as one row, after the others + if exact_kernel::style::safe_area_properties::is_author_name(&a.name) { + continue; + } if let Some(e) = flex.and_then(|f| tags::multicol_on_flex(f, a).err()) { self.errors.push(e); continue; @@ -718,6 +726,26 @@ impl Lowerer<'_> { origins.resize(bindings.len(), origin); } } + if let Some(a) = &custom { + let control = contract_syntax::payload_control(tag, attrs); + let font = &font; + if let Err(e) = self.attr( + tag, + control, + a, + scope, + locals, + &mut bindings, + &mut handlers, + &mut surface, + font, + ) { + self.errors.push(native::name_the_fix(n, e)); + } + if let Some(origins) = &mut origins { + origins.resize(bindings.len(), Origin::Own(None)); + } + } // @ref LLP 1116.006 D2 — no box where no split shows it (the web shell shows it). if routes::split_placeholder(expanded).is_some() { let none = self.fixed(true, "none"); diff --git a/contract/lower/src/tags.rs b/contract/lower/src/tags.rs index bfd560f5c..c1dd9cd06 100644 --- a/contract/lower/src/tags.rs +++ b/contract/lower/src/tags.rs @@ -421,6 +421,10 @@ pub fn attr(name: &str) -> Option { if let Some(target) = crate::style_names::lookup(name) { return Some(target); } + // @ref LLP 1123 D5 — a runtime custom property; a node's are one row + if exact_kernel::style::safe_area_properties::is_author_name(name) { + return Some(AttrTarget::Styles(&[StyleId::SafeAreaProperties])); + } Some(match name { "datetime" => AttrTarget::Prop(PropId::Datetime), "format" => AttrTarget::Prop(PropId::TimeFormat), diff --git a/contract/lower/src/values.rs b/contract/lower/src/values.rs index 685aee3c9..380286316 100644 --- a/contract/lower/src/values.rs +++ b/contract/lower/src/values.rs @@ -1,12 +1,16 @@ //! Attribute values checked against what they set, at compile time: a //! literal style value by the kernel's own row parser, a computed one and a //! prop by type (LLP 1017 P1a). +// @ref LLP 1123 D5 — length tokens written as their values where nothing binds one +#[path = "length_tokens.rs"] +mod length_tokens; use crate::style_names::press_refusal; use crate::{edits, err, media, symbols, tags, vocab, FontUse, LowerError}; use contract_syntax::{Attr, Expr, Span, TemplatePart, UnOp}; use contract_types::{Ref, Scope, Shapes, Ty}; use exact_kernel::style::sides as box_sides; use exact_kernel::{PropId, StyleId, StyleProps, StyleValue, StyleValueError}; +pub(crate) use length_tokens::{call_tokens, fallback_tokens, grid_tokens}; use std::{cell::Cell, rc::Rc}; /// A literal, as an author wrote it, for a message. fn literal_text(e: &Expr) -> String { @@ -32,64 +36,6 @@ fn constant_text(e: &Expr) -> Option { _ => None, } } -/// A grid track list with each length token it names written as the token's -/// value (`minmax(card-min-width, 1fr)`, the loader having written -/// `var(--card-min-width)` as the name), as a browser substitutes `var()` before -/// it parses the tracks (CSS Variables 1 §3). Only a token with one value in -/// every app mode is written in; the kernel's track parser refuses any other. -pub(crate) fn grid_tokens(a: &Attr, rows: &[StyleId]) -> Option { - if !rows - .iter() - .any(|r| matches!(r, StyleId::GridTemplateColumns | StyleId::GridTemplateRows)) - { - return None; - } - fn write(e: &mut Expr, changed: &mut bool) { - match e { - Expr::Str(text, _) => { - let mut out = String::with_capacity(text.len()); - let mut rest = text.as_str(); - while let Some(start) = rest.find(|c: char| c.is_ascii_alphabetic()) { - let (before, word) = rest.split_at(start); - let end = word - .find(|c: char| { - !(c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.')) - }) - .unwrap_or(word.len()); - // A word that follows a digit is the number's unit (`1fr`, `9.5rem`). - let unit = before.ends_with(|c: char| c.is_ascii_digit() || c == '.'); - out.push_str(before); - match crate::theme::measure_written(&word[..end]).filter(|_| !unit) { - Some((exact_forma::Kind::Length, values)) if values.len() == 1 => { - out.push_str(&values[0]); - *changed = true; - } - _ => out.push_str(&word[..end]), - } - rest = &word[end..]; - } - out.push_str(rest); - *text = out; - } - Expr::Ternary(_, yes, no, _) - | Expr::Match { - some: yes, - none: no, - .. - } => { - write(yes, changed); - write(no, changed); - } - Expr::Let { body, .. } => write(body, changed), - _ => {} - } - } - let mut out = a.clone(); - let mut changed = false; - write(&mut out.value, &mut changed); - changed.then_some(out) -} - /// `navigationSplit`'s column width written as a number: its text, as the /// prop carries it (LLP 1116.004 D1.2). pub(crate) fn split_width(prop: PropId, e: &Expr) -> Option { @@ -233,6 +179,7 @@ pub(crate) fn describe(e: &StyleValueError) -> String { StyleValueError::BadAnimationRange { .. } => "expected normal, or one or two distinct ends, each normal, a length or percentage, or a range name (cover, contain, entry, exit, entry-crossing, exit-crossing) with an optional length or percentage (`0px 300px`, `entry 20% cover 50%`)".into(), StyleValueError::BadPositionTryFallbacks { .. } => "expected none, or comma-separated attempts, each one to three of flip-block, flip-inline and flip-start, applied in order; flip-x, flip-y and named rules are not implemented".into(), StyleValueError::BadTimelineScope { .. } => "expected none, all, or `--name`s separated by commas".into(), + StyleValueError::BadSafeAreaProperties { .. } => "expected `--name: ` declarations: a length in px, rem, a percentage, a viewport unit, env(), var(), or calc(), min(), max() or clamp() of these; a name is `--` and an identifier that does not start `--exact-`".into(), StyleValueError::BadTimelineName { .. } => "expected none or one `--name`".into(), StyleValueError::BadViewTimelineInset { .. } => "expected one or two of auto and a length or percentage, the start then the end".into(), StyleValueError::BadTransition { .. } => "unsupported transition property or invalid timing components; exact2 supports transform components, opacity, paint and SVG properties, and admitted numeric height transitions; general layout interpolation is not implemented".into(), diff --git a/contract/lower/src/var_tokens.rs b/contract/lower/src/var_tokens.rs index 4daf04448..bec031001 100644 --- a/contract/lower/src/var_tokens.rs +++ b/contract/lower/src/var_tokens.rs @@ -1,30 +1,36 @@ -//! @ref LLP 1153 D6 — `var(--name)` in a style row is the design's token -//! `name`. Each one is written as the name before anything reads the row -//! (scoping, the types, the design's retention): by the loader for a file, -//! and by `contract::compile` for a source text. So it lowers exactly as the -//! name does: folded, or on the web the token's `var(--x-name)` where it -//! varies. A browser substitutes `var()` when it computes a value; a token is -//! the build's, which every host draws, so a reference resolves only to a -//! token the app declares. +//! @ref LLP 1153 D6, LLP 1123 D5 — `var(--name)` in a style row names, in +//! this order: //! -//! - A name the design declares is the token. A fallback is never used, and -//! the app is warned once (`forma-var-fallback`). -//! - Any other `var()` in a style row is refused, fallback or not, so a typo -//! never ships the fallback (`forma-unknown-token`, naming the design's -//! tokens of the kinds the row takes). The refused row is dropped, so the -//! passes after the loader say nothing more of it. -//! - The host's own custom properties, the safe area where a box is -//! (`var(--exact-safe-area-inset-top)`, LLP 1123 D9), are no token: they -//! are left for the kernel, which reads them. -//! - A component's argument, a `fn`'s result and a `derive`'s value that is -//! one `var()` naming a token is that token, as a row reads it once the -//! component is expanded or the call made. Any other argument is -//! left as written, since it may be text; where it reaches a style row, a -//! `var()` in it naming no token is refused there ([`carried`]). +//! - The host's own custom property (`var(--exact-safe-area-inset-top)`, +//! LLP 1123 D9), which is left for the kernel. +//! - The design's token `name`, written as the name before anything reads +//! the row (scoping, the types, the design's retention): by the loader for +//! a file, and by `contract::compile` for a source text. It lowers exactly +//! as the name does: folded, or on the web the token's `var(--x-name)` +//! where it varies. A fallback is never used, and the app is warned once +//! (`forma-var-fallback`). +//! - In a length row or a declaration, a runtime custom property some node +//! of the app declares (`--gap="8px"`), which the kernel reads at run +//! time, its fallback a value checked as the row's own; any other row +//! refuses one. A name nothing declares, which can only take its fallback, +//! is warned with one (`lower-var-undeclared`), as CSS admits it. +//! - Nothing else: the call is refused, so a typo never ships its fallback +//! (`forma-unknown-token`, naming the design's tokens of the kinds the row +//! takes). A name with a `.`, which no node can declare, is a token's. The +//! refused row is dropped, so the passes after the loader say nothing more +//! of it. +//! +//! A component's argument, a `fn`'s result and a `derive`'s value that is +//! one `var()` naming a token is that token, as a row reads it once the +//! component is expanded or the call made. Any other argument is left as +//! written, since it may be text; where it reaches a style row, a `var()` in +//! it naming no token is refused there ([`carried`]). use crate::{tags, LowerError}; use contract_syntax::{Attr, DesignSource, Expr, File, Node, Span, TemplatePart, ThemeDecl}; use exact_forma as forma; +use exact_kernel::style::safe_area_properties::is_author_name; +use exact_kernel::StyleId; /// The tokens an app declares, as a `var()` may name them. #[derive(Debug, Clone, Default)] @@ -38,6 +44,9 @@ pub struct Tokens { /// design is read, so its `var()`s are written as names and refused no /// further. parsed: bool, + /// The runtime custom properties the app's nodes declare (LLP 1123 D5), + /// each name after its `--`. + runtime: std::collections::BTreeSet, } impl Tokens { @@ -61,6 +70,7 @@ impl Tokens { names: Vec::new(), designed, parsed, + runtime: Default::default(), }; }; let names: Vec = merged.tokens.iter().map(|t| t.name.value.clone()).collect(); @@ -80,16 +90,42 @@ impl Tokens { names, designed, parsed, + runtime: Default::default(), + } + } + + /// These tokens with the runtime custom properties `files` declare. + pub fn with_runtime<'a>(mut self, files: impl IntoIterator) -> Tokens { + for file in files { + self.runtime.extend(declared_properties(file)); } + self } fn declares(&self, name: &str) -> bool { !self.parsed || self.names.iter().any(|(n, _)| n == name) } + + /// The one token or declared property `name` most plausibly misspells. + fn near(&self, name: &str) -> Option { + let tokens = self.names.iter().map(|(n, _)| n.as_str()); + contract_syntax::suggestion(name, tokens.chain(self.runtime.iter().map(String::as_str))) + .map(str::to_string) + } +} + +/// A `var()` of a name no token or node declares (LLP 1123 D5): the call as +/// written, and the one declared name it most plausibly misspells. +#[derive(Debug, Clone, PartialEq)] +pub struct Undeclared { + /// The call as written. + pub call: String, + /// The token or declared property it most plausibly misspells. + pub near: Option, } -/// What [`rewrite`] reports: the rows it refused, and the fallbacks it -/// dropped. +/// What [`rewrite`] reports: the rows it refused, the fallbacks it +/// dropped, and the `var()`s of names nothing declares. #[derive(Debug, Default)] pub struct Rewritten { /// Each style row refused, and dropped from the file. @@ -97,11 +133,75 @@ pub struct Rewritten { /// Each `var()` whose fallback was dropped: where, and the call as /// written. pub fallbacks: Vec<(Span, String)>, + /// Each `var()` with a fallback of a name no token or node declares, + /// and where. + pub undeclared: Vec<(Span, Undeclared)>, +} + +/// The runtime custom properties `file`'s nodes and styles declare (LLP +/// 1123 D5), each name after its `--`. +pub fn declared_properties(file: &File) -> std::collections::BTreeSet { + // Every call here names no other compiler function (`from_iter`, not `new`): the walk + // census (`contract-checking`) matches calls by name and counts a walk that could recurse + let mut out = std::collections::BTreeSet::from_iter([]); + for s in &file.styles { + author_names(&s.attrs, &mut out); + } + for c in &file.components { + view_names(&c.view, &mut out); + } + if let Some(c) = &file.members { + view_names(&c.view, &mut out); + } + out +} + +/// Each custom property `view`'s elements declare, after its `--`, added to +/// `out`. +fn view_names(tree_nodes: &[Node], declared_names: &mut std::collections::BTreeSet) { + for n in Node::walk(tree_nodes) { + if let Node::Element { + attrs: own_attrs, .. + } = n + { + author_names(own_attrs, declared_names); + } + } +} + +/// Each custom property `list` declares, after its `--`, added to `out`. +fn author_names(list: &[Attr], out: &mut std::collections::BTreeSet) { + for a in list { + if is_author_name(&a.name) { + out.insert(a.name[2..].to_owned()); + } + } +} + +/// The one warning for every `var()` of a name nothing declares, at the +/// first (LLP 1123 D5). +pub fn undeclared_warning(found: &[(Span, Undeclared)]) -> Option { + let (span, Undeclared { call, near }) = found.first()?; + let name = call_name(call); + let near = near + .as_ref() + .map(|n| format!("; did you mean `--{n}`?")) + .unwrap_or_default(); + let others = match found.len() - 1 { + 0 => String::new(), + _ => "; other `var()`s in this app name undeclared properties likewise".into(), + }; + Some(LowerError { + id: "lower-var-undeclared", + message: format!("`{call}`: no node of this app declares `--{name}` and no token of the design is named so, so the fallback always stands in; declare it (`--{name}=\"…\"`) or write the fallback itself{near}{others}"), + span: *span, + }) } /// Write each `var()` of `file`'s style rows that names a token as its -/// name, refuse and drop each row with another, and write a component -/// argument that is one such `var()` as the name. +/// name, leave each that a length or a declaration reads at run time, refuse +/// and drop each row with another, and write a component argument that is +/// one such `var()` as the name (the module's order). pub fn rewrite(file: &mut File, tokens: &Tokens) -> Rewritten { let mut out = Rewritten::default(); for s in file @@ -133,8 +233,14 @@ pub fn rewrite(file: &mut File, tokens: &Tokens) -> Rewritten { } /// An app's design as [`Tokens::of`] reads it: `app.forma`'s text, its -/// packages' designs and an inline `theme`. -type Noted = (Option, Vec, Option); +/// packages' designs and an inline `theme`; and the runtime custom +/// properties its nodes declare. +type Noted = ( + Option, + Vec, + Option, + std::collections::BTreeSet, +); thread_local! { /// The design a `var()` may name while the app's styles are lowered, @@ -145,15 +251,20 @@ thread_local! { /// Note `file`'s design for the rows [`carried`] checks, as lowering starts. pub(crate) fn note(file: &File) { let design = file.design.as_ref().map(|d| d.text.clone()); - let noted = (design, file.package_designs.clone(), file.theme.clone()); + let noted = ( + design, + file.package_designs.clone(), + file.theme.clone(), + declared_properties(file), + ); DESIGN.with(|d| *d.borrow_mut() = Some(noted)); } /// A style row's `var()` that reached it through a component's argument, /// which the loader writes only when the argument is one `var()` naming a -/// token: one naming no token is refused as the loader refuses it in a row, -/// naming the tokens the row takes. A `var()` among other words of an -/// argument, naming a token, is left for the row's own check. +/// token: one the row cannot read is refused as the loader refuses it in a +/// row. A `var()` among other words of an argument, naming a token, is left +/// for the row's own check. pub(crate) fn carried(a: &Attr) -> Result<(), LowerError> { fn mentions(e: &Expr) -> bool { let named = |s: &str| { @@ -177,15 +288,16 @@ pub(crate) fn carried(a: &Attr) -> Result<(), LowerError> { if !tags::style(&a.name) || !mentions(&a.value) { return Ok(()); } - let Some((design, packages, theme)) = DESIGN.with(|d| d.borrow().clone()) else { + let Some((design, packages, theme, runtime)) = DESIGN.with(|d| d.borrow().clone()) else { return Ok(()); }; - let tokens = Tokens::of(design.as_deref(), &packages, theme.as_ref()); + let mut tokens = Tokens::of(design.as_deref(), &packages, theme.as_ref()); + tokens.runtime = runtime; let (mut out, mut refused) = (Rewritten::default(), None); value( &mut a.value.clone(), &tokens, - Mode::Row, + row_mode(a), &mut out, &mut refused, ); @@ -243,14 +355,21 @@ fn nodes(list: &mut [Node], tokens: &Tokens, out: &mut Rewritten) { } /// A list's style rows rewritten; one with a `var()` no token answers is -/// refused and dropped. +/// refused and dropped, as is a custom property named as a token is. fn rows(list: &mut Vec, tokens: &Tokens, out: &mut Rewritten) { list.retain_mut(|a| { if !tags::style(&a.name) { return true; } + let name = a.name.strip_prefix("--").unwrap_or_default(); + if tokens.parsed && tokens.names.iter().any(|(n, _)| n == name) { + let why = Why::Token(name.to_string()); + out.refused.push(refusal(a, why, "", a.span, tokens)); + return false; + } let mut refused = None; - value(&mut a.value, tokens, Mode::Row, out, &mut refused); + let mode = row_mode(a); + value(&mut a.value, tokens, mode, out, &mut refused); match refused { None => true, Some((why, literal, span)) => { @@ -263,8 +382,13 @@ fn rows(list: &mut Vec, tokens: &Tokens, out: &mut Rewritten) { #[derive(Clone, Copy, PartialEq)] enum Mode { - /// A style row's value: every `var()` written or refused. - Row, + /// A style row's value: every `var()` written or refused; whether the + /// row reads a runtime custom property ([`runtime_row`]). + Row(bool), + /// A custom property's declaration: a row that reads runtime properties, + /// whose token calls stay as written for lowering to write each + /// token's value ([`crate::values::call_tokens`]). + Declaration, /// A component's argument: a literal that is one `var()` naming a /// token, written; the rest left. Whole, @@ -279,6 +403,40 @@ enum Why { Unnamed, /// Its name is computed (a template's hole). Computed, + /// It names a runtime custom property in a row that reads none. + Runtime(String), + /// A node declares a custom property a token of the design is named. + Token(String), + /// A token of another kind than a length stands where a custom property + /// holds one. + NotLength(String), +} + +/// Whether `a`'s rows read a runtime custom property: lengths, which the +/// kernel substitutes per node, and declarations (LLP 1123 D5). +fn runtime_row(a: &Attr) -> bool { + use exact_kernel::StyleCodec; + let rows = tags::rows(a); + !rows.is_empty() + && !rows.iter().any(|r| local_inset(*r)) + && rows.iter().all(|r| { + matches!( + r.codec(), + StyleCodec::Dimension | StyleCodec::SafeAreaProperties + ) + }) +} + +/// Whether `row` overrides a content owner's local inset, which the kernel +/// resolves before any custom property, so it reads none. +fn local_inset(row: StyleId) -> bool { + matches!( + row, + StyleId::LocalInsetTop + | StyleId::LocalInsetRight + | StyleId::LocalInsetBottom + | StyleId::LocalInsetLeft + ) } /// The first refusal in a value: why, the literal's text, where. @@ -297,29 +455,49 @@ fn value(e: &mut Expr, tokens: &Tokens, mode: Mode, out: &mut Rewritten, refused if mode == Mode::Whole && whole_var(s).is_none() { return; } - match text(s, tokens, false, &mut None) { - Ok(Some((next, fallbacks))) => { + match text( + s, + tokens, + false, + &mut None, + runtime(mode), + mode == Mode::Declaration, + ) { + Ok(Some((next, fallbacks, undeclared))) => { out.fallbacks .extend(fallbacks.into_iter().map(|f| (*span, f))); + out.undeclared + .extend(undeclared.into_iter().map(|f| (*span, f))); *s = next; } Ok(None) => {} - Err(why) if mode == Mode::Row && refused.is_none() => { + Err(why) + if matches!(mode, Mode::Row(_) | Mode::Declaration) && refused.is_none() => + { *refused = Some((why, s.clone(), *span)); } Err(_) => {} } } - Expr::Template(parts, span) if mode == Mode::Row => { + Expr::Template(parts, span) if matches!(mode, Mode::Row(_) | Mode::Declaration) => { let mut quote = None; let n = parts.len(); for i in 0..n { let hole = i + 1 < n && matches!(parts[i + 1], TemplatePart::Expr(_)); match &mut parts[i] { - TemplatePart::Text(s) => match text(s, tokens, hole, &mut quote) { - Ok(Some((next, fallbacks))) => { + TemplatePart::Text(s) => match text( + s, + tokens, + hole, + &mut quote, + runtime(mode), + mode == Mode::Declaration, + ) { + Ok(Some((next, fallbacks, undeclared))) => { out.fallbacks .extend(fallbacks.into_iter().map(|f| (*span, f))); + out.undeclared + .extend(undeclared.into_iter().map(|f| (*span, f))); *s = next; } Ok(None) => {} @@ -424,31 +602,54 @@ pub fn whole_var(text: &str) -> Option<(String, bool)> { /// A `var(` in a literal's text. #[derive(Debug, PartialEq)] enum Found { - /// A whole call: its bytes, its name and its fallback as written. + /// A whole call: its bytes, its name and its fallback's bytes. Call { at: std::ops::Range, name: String, - fallback: Option, + fallback: Option>, }, /// One with no name, or whose name a template's hole computes. Bad(Why), } -/// `text` with each `var()` naming a token written as the name, and each -/// call whose fallback it dropped; `None` when it has no `var()`. `hole`: -/// a template's hole follows the text. `quote`: the quote a template's -/// earlier text left open, and this text leaves open. +/// Whether a value in `mode` may read a runtime custom property. +fn runtime(mode: Mode) -> bool { + matches!(mode, Mode::Row(true) | Mode::Declaration) +} + +/// How a style row's value is rewritten: a declaration's apart from any +/// other row's. +fn row_mode(a: &Attr) -> Mode { + match tags::rows(a).as_slice() { + [StyleId::SafeAreaProperties] => Mode::Declaration, + _ => Mode::Row(runtime_row(a)), + } +} + +/// A text's `var()`s rewritten: the text, each call whose fallback was +/// dropped, and each call of a name nothing declares. +type Written = (String, Vec, Vec); + +/// `text` with each `var()` naming a token written as the name, each call +/// whose fallback it dropped, and each of a name nothing declares, which +/// its fallback answers (`runtime`: the row reads runtime custom +/// properties); `None` when it has no `var()`. `hole`: a template's hole +/// follows the text. `quote`: the quote a template's earlier text left +/// open, and this text leaves open. fn text( text: &str, tokens: &Tokens, hole: bool, quote: &mut Option, -) -> Result)>, Why> { + runtime: bool, + keep: bool, +) -> Result, Why> { let found = calls(text, hole, quote); if found.is_empty() { return Ok(None); } - let (mut out, mut fallbacks, mut at) = (String::new(), Vec::new(), 0); + let (mut out, mut fallbacks, mut undeclared, mut at) = + (String::new(), Vec::new(), Vec::new(), 0); for f in found { match f { Found::Call { @@ -460,13 +661,56 @@ fn text( continue; } if !tokens.declares(&name) { - return Err(Why::Unknown(name, fallback.is_some())); + // Exact reserves dotted names for design tokens, so no node declares one + let property = !name.contains('.'); + match tokens.runtime.contains(&name) { + true if runtime => {} + true => return Err(Why::Runtime(name)), + false if runtime && property && fallback.is_some() => { + let near = tokens.near(&name); + let call = text[range].to_string(); + undeclared.push(Undeclared { call, near }); + } + false => return Err(Why::Unknown(name, fallback.is_some())), + } + // The call stays for the kernel, its fallback a value of its own + if let Some(f) = fallback { + let inner = (self::text)( + &text[f.clone()], + tokens, + false, + &mut None, + runtime, + true, + )?; + if let Some((inner, mut dropped, mut unknown)) = inner { + out.push_str(&text[at..f.start]); + out.push_str(&inner); + at = f.end; + fallbacks.append(&mut dropped); + undeclared.append(&mut unknown); + } + } + continue; } // A design that does not parse names no token: its refusal // fails the build, and no fallback is said to be unused. if fallback.is_some() && tokens.parsed { fallbacks.push(text[range.clone()].to_string()); } + // A declaration's or a runtime fallback's token call stays for + // lowering to write as its value + if keep { + let kind = tokens + .names + .iter() + .find(|(n, _)| *n == name) + .and_then(|(_, k)| *k); + if kind.is_some_and(|k| k != forma::Kind::Length) { + return Err(Why::NotLength(name)); + } + continue; + } out.push_str(&text[at..range.start]); out.push_str(&name); at = range.end; @@ -475,7 +719,7 @@ fn text( } } out.push_str(&text[at..]); - Ok(Some((out, fallbacks))) + Ok(Some((out, fallbacks, undeclared))) } /// Whether `name` (after its `--`) is a custom property the host sets. @@ -505,6 +749,13 @@ fn calls(text: &str, hole: bool, quote: &mut Option) -> Vec { i += 1; continue; } + // A comment holds no call + if text[i..].starts_with("/*") { + i = text[i + 2..] + .find("*/") + .map_or(text.len(), |e| i + 2 + e + 2); + continue; + } let opens = text .get(i..i + 4) .is_some_and(|s| s.eq_ignore_ascii_case("var(")) @@ -547,7 +798,7 @@ fn calls(text: &str, hole: bool, quote: &mut Option) -> Vec { found.push(Found::Call { at: i..end + 1, name: name.to_string(), - fallback: Some(text[after + 1..end].trim().to_string()), + fallback: Some(after + 1..end), }); i = end + 1; } @@ -599,6 +850,22 @@ fn refusal(a: &Attr, why: Why, literal: &str, span: Span, tokens: &Tokens) -> Lo "lower-attr-value", format!("{written}: a `var()` names its token whole; a token's name from data is the value itself (`{}=name`), which the runtime reads against the design", a.name), ), + Why::NotLength(name) => ( + "lower-attr-value", + format!("{written}: `--{name}` is a design token of another kind than a length, and a custom property's value, or a fallback a length reads at run time, is a length"), + ), + Why::Token(name) => ( + "lower-attr-value", + format!("`{}`: `{name}` is a token of this app's design, and `var(--{name})` reads the token, so no node declares a custom property of that name; name the property otherwise", a.name), + ), + Why::Runtime(name) if tags::rows(a).into_iter().any(local_inset) => ( + "lower-attr-value", + format!("{written}: `{}` sets the content owner's inset, which the kernel resolves before any custom property, so it reads none; write the length `--{name}` holds", a.name), + ), + Why::Runtime(name) => ( + "lower-attr-value", + format!("{written}: `--{name}` is a custom property a node declares, which a length (`padding`, `width`, …) or another declaration reads; `{}` names a token of the design (`var(--name)` of a token, or a role)", a.name), + ), Why::Unknown(name, fallback) => { let kinds = kinds(a); let said = kinds @@ -635,9 +902,19 @@ fn refusal(a: &Attr, why: Why, literal: &str, span: Span, tokens: &Tokens) -> Lo } else { "" }; + // A length reads a custom property a node declares too (LLP 1123 D5) + let (nodes, near) = match runtime_row(a) { + true => ( + " and no node of the app declares it", + (tokens.near(&name).filter(|_| dotted.is_empty())) + .map(|n| format!("; did you mean `--{n}`?")) + .unwrap_or_default(), + ), + false => ("", String::new()), + }; ( "forma-unknown-token", - format!("{written}: `--{name}` is no token of this app's design; {listed}{dotted}{role}{fallback}"), + format!("{written}: `--{name}` is no token of this app's design{nodes}; {listed}{dotted}{role}{near}{fallback}"), ) } }; @@ -693,11 +970,20 @@ mod tests { names: names.iter().map(|n| (n.to_string(), None)).collect(), designed: true, parsed: true, + runtime: Default::default(), } } fn written(s: &str) -> Result, Why> { - text(s, &tokens(&["ink", "space.row"]), false, &mut None).map(|o| o.map(|(s, _)| s)) + text( + s, + &tokens(&["ink", "space.row"]), + false, + &mut None, + false, + false, + ) + .map(|o| o.map(|(s, ..)| s)) } #[test] @@ -737,7 +1023,10 @@ mod tests { assert_eq!(written("var(--ink"), Err(Why::Unnamed)); // A name a template's hole completes. let t = tokens(&["ink"]); - assert_eq!(text("var(--", &t, true, &mut None), Err(Why::Computed)); + assert_eq!( + text("var(--", &t, true, &mut None, false, false), + Err(Why::Computed) + ); } #[test] @@ -756,7 +1045,7 @@ mod tests { #[test] fn a_fallback_is_kept_for_the_warning() { let t = tokens(&["ink"]); - let (_, fallbacks) = text("var(--ink, #111)", &t, false, &mut None) + let (_, fallbacks, _) = text("var(--ink, #111)", &t, false, &mut None, false, false) .unwrap() .unwrap(); assert_eq!(fallbacks, ["var(--ink, #111)"]); diff --git a/contract/syntax/src/lexer.rs b/contract/syntax/src/lexer.rs index 6dd506dd4..c7fdc4848 100644 --- a/contract/syntax/src/lexer.rs +++ b/contract/syntax/src/lexer.rs @@ -247,29 +247,29 @@ impl Lexer { // A vendor-prefixed CSS name, as the Compat Standard spells // some (`-webkit-text-stroke`, LLP 1077 D7), or one Exact // invents (`-exact-press-scale`, LLP 1081 D7), or a custom - // property the host defines (`--exact-safe-area-inset-top`, - // LLP 1123 D9): these prefixes only, and only as an - // attribute's name (followed by `=`), so `-webkit-x` in an - // expression stays a negation. - let vendor = ["-webkit-", "-apple-", "-exact-", "--exact-"] - .iter() - .find(|p| { - trimmed[pos..].starts_with(*p) - && bytes - .get(pos + p.len()) - .is_some_and(|n| (*n as char).is_ascii_alphabetic()) - && { - let rest = &trimmed[pos + p.find(|c| c != '-').unwrap_or(1)..]; - let end = rest - .find(|c: char| { - !(c.is_ascii_alphanumeric() || c == '-' || c == '_') - }) - .unwrap_or(rest.len()); - let after = rest[end..].trim_start_matches([' ', '\t']); - after.starts_with('=') && !after.starts_with("==") - } - }); - let dashes = vendor.map_or(0, |p| p.find(|c| c != '-').unwrap_or(1)); + // property (`--gap`, LLP 1123 D5; the host's own, + // `--exact-safe-area-inset-top`, D9): these prefixes only, + // and only as an attribute's name (followed by `=`), so + // `-webkit-x` in an expression stays a negation. + let vendor = ["-webkit-", "-apple-", "-exact-", "--"].iter().find(|p| { + trimmed[pos..].starts_with(*p) + && bytes.get(pos + p.len()).is_some_and(|n| { + let n = *n as char; + n.is_ascii_alphabetic() + || (**p == "--" && (n.is_ascii_digit() || n == '_')) + }) + && { + let rest = &trimmed[pos + leading_dashes(p)..]; + let end = rest + .find(|c: char| { + !(c.is_ascii_alphanumeric() || c == '-' || c == '_') + }) + .unwrap_or(rest.len()); + let after = rest[end..].trim_start_matches([' ', '\t']); + after.starts_with('=') && !after.starts_with("==") + } + }); + let dashes = vendor.map_or(0, |p| leading_dashes(p)); if c.is_ascii_alphabetic() || c == '_' || dashes > 0 { // An identifier may contain hyphens — `font-size`, // `aria-label` — as CSS's do; so, as in CSS `calc()`, @@ -277,13 +277,17 @@ impl Lexer { // while `x-1` still lexes as `x`, `-`, `1` (LLP 1017 §8.1). let start = pos; pos += dashes; + // A custom property's name, only ever an attribute's, takes + // every character CSS's does (`--gap-2`) + let custom = dashes == 2; while pos < bytes.len() && ((bytes[pos] as char).is_ascii_alphanumeric() || bytes[pos] == b'_' || (bytes[pos] == b'-' - && bytes - .get(pos + 1) - .is_some_and(|n| (*n as char).is_ascii_alphabetic()))) + && (custom + || bytes + .get(pos + 1) + .is_some_and(|n| (*n as char).is_ascii_alphabetic())))) { pos += 1; } @@ -685,3 +689,9 @@ fn skip_escaped(text: &str, slash: usize) -> usize { fn char_len(text: &str, pos: usize) -> usize { text[pos..].chars().next().map(char::len_utf8).unwrap_or(1) } + +/// How many `-` a name prefix starts with: two for a custom property's +/// `--`, one for a vendor's. +fn leading_dashes(prefix: &str) -> usize { + prefix.len() - prefix.trim_start_matches('-').len() +} diff --git a/host/apple/include/exact.h b/host/apple/include/exact.h index ecfc53911..193f7cd73 100644 --- a/host/apple/include/exact.h +++ b/host/apple/include/exact.h @@ -256,7 +256,7 @@ size_t exact_corner_outline(const float *shape, float x, float y, float width, f /* A style owns this environment snapshot until destroy. Values: top, right, bottom, left, * viewport width/height (the window's when a sheet is open), segment cols/rows, the layout * regions' count (0 or 20) and the regions (LLP 1123 D10), the title-bar area's count (0 or 4) - * and its x,y,w,h, then x,y,w,h per segment. create copies them and parses the UTF-8 + * and its x,y,w,h, x,y,w,h per segment, then the root font size. create copies them and parses the UTF-8 * expression; NULL for malformed input. * resolve borrows a live context; destroy consumes it exactly once (NULL is allowed). */ void *exact_calc_create(const uint8_t *text, size_t len, const double *values, size_t count); diff --git a/host/apple/src/calc.rs b/host/apple/src/calc.rs index 82d34db0f..91d261be3 100644 --- a/host/apple/src/calc.rs +++ b/host/apple/src/calc.rs @@ -11,6 +11,11 @@ impl Context { /// Read canonical CSS and copy its environment. See `exact_calc_create` in exact.h. pub fn new(text: &str, values: &[f64]) -> Option> { let calculation = Comparison::from_css(text)?; + // The root font size, which a `rem` multiplies, last + let (&root_font_size, values) = values.split_last()?; + if !(root_font_size > 0.0 && (root_font_size as f32).is_finite()) { + return None; + } // The layout regions' count, exactly 0 or 20, then the regions (LLP // 1123 D10); the title-bar area's, 0 or 4, then the area let regions = match values.get(8) { @@ -41,6 +46,7 @@ impl Context { values[2] as f32, values[3] as f32, ); + env.root_font_size = root_font_size as f32; env.viewport_width = values[4] as f32; env.viewport_height = values[5] as f32; env.cols = values[6] as u8; @@ -109,7 +115,7 @@ pub fn write(out: &mut String, c: Comparison, env: &Env) { for r in &env.segments { let _ = write!(out, ",{},{},{},{}", r.x, r.y, r.width, r.height); } - out.push_str("]}"); + let _ = write!(out, ",{}]}}", env.root_font_size); } /// Export the calculation seam from the application's static archive. @@ -127,8 +133,8 @@ macro_rules! calc_exports { count: usize, ) -> *mut ::std::ffi::c_void { // Eight values, the regions' count and twenty regions, the title-bar - // area's count and its four values, then up to 255×255 segments - if text.is_null() || values.is_null() || count > 9 + 20 + 1 + 4 + 4 * 255 * 255 { + // area's count and its four values, up to 255×255 segments, then the root font size + if text.is_null() || values.is_null() || count > 9 + 20 + 1 + 4 + 4 * 255 * 255 + 1 { return ::std::ptr::null_mut(); } // SAFETY: the caller supplies count readable, aligned doubles. @@ -185,13 +191,14 @@ mod tests { super::write(&mut json, c, &exact_kernel::Env::default()); let survivor = super::Context::new( "min(47px, 53%)", - &[0., 0., 0., 0., 300., 600., 1., 1., 0., 0.], + &[0., 0., 0., 0., 300., 600., 1., 1., 0., 0., 16.], ) .unwrap(); for i in 0..16_000 { let text = format!("min({i}px, 52%)"); let context = - super::Context::new(&text, &[0., 0., 0., 0., 300., 600., 1., 1., 0., 0.]).unwrap(); + super::Context::new(&text, &[0., 0., 0., 0., 300., 600., 1., 1., 0., 0., 16.]) + .unwrap(); assert_eq!(context.length(100.), f64::from((i as f32).min(52.))); let old = identity(&context.calculation); drop(context); @@ -210,7 +217,7 @@ mod tests { let value: serde_json::Value = serde_json::from_str(&json).unwrap(); let context = super::Context::new( value["calc"].as_str().unwrap(), - &[0., 0., 0., 0., 300., 600., 1., 1., 0., 0.], + &[0., 0., 0., 0., 300., 600., 1., 1., 0., 0., 16.], ) .unwrap(); drop(value); @@ -221,11 +228,14 @@ mod tests { #[test] fn contexts_keep_their_own_environment_and_validate_the_wire() { let n = "min(50%, 10vw + env(safe-area-inset-top))"; - let first = super::Context::new(n, &[3., 0., 0., 0., 300., 600., 1., 1., 0., 0.]).unwrap(); + let first = + super::Context::new(n, &[3., 0., 0., 0., 300., 600., 1., 1., 0., 0., 16.]).unwrap(); for width in 400..1400 { - let other = - super::Context::new(n, &[7., 0., 0., 0., width as f64, 600., 1., 1., 0., 0.]) - .unwrap(); + let other = super::Context::new( + n, + &[7., 0., 0., 0., width as f64, 600., 1., 1., 0., 0., 16.], + ) + .unwrap(); assert!((other.length(400.) - (width as f64 / 10. + 7.).min(200.)).abs() < 0.0001); assert_eq!(first.length(400.), 33.); } @@ -236,10 +246,43 @@ mod tests { ); for bad in [0., 1.5, 256., f64::INFINITY, f64::NAN] { assert!( - super::Context::new(n, &[0., 0., 0., 0., 300., 600., bad, 1., 0., 0.]).is_none() + super::Context::new(n, &[0., 0., 0., 0., 300., 600., bad, 1., 0., 0., 16.]) + .is_none() ); } - assert!(super::Context::new(n, &[0., 0., 0., 0., 300., 600., 2., 1., 0., 0.]).is_none()); + assert!( + super::Context::new(n, &[0., 0., 0., 0., 300., 600., 2., 1., 0., 0., 16.]).is_none() + ); + for bad in [0., -16., f64::INFINITY] { + assert!( + super::Context::new(n, &[0., 0., 0., 0., 300., 600., 1., 1., 0., 0., bad]) + .is_none(), + "a root font size of {bad}" + ); + } + } + + /// A deferred calculation's `rem` is the root font size the snapshot + /// carries, which a custom property's value can hold (LLP 1123 D5). + #[test] + fn a_snapshot_carries_the_root_font_size() { + let exact_kernel::Dimension::Compare(c) = + exact_kernel::Dimension::parse_calc("min(50%, 2rem)").unwrap() + else { + panic!("expected comparison"); + }; + let env = exact_kernel::Env { + root_font_size: 20., + ..Default::default() + }; + let mut json = String::new(); + super::write(&mut json, c, &env); + let value: serde_json::Value = serde_json::from_str(&json).unwrap(); + let values: Vec = (value["env"].as_array().unwrap().iter()) + .map(|v| v.as_f64().unwrap()) + .collect(); + let context = super::Context::new(value["calc"].as_str().unwrap(), &values).unwrap(); + assert_eq!(context.length(100.), 40.); } /// LLP 1123 D10: a deferred calculation reads the layout regions the @@ -345,11 +388,13 @@ mod tests { #[test] fn a_context_resolves_against_its_basis_as_the_kernel_does() { let n = "min(50%, 30px)"; - let context = super::Context::new(n, &[0., 0., 0., 0., 0., 0., 1., 1., 0., 0.]).unwrap(); + let context = + super::Context::new(n, &[0., 0., 0., 0., 0., 0., 1., 1., 0., 0., 16.]).unwrap(); assert_eq!(context.length(40.0), 20.0); assert_eq!(context.length(200.0), 30.0); assert!( - super::Context::new("10px", &[0., 0., 0., 0., 300., 600., 1., 1., 0., 0.]).is_none() + super::Context::new("10px", &[0., 0., 0., 0., 300., 600., 1., 1., 0., 0., 16.]) + .is_none() ); } } @@ -371,7 +416,7 @@ mod ffi_tests { #[test] fn the_native_entry_point_owns_its_expression_and_validates_utf8() { let text = b"min(47px, 53%)".to_vec(); - let values = [0., 0., 0., 0., 300., 600., 1., 1., 0., 0.]; + let values = [0., 0., 0., 0., 300., 600., 1., 1., 0., 0., 16.]; // SAFETY: both buffers remain readable for the call; create copies them. let context = unsafe { exact_calc_create(text.as_ptr(), text.len(), values.as_ptr(), values.len()) }; diff --git a/host/apple/src/style.rs b/host/apple/src/style.rs index 187929888..d64ad0ac5 100644 --- a/host/apple/src/style.rs +++ b/host/apple/src/style.rs @@ -161,6 +161,8 @@ pub(crate) fn style_json_rows( out.push_str("\":"); let wrote = match style.get(id) { RowValue::ShapeOutside(_) => false, // LLP 1043.000 M3 + // The kernel's own (LLP 1123 D5): the lengths that read them are sent resolved + RowValue::SafeAreaProperties(_) => false, // Layout only (LLP 1053 G1): the kernel sizes the box. RowValue::AspectRatio(_) => false, RowValue::PositionTryFallbacks(v) => { diff --git a/host/apple/tests/ExactKitTests/BoxLayerIOSTests.swift b/host/apple/tests/ExactKitTests/BoxLayerIOSTests.swift index 3b74502b4..4680dde04 100644 --- a/host/apple/tests/ExactKitTests/BoxLayerIOSTests.swift +++ b/host/apple/tests/ExactKitTests/BoxLayerIOSTests.swift @@ -62,7 +62,7 @@ final class BoxLayerIOSTests: XCTestCase { func testACalculatedRadiusReadsTheKernelOnEachAxis() throws { let radius = try XCTUnwrap(CalculatedLength([ "calc": .string("min(50%, 10vw)"), - "env": [0, 0, 0, 0, 300, 600, 1, 1, 0, 0] + "env": [0, 0, 0, 0, 300, 600, 1, 1, 0, 0, 16] ])) var style: NodeStyle = ["background_color": [36, 104, 172, 255]] for corner in ["top_left", "top_right", "bottom_right", "bottom_left"] { @@ -74,7 +74,7 @@ final class BoxLayerIOSTests: XCTestCase { // Cancellation precedes the final conversion to layout precision. let steep = BatchValue.calculation(try XCTUnwrap(CalculatedLength([ "calc": .string("calc(1e9 * (min(0.1%, 1px) - 0.2px) + 10px)"), - "env": [0, 0, 0, 0, 300, 600, 1, 1, 0, 0] + "env": [0, 0, 0, 0, 300, 600, 1, 1, 0, 0, 16] ]))) XCTAssertEqual(steep.length(basis: 200), 10) } @@ -235,7 +235,7 @@ final class BoxLayerIOSTests: XCTestCase { func testAPaddingResolvedAtLayoutReadsTheKernelsContentBox() throws { let padding = try XCTUnwrap(CalculatedLength([ "calc": .string("min(10%, 20px)"), - "env": [0, 0, 0, 0, 300, 600, 1, 1, 0, 0] + "env": [0, 0, 0, 0, 300, 600, 1, 1, 0, 0, 16] ])) let knots: NodeStyle = ["padding_top": .calculation(padding)] var style = knots diff --git a/host/apple/tests/ExactKitTests/BoxLayerMacTests.swift b/host/apple/tests/ExactKitTests/BoxLayerMacTests.swift index 2f304ca40..dd1477631 100644 --- a/host/apple/tests/ExactKitTests/BoxLayerMacTests.swift +++ b/host/apple/tests/ExactKitTests/BoxLayerMacTests.swift @@ -315,7 +315,7 @@ final class BoxLayerMacTests: XCTestCase { func testAPaddingResolvedAtLayoutReadsTheKernelsContentBox() throws { let padding = try XCTUnwrap(CalculatedLength([ "calc": .string("min(10%, 20px)"), - "env": [0, 0, 0, 0, 300, 600, 1, 1, 0, 0] + "env": [0, 0, 0, 0, 300, 600, 1, 1, 0, 0, 16] ])) let knots: NodeStyle = ["padding_top": .calculation(padding)] var style = knots diff --git a/host/web-js/build.mjs b/host/web-js/build.mjs index 125b33920..1b505f323 100644 --- a/host/web-js/build.mjs +++ b/host/web-js/build.mjs @@ -251,7 +251,7 @@ if (!checkOnly || prerequisitesOnly) { if (rust || leaves.some(([flag]) => !leafTaken(flag))) webToolchainEnv(process.env); if (prerequisitesOnly) process.exit(0); } -const runtime = ['rt.js', 'clock.js', 'resources.js', 'tree.js', 'events.js', 'pieces.js', 'mount.js', 'strings.js', 'request-send.js', 'presence-bindings.js', 'rows.js', 'resource-inspection.js', 'rt-link.js', 'generation-reload.js', 'elements.js', 'editor.js', 'live-time.js', 'font-family.js', 'observers.js', 'grid.js', 'overlay.js', 'roster.js', 'router.js', 'route-pattern.js', 'schedule.js', 'each.js', 'timer-waits.js', 'timer-observations.js', 'budget.js', 'shape.js', 'pointer.js', 'document.js', 'media.js', 'links.js', 'commands.js', 'focus.js', 'backdrop.js', 'persist.js', 'chosen.js', 'modes.js', 'follow.js', 'zoom.js', 'beat.js', 'regions.js', 'said.js', 'held.js', 'uploads.js', 'lower.js']; +const runtime = ['rt.js', 'clock.js', 'resources.js', 'tree.js', 'events.js', 'pieces.js', 'mount.js', 'strings.js', 'request-send.js', 'presence-bindings.js', 'rows.js', 'resource-inspection.js', 'rt-link.js', 'generation-reload.js', 'elements.js', 'editor.js', 'live-time.js', 'font-family.js', 'observers.js', 'grid.js', 'overlay.js', 'roster.js', 'router.js', 'route-pattern.js', 'schedule.js', 'each.js', 'timer-waits.js', 'timer-observations.js', 'budget.js', 'shape.js', 'pointer.js', 'document.js', 'media.js', 'links.js', 'commands.js', 'focus.js', 'backdrop.js', 'persist.js', 'chosen.js', 'modes.js', 'follow.js', 'zoom.js', 'beat.js', 'regions.js', 'declarations.js', 'said.js', 'held.js', 'uploads.js', 'lower.js']; for (const f of runtime) cpSync(resolve(here, f === 'timer-observations.js' ? '../web/' + f : f), resolve(gen, f)); // The live table's runtime is the dev loop's build's alone. if (!devReload) writeFileSync(resolve(gen, 'modes.js'), withoutDev(readFileSync(resolve(here, 'modes.js'), 'utf8'))); diff --git a/host/web-js/custom-properties.test.mjs b/host/web-js/custom-properties.test.mjs new file mode 100644 index 000000000..89d09aa95 --- /dev/null +++ b/host/web-js/custom-properties.test.mjs @@ -0,0 +1,19 @@ +// LLP 1123 D5 on the JS target: a node's bound custom properties, one row, reach its style one declaration at a time, +// and a name it no longer declares, or one an author may not declare, is not left behind. +import { expect, test } from 'bun:test'; +import { declare } from './declarations.js'; + +test("a node's custom properties are written one declaration at a time, and one no longer declared goes", () => { + const set = new Map(); + const e = { style: { setProperty: (k, v) => set.set(k, v), removeProperty: (k) => set.delete(k) } }; + declare(e, '--gap: 8px; --pad: calc(2 * var(--gap))'); + expect([...set]).toEqual([['--gap', '8px'], ['--pad', 'calc(2 * var(--gap))']]); + // A `;` in a comment or a function is no boundary, and the comment stays, so no tokens join + declare(e, '--pad: calc(1px /*;*/ + 2px); --exact-safe-area-inset-top: 1px; bad: 2px; --a\\?: 1/**/px'); + expect([...set]).toEqual([['--pad', 'calc(1px /*;*/ + 2px)'], ['--a?', '1/**/px']]); + // A comment may stand around a name, and an escape CSS has no code point for is U+FFFD + declare(e, '--keep: 2px; /* note */ --b/**/: 4px; --\\110000: 8px'); + expect([...set]).toEqual([['--keep', '2px'], ['--b', '4px'], ['--\ufffd', '8px']]); + declare(e, null); + expect(set.size).toBe(0); +}); diff --git a/host/web-js/declarations.js b/host/web-js/declarations.js new file mode 100644 index 000000000..59f838f1d --- /dev/null +++ b/host/web-js/declarations.js @@ -0,0 +1,48 @@ +// A node's custom properties (LLP 1123 D5), `--a: ; --b: `, as one row's value: each written as itself, +// and one the node no longer declares removed. A `;` inside a comment, a string or a function is no boundary. +export function declare(e, t) { + const now = new Map(); + for (const d of declarations(t ?? '')) { + const [, written, value] = NAME.exec(d) ?? []; + const name = written && decoded(written); + if (name && !name.startsWith('--exact-')) now.set(name, value.trim()); + } + for (const name of e.$declared ?? []) if (!now.has(name)) e.style.removeProperty(name); + for (const [name, value] of now) e.style.setProperty(name, value); + e.$declared = [...now.keys()]; +} + +// A declaration: a custom property's name, in CSS's grammar with its escapes, then its value; white space and comments +// may stand around the name. +const NAME = /^(?:\s|\/\*[\s\S]*?\*\/)*(--(?:[\w-]|[^\x00-\x7f]|\\(?:[0-9a-fA-F]{1,6}\s?|[^\n0-9a-fA-F]))+)(?:\s|\/\*[\s\S]*?\*\/)*:([\s\S]*)$/; + +// A name with its escapes decoded, as the CSSOM names the property: a code point CSS has none of (zero, a surrogate, +// past U+10FFFF) is U+FFFD, as CSS Syntax 3 §4.3.7 decodes it. +const decoded = name => name.replace(/\\(?:([0-9a-fA-F]{1,6})\s?|([^\n]))/g, (_, hex, c) => { + if (!hex) return c; + const n = parseInt(hex, 16); + return String.fromCodePoint(n === 0 || (n >= 0xd800 && n <= 0xdfff) || n > 0x10ffff ? 0xfffd : n); +}); + +// The declarations of `t`, split at each top-level `;`. +function declarations(t) { + const out = []; + let at = 0, depth = 0, quote = null; + for (let i = 0; i < t.length; i++) { + const c = t[i]; + if (c === '\\') i++; + else if (quote) quote = c === quote ? null : quote; + else if (c === '/' && t[i + 1] === '*') { + const end = t.indexOf('*/', i + 2); + i = end < 0 ? t.length : end + 1; + } else if (c === '"' || c === "'") quote = c; + else if (c === '(') depth++; + else if (c === ')') depth = Math.max(0, depth - 1); + else if (c === ';' && depth === 0) { + out.push(t.slice(at, i)); + at = i + 1; + } + } + out.push(t.slice(at)); + return out; +} diff --git a/host/web-js/src/style.rs b/host/web-js/src/style.rs index bd290eaab..2100ffb97 100644 --- a/host/web-js/src/style.rs +++ b/host/web-js/src/style.rs @@ -1131,6 +1131,9 @@ pub fn style_writes(id: u16, timeline: bool, written: bool) -> Result with("timeline-scope", NONE), with("--exact-timeline-scope", NONE), ], + // @ref LLP 1123 D5 — a node's custom properties, which tree.js `css` + // writes one declaration at a time + StyleId::SafeAreaProperties => vec![with("--", "v=>v")], StyleId::GridTemplateColumns | StyleId::GridTemplateRows => vec![with( &css_property(row), "v=>gridValue(\"tracks\",v)", diff --git a/host/web-js/tree.js b/host/web-js/tree.js index 975c22c94..1de12e349 100644 --- a/host/web-js/tree.js +++ b/host/web-js/tree.js @@ -5,6 +5,7 @@ import { listRow, listOwner, renderMarkup } from './navigation.js'; import { Docs } from './document.js'; import { Refusal } from './shape.js'; import { regions } from './regions.js'; +import { declare } from './declarations.js'; import { backdropValue as backdropCss } from './backdrop.js'; import { onEnd, effect, say, inflight, After, Paint, Probes, Media, Links, Scrolls, Selects } from './rt.js'; import { Adopt, adopting } from './mount.js'; @@ -319,6 +320,7 @@ export function css(e, prop, unit, v, rendered) { t = cssText(prop, unit, v); if (last[prop] === t) return; last[prop] = t; + if (prop === '--') return declare(e, t); if (prop === '--exact-animation-trigger') { if (v === 'none') e.setAttribute('data-exact-animation-trigger', 'none'); else e.removeAttribute('data-exact-animation-trigger'); diff --git a/host/web/src/css.rs b/host/web/src/css.rs index 6bdb5813f..a5a896070 100644 --- a/host/web/src/css.rs +++ b/host/web/src/css.rs @@ -13,6 +13,7 @@ pub mod text_style; pub use decorations::{atom_faces, decoration_styles}; pub use fonts::{font_alias, font_family_names, runtime_font_family}; +use exact_kernel::style::safe_area_properties::SafeAreaProperties; use exact_kernel::style::ColorValue; use exact_kernel::{Color, Dimension, Display, Overflow, RowValue, StyleId, StyleProps}; use exact_motion::{Easing, Property, TimingFunction, Transition, TransitionProperty, Transitions}; @@ -304,6 +305,15 @@ fn css_text_in( ); } } + // @ref LLP 1123 D5 — runtime custom properties are the browser's own + (StyleId::SafeAreaProperties, RowValue::SafeAreaProperties(c)) => { + for (name, value) in c.iter() { + SafeAreaProperties::write_name(name, &mut out); + out.push(':'); + dimension(&mut out, value.clone()); + out.push(';'); + } + } (StyleId::LayoutTransition, RowValue::Transitions(t)) => { if let Some(text) = layout_transition_css(t) { push_text!(&mut out, "--exact-layout-transition:{};", text); @@ -802,6 +812,7 @@ fn lowered(id: StyleId, value: &RowValue<'_>) -> bool { | RowValue::AnimationTimeline(_) | RowValue::AnimationRange(_) | RowValue::TimelineScope(_) + | RowValue::SafeAreaProperties(_) | RowValue::TimelineName(_) => false, _ => true, } @@ -990,6 +1001,7 @@ fn declared(out: &mut String, id: StyleId, value: &RowValue<'_>) { RowValue::AnimationTimeline(t) => out.push_str(&t.css()), RowValue::AnimationRange(r) => out.push_str(&r.css()), RowValue::TimelineScope(s) => out.push_str(&s.css()), + RowValue::SafeAreaProperties(c) => out.push_str(&c.css()), RowValue::TimelineName(n) => out.push_str(&n.css()), RowValue::ViewTimelineInset(i) => out.push_str(&i.css()), RowValue::Paint(p) => out.push_str(&p.css()), diff --git a/host/web/src/css/clears.rs b/host/web/src/css/clears.rs index 169c5a8a0..8e818fe95 100644 --- a/host/web/src/css/clears.rs +++ b/host/web/src/css/clears.rs @@ -7,12 +7,11 @@ pub(super) fn push(out: &mut String, id: StyleId, press: bool) -> bool { use StyleId::*; match id { TintColor | ExitAnimation | DragTimeline | AnimationTimeline | AnimationRange - | TimelineScope | LayoutTransition | PressScale | PressHaptic | ControlSize - | ControlCornerStyle | Fit | LineClamp | RotateAxis | TranslateZ | TranslatePercent - | SymbolRendering | TintAdjustment | SymbolPalette | SymbolValue | SymbolEffect - | ContentTransition | ScrollEdgeEffect | HoverEffect | SmartInvert | AnimationTrigger => { - return false - } + | TimelineScope | SafeAreaProperties | LayoutTransition | PressScale | PressHaptic + | ControlSize | ControlCornerStyle | Fit | LineClamp | RotateAxis | TranslateZ + | TranslatePercent | SymbolRendering | TintAdjustment | SymbolPalette | SymbolValue + | SymbolEffect | ContentTransition | ScrollEdgeEffect | HoverEffect | SmartInvert + | AnimationTrigger => return false, // The name and the drag code's copy of it (css.rs). ScrollTimelineName => { out.push_str("scroll-timeline-name:unset;--exact-scroll-timeline:unset;") diff --git a/host/web/src/element_tests.rs b/host/web/src/element_tests.rs index 0cbffcee2..dce535257 100644 --- a/host/web/src/element_tests.rs +++ b/host/web/src/element_tests.rs @@ -632,6 +632,46 @@ fn a_layout_region_is_the_browsers_safe_area() { } } +/// A node's custom properties (LLP 1123 D5) are the browser's own: each +/// declaration's length, and a length reads one through `var()`, which the +/// browser substitutes. +#[test] +fn custom_properties_reach_the_browser_as_declarations() { + use exact_kernel::{StyleId, StyleValue}; + let mut style = StyleProps::default(); + let declared = "--gap: 8px; --pad: calc(var(--gap) * 2)"; + style + .set_dynamic( + StyleId::SafeAreaProperties, + &StyleValue::Text(declared.into()), + ) + .unwrap(); + style + .set_dynamic( + StyleId::PaddingLeft, + &StyleValue::Text("var(--pad, 4px)".into()), + ) + .unwrap(); + // A fallback stands alone where the row's value does, so a sum keeps its `calc()` + style + .set_dynamic( + StyleId::MarginTop, + &StyleValue::Text("var(--missing, calc(10% + 2px))".into()), + ) + .unwrap(); + let (out, _) = crate::css::css_text(&style, &[]); + assert!( + out.contains("--gap:8px;--pad:calc(2 * var(--gap));"), + "{out}" + ); + assert!(out.contains("padding-left:var(--pad, 4px)"), "{out}"); + // As host/web/tests/local-insets.test.mjs has the browser read it + assert!( + out.contains("margin-top:var(--missing, calc(10% + 2px))"), + "{out}" + ); +} + /// A content owner's local inset (LLP 1123 D9) reaches the browser as the /// registered custom property it reads, alone or in a calculation. #[test] diff --git a/host/web/tests/local-insets.test.mjs b/host/web/tests/local-insets.test.mjs index 0bd14255b..2326db133 100644 --- a/host/web/tests/local-insets.test.mjs +++ b/host/web/tests/local-insets.test.mjs @@ -1,7 +1,9 @@ // @ref LLP 1123 D9 — `var(--exact-safe-area-inset-*)` on the web: registered // lengths that inherit, the document's `env()` at the root, and the neutral // look's sheet's own (none at its top; none at all as a wide window's card). -// Chrome's safe-area override stands in for a phone's insets. +// Chrome's safe-area override stands in for a phone's insets. LLP 1123 D5: +// an author's custom properties, as css.rs writes them, read as the kernel +// reads them. import { afterAll, beforeAll, expect, test } from 'bun:test'; import { readFileSync } from 'node:fs'; import { resolve } from 'node:path'; @@ -14,13 +16,28 @@ const style = withLook(readFileSync(resolve(WEB, 'index.html'), 'utf8')).match(/ const probe = 'width:10px;height:var(--exact-safe-area-inset-top);padding-bottom:max(4px, var(--exact-safe-area-inset-bottom));margin-top:calc(-1 * var(--exact-safe-area-inset-top))'; let server; beforeAll(() => { - server = Bun.serve({ port: 0, hostname: '127.0.0.1', fetch() { + server = Bun.serve({ port: 0, hostname: '127.0.0.1', fetch(request) { + // The JS target's declaration updater, as a bound row runs it + if (new URL(request.url).pathname === '/declarations.js') { + return new Response(Bun.file(resolve(WEB, '../web-js/declarations.js')), { headers: { 'content-type': 'text/javascript' } }); + } return new Response(`
-
`, { headers: { 'content-type': 'text/html' } }); +
+
+
+
+
+ + `, { headers: { 'content-type': 'text/html' } }); } }); }); afterAll(() => server?.stop(true)); @@ -33,16 +50,26 @@ test('a box reads its container\'s insets, a sheet\'s its own, and an author\'s const cdp = await page.context().newCDPSession(page); await cdp.send('Emulation.setSafeAreaInsetsOverride', { insets: { top: 47, bottom: 34, left: 0, right: 0 } }); await page.goto(server.url.href); - return page.evaluate(() => Object.fromEntries(['page', 'sheet', 'own'].map((id) => { + await page.waitForSelector('body[data-ready]'); + return page.evaluate(() => Object.fromEntries([ + ...['page', 'sheet', 'own'].map((id) => [id, ['height', 'paddingBottom', 'marginTop']]), + ['fallback', ['marginTop', 'height']], + ['capture', ['height', 'width']], + ['bound-reader', ['height', 'width']], + ].map(([id, props]) => { const s = getComputedStyle(document.getElementById(id)); - return [id, [s.height, s.paddingBottom, s.marginTop].map(parseFloat)]; + return [id, props.map(p => parseFloat(s[p]))]; }))); }; + // An author's custom properties (LLP 1123 D5): a fallback stands alone, 10% of the 200px block plus 2px; a + // capture holds the declaring box's inset, not the nearer override's 30; a percentage is the reader's own; the JS + // target's updater writes a bound row, a comment and an escaped name among it + const custom = { fallback: [22, 8], capture: [47, 50], 'bound-reader': [12, 9] }; // Narrow: the page reads env(); the sheet starts below the status bar and reaches the bottom. // An author's own value, as css.rs writes it, is what its subtree reads. - expect(await read(390)).toEqual({ page: [47, 34, -47], sheet: [0, 34, 0], own: [42, 34, -42] }); + expect(await read(390)).toEqual({ page: [47, 34, -47], sheet: [0, 34, 0], own: [42, 34, -42], ...custom }); // Wide: the sheet is a card clear of every edge. - expect(await read(1000)).toEqual({ page: [47, 34, -47], sheet: [0, 4, 0], own: [42, 34, -42] }); + expect(await read(1000)).toEqual({ page: [47, 34, -47], sheet: [0, 4, 0], own: [42, 34, -42], ...custom }); } finally { await browser.close(); } diff --git a/kernel/build.rs b/kernel/build.rs index 07f9507f2..8c057eeee 100644 --- a/kernel/build.rs +++ b/kernel/build.rs @@ -638,7 +638,7 @@ fn generate(schema: &Schema, digest: u64) -> String { // ---- StyleId / StyleCodec -------------------------------------------- writeln!(w, "/// Wire codec of a style row.").unwrap(); writeln!(w, "#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]").unwrap(); - writeln!(w, "pub enum StyleCodec {{ Dimension, LineHeight, F32, U8, U16, U32, I32, AutoI32, ColorValue, KeywordColor, Vec2, Tracks, Placement, Transitions, Animations, ClipPath, ShapeOutside, AspectRatio, Paint, DashArray, Transform, TransformOrigin, PaintOrder, Marker, Filter, BackgroundImage, BackdropFilter, BoxShadow, TextShadow, FontVariations, FontFeatures, MaskImage, CornerShape, RotateAxis, SymbolPalette, DragTimeline, AnimationTimeline, AnimationRange, TimelineScope, TimelineName, ViewTimelineInset, PositionTryFallbacks, Enum }}").unwrap(); + writeln!(w, "pub enum StyleCodec {{ Dimension, LineHeight, F32, U8, U16, U32, I32, AutoI32, ColorValue, KeywordColor, Vec2, Tracks, Placement, Transitions, Animations, ClipPath, ShapeOutside, AspectRatio, Paint, DashArray, Transform, TransformOrigin, PaintOrder, Marker, Filter, BackgroundImage, BackdropFilter, BoxShadow, TextShadow, FontVariations, FontFeatures, MaskImage, CornerShape, RotateAxis, SymbolPalette, DragTimeline, AnimationTimeline, AnimationRange, TimelineScope, SafeAreaProperties, TimelineName, ViewTimelineInset, PositionTryFallbacks, Enum }}").unwrap(); writeln!(w, "/// One style row; the discriminant is the mask bit.").unwrap(); writeln!(w, "#[repr(u8)]").unwrap(); writeln!( diff --git a/kernel/build/codec.rs b/kernel/build/codec.rs index 872cb9ce9..f0aa94619 100644 --- a/kernel/build/codec.rs +++ b/kernel/build/codec.rs @@ -262,6 +262,12 @@ fn parse_codec(s: &str) -> Codec { variant: "TimelineScope", error: "BadTimelineScope", }, + // @ref LLP 1123 D5 — runtime custom properties, CSS Variables 1. + "safe-area-properties" => Codec::CssValue { + path: "crate::style::safe_area_properties::SafeAreaProperties", + variant: "SafeAreaProperties", + error: "BadSafeAreaProperties", + }, other => match other.strip_prefix("enum:") { Some(name) => Codec::Enum(name.to_string()), None => panic!("schema: unknown codec `{other}`"), diff --git a/kernel/src/arena.rs b/kernel/src/arena.rs index 386562afd..886d1e4b8 100644 --- a/kernel/src/arena.rs +++ b/kernel/src/arena.rs @@ -16,6 +16,7 @@ pub(crate) mod button; pub(crate) mod control_text; pub(crate) mod defaults; mod inline_image; +mod styles; pub mod text_style; use taffy::NodeId; @@ -64,6 +65,8 @@ pub struct NodeArena { // @ref LLP 1043.000 §3 D4 — no per-node vector or allocation. pub(crate) flow: IdMap, pub(crate) exclusion_slots: SlotSet, + /// The slots that declare custom properties (LLP 1123 D5). + pub(crate) declaring_slots: SlotSet, /// @ref LLP 1093 D7 — multi-column containers and their last cuts. pub(crate) frag: crate::fragment::FragState, /// Relative rows and the slots whose inputs changed (LLP 1069.000 D3). @@ -184,6 +187,7 @@ impl Clone for NodeArena { frames: self.frames.clone(), flow: self.flow.clone(), exclusion_slots: self.exclusion_slots.clone(), + declaring_slots: self.declaring_slots.clone(), frag: self.frag.clone(), relative: self.relative.clone(), symbols_owed: self.symbols_owed.clone(), @@ -276,6 +280,7 @@ impl NodeArena { self.fit_scales.clear(); self.flow.clear(); self.exclusion_slots.clear(); + self.declaring_slots.clear(); self.frag = Default::default(); self.relative = Default::default(); self.symbols_owed.clear(); @@ -926,6 +931,7 @@ impl NodeArena { self.field_content.remove(&slot); self.mark_reports.remove(&slot); self.exclusion_slots.remove(slot); + self.declaring_slots.remove(slot); self.frag.forget(slot); self.relative.forget(slot); self.symbols_owed.remove(slot); @@ -1038,50 +1044,6 @@ impl NodeArena { } } - /// A test's write in place, copied first when shared. Production writes - /// go through [`set_style`](Self::set_style), which keeps an unset row - /// at its initial value, as sharing assumes. - #[cfg(test)] - pub(crate) fn style_mut(&mut self, slot: u32) -> &mut StyleProps { - Rc::make_mut(&mut self.styles[slot as usize]) - } - - /// Replace the slot's style, sharing an equal one's allocation. - pub(crate) fn set_style(&mut self, slot: u32, style: StyleProps) { - let style = self.shared.intern(style); - self.set_shared_style(slot, style); - } - - /// Patch a slot without copying a style another node already holds. - pub(crate) fn patch_style(&mut self, slot: u32, patch: &StyleProps) { - let style = self.shared.patch(&self.styles[slot as usize], patch); - self.set_shared_style(slot, style); - } - - /// Clear rows without copying a style another node already holds. - pub(crate) fn clear_style(&mut self, slot: u32, mask: crate::StyleMask, written: bool) { - let style = self - .shared - .clear(&self.styles[slot as usize], mask, written); - self.set_shared_style(slot, style); - } - - fn set_shared_style(&mut self, slot: u32, style: Rc) { - self.relative.update(slot, !style.relative.is_empty()); - if crate::fragment::is_multicol(&style) { - self.frag.containers.insert(slot); - } else { - self.frag.containers.remove(slot); - } - self.styles[slot as usize] = style; - self.refresh_sticky(slot); - } - - /// Distinct styles the arena holds for its nodes, beyond the initial one. - pub fn shared_style_count(&self) -> usize { - self.shared.len() - } - /// Set a prop; the previous value. pub(crate) fn set_prop( &mut self, diff --git a/kernel/src/arena/styles.rs b/kernel/src/arena/styles.rs new file mode 100644 index 000000000..d2d5f3bf1 --- /dev/null +++ b/kernel/src/arena/styles.rs @@ -0,0 +1,55 @@ +//! A node's style, shared with every node that holds an equal one, and the +//! sets the arena keeps of what styles hold. +use super::*; + +impl NodeArena { + /// A test's write in place, copied first when shared. Production writes + /// go through [`set_style`](Self::set_style), which keeps an unset row + /// at its initial value, as sharing assumes. + #[cfg(test)] + pub(crate) fn style_mut(&mut self, slot: u32) -> &mut StyleProps { + Rc::make_mut(&mut self.styles[slot as usize]) + } + + /// Replace the slot's style, sharing an equal one's allocation. + pub(crate) fn set_style(&mut self, slot: u32, style: StyleProps) { + let style = self.shared.intern(style); + self.set_shared_style(slot, style); + } + + /// Patch a slot without copying a style another node already holds. + pub(crate) fn patch_style(&mut self, slot: u32, patch: &StyleProps) { + let style = self.shared.patch(&self.styles[slot as usize], patch); + self.set_shared_style(slot, style); + } + + /// Clear rows without copying a style another node already holds. + pub(crate) fn clear_style(&mut self, slot: u32, mask: crate::StyleMask, written: bool) { + let style = self + .shared + .clear(&self.styles[slot as usize], mask, written); + self.set_shared_style(slot, style); + } + + fn set_shared_style(&mut self, slot: u32, style: Rc) { + self.relative.update(slot, !style.relative.is_empty()); + if crate::fragment::is_multicol(&style) { + self.frag.containers.insert(slot); + } else { + self.frag.containers.remove(slot); + } + // With no declaration and no owner's local insets, a move changes no length + if style.mask.has(crate::StyleId::SafeAreaProperties) { + self.declaring_slots.insert(slot); + } else { + self.declaring_slots.remove(slot); + } + self.styles[slot as usize] = style; + self.refresh_sticky(slot); + } + + /// Distinct styles the arena holds for its nodes, beyond the initial one. + pub fn shared_style_count(&self) -> usize { + self.shared.len() + } +} diff --git a/kernel/src/error.rs b/kernel/src/error.rs index 34baf7202..2158eab1b 100644 --- a/kernel/src/error.rs +++ b/kernel/src/error.rs @@ -81,6 +81,8 @@ pub enum DecodeError { BadAnimationRange, /// Invalid `timeline-scope` (LLP 1057.003 D4). BadTimelineScope, + /// Invalid runtime custom properties (LLP 1123 D5). + BadSafeAreaProperties, /// Invalid `scroll-timeline-name` or `view-timeline-name` (LLP 1057.003 D5). BadTimelineName, /// Invalid `view-timeline-inset` (LLP 1057.003 D5). @@ -594,6 +596,10 @@ pub enum StyleValueError { BadTimelineScope { style: StyleId, }, + /// Not `--name: ` declarations of authors' names. + BadSafeAreaProperties { + style: StyleId, + }, /// Not `none` or one ``. BadTimelineName { style: StyleId, diff --git a/kernel/src/kernel/owner.rs b/kernel/src/kernel/owner.rs index 498ca200d..b1927dba8 100644 --- a/kernel/src/kernel/owner.rs +++ b/kernel/src/kernel/owner.rs @@ -23,11 +23,15 @@ use super::Kernel; use crate::arena::NodeArena; use crate::error::{KernelError, LayoutError}; -use crate::generated::{StyleId, StyleProps}; -use crate::id::{NodeFlags, ViewId}; +use crate::generated::{StyleId, StyleMask, StyleProps}; +use crate::id::ViewId; use crate::layout::LayoutMirror; +use crate::style::calc::{self, simplify, Node}; +use crate::style::safe_area_properties::{Resolved, SafeAreaProperties}; use crate::style::{Dimension, Edge, Env, RowValue}; use std::borrow::Cow; +use std::collections::BTreeMap; +use std::sync::Arc; /// The rows an author overrides the four insets with, top right bottom left. pub(crate) const OVERRIDES: [StyleId; 4] = [ @@ -37,32 +41,390 @@ pub(crate) const OVERRIDES: [StyleId; 4] = [ StyleId::LocalInsetLeft, ]; -/// Whether a style holds a length that reads a local inset, its own -/// overrides aside (they read their parent's, [`local_at`]). -pub(crate) fn reads_local(style: &StyleProps) -> bool { - style.mask.iter().any(|id| { - !OVERRIDES.contains(&id) - && matches!(style.get(id), RowValue::Dimension(Dimension::Compare(c)) if c.reads_local()) - }) +/// Whether a style's lengths read what only the node's own environment +/// has: a local inset or an author's custom property (LLP 1123 D5, D9). +pub(crate) fn reads_node(style: &StyleProps) -> bool { + !node_rows(style).is_empty() +} + +/// The rows of `style` whose lengths read a local inset, its own overrides +/// aside (they read their parent's, [`local_at`]), or an author's custom +/// property. +fn node_rows(style: &StyleProps) -> StyleMask { + rows_where(style, |c| c.reads_local() || c.reads_custom()) +} + +/// Whether a style holds a length that reads an author's custom property. +pub(crate) fn reads_properties(style: &StyleProps) -> bool { + !rows_where(style, calc::Comparison::reads_custom).is_empty() +} + +fn rows_where(style: &StyleProps, reads: impl Fn(&calc::Comparison) -> bool) -> StyleMask { + let mut rows = StyleMask::EMPTY; + for id in style.mask.iter().filter(|id| !OVERRIDES.contains(id)) { + if matches!(style.get(id), RowValue::Dimension(Dimension::Compare(c)) if reads(&c)) { + rows.set(id); + } + } + rows +} + +/// Whether an input of `slot`'s lengths moved with a local inset: one reads +/// it, or a custom property they read reaches one. +fn reads_insets(arena: &NodeArena, slot: u32, style: &StyleProps) -> bool { + !rows_where(style, calc::Comparison::reads_local).is_empty() + || reads_properties(style) && properties_read_local(arena, slot, style) +} + +/// Derive `slot`'s lengths again after their local insets or custom +/// properties changed, through what a change of the rows that read them +/// does (`txn::style_changed`): a paragraph is measured again where one is +/// a text row, an inline image's or an inline edge, whatever the value. An +/// engine style that comes out the same lays the box out no more +/// (`TaffyMirror::write_style`); `dirty` lays it out regardless, as an inset +/// change does. +pub(crate) fn rederive( + arena: &mut NodeArena, + layout: &mut dyn LayoutMirror, + slot: u32, + dirty: bool, + receipt: &mut crate::CommitReceipt, +) { + let rows = node_rows(&arena.effective_style(slot)); + crate::txn::style_changed(arena, layout, slot, rows, receipt); + if let Some(node) = arena.taffy(slot).filter(|_| dirty) { + layout.mark_dirty(node); + } +} + +/// `slot`'s custom properties changed from `old` (LLP 1123 D5): each reader +/// of a name whose value changed is derived again, in `slot`'s subtree, +/// below the nodes that declare that name again, and through the +/// declarations that read it. +pub(crate) fn declarations_changed( + arena: &mut NodeArena, + layout: &mut dyn LayoutMirror, + slot: u32, + old: &SafeAreaProperties, + touched: &mut Vec, + receipt: &mut crate::CommitReceipt, +) { + let new = own_declarations(arena, slot); + let mut changed: Vec> = Vec::new(); + for (name, _) in old.iter().chain(new.iter()) { + if old.get(name) != new.get(name) && !changed.iter().any(|n| &**n == name) { + changed.push(name.into()); + } + } + let mut stack = vec![(slot, reaching(&new, &changed, true))]; + while let Some((s, names)) = stack.pop() { + if names.is_empty() { + continue; + } + let style = arena.effective_style(s); + if reads_properties(&style) && read_names(&style).iter().any(|n| names.contains(n)) { + drop(style); + rederive(arena, layout, s, false, receipt); + touched.push(arena.key(s)); + } + for &c in arena.children(s) { + stack.push((c, reaching(&own_declarations(arena, c), &names, false))); + } + } +} + +/// The names whose values change at a node that declares `own`, when those +/// in `above` changed: the changed ones it does not declare again, and each +/// it declares that reads a changed one. `at_root`: `own` is what changed, +/// so `above` names its own too. +fn reaching(own: &SafeAreaProperties, above: &[Arc], at_root: bool) -> Vec> { + let mut out: Vec> = match at_root { + true => above.to_vec(), + false => above + .iter() + .filter(|n| own.get(n).is_none()) + .cloned() + .collect(), + }; + // What each declaration reads, collected once + let reads: Vec<(&str, Vec>)> = own + .iter() + .map(|(name, value)| { + let mut names = Vec::new(); + if let Some(t) = calc::tree_of(value) { + t.names(&mut names); + } + (name, names) + }) + .collect(); + loop { + let mut added = false; + for (name, names) in &reads { + if out.iter().any(|n| &**n == *name) { + continue; + } + // A name it declares is its own; any other, its parent's + let moved = names.iter().any(|m| match own.get(m) { + Some(_) => out.contains(m), + None => above.contains(m), + }); + if moved { + out.push((*name).into()); + added = true; + } + } + if !added { + return out; + } + } +} + +/// `slot`'s custom properties before a change of `changed`, where it +/// changes them. +pub(crate) fn declared_before( + arena: &NodeArena, + slot: u32, + changed: StyleMask, +) -> Option { + changed + .has(StyleId::SafeAreaProperties) + .then(|| own_declarations(arena, slot)) +} + +/// The custom properties `slot` declares itself. +pub(crate) fn own_declarations(arena: &NodeArena, slot: u32) -> SafeAreaProperties { + let style = arena.style(slot); + match style.get(StyleId::SafeAreaProperties) { + RowValue::SafeAreaProperties(own) if style.mask.has(StyleId::SafeAreaProperties) => { + own.clone() + } + _ => SafeAreaProperties::default(), + } } /// The environment `slot`'s lengths, `style`, resolve against: the /// arena's, unless they read a local inset ([`env_at`]). pub(crate) fn env_for<'a>(arena: &'a NodeArena, slot: u32, style: &StyleProps) -> Cow<'a, Env> { - match reads_local(style) { + match reads_node(style) { true => env_at(arena, slot), false => Cow::Borrowed(arena.env()), } } /// The environment `slot`'s lengths resolve against: the arena's, with the -/// local insets `slot` inherits ([`local_at`]). +/// local insets `slot` inherits ([`local_at`]) and the custom properties its +/// lengths read ([`properties_at`]). pub(crate) fn env_at(arena: &NodeArena, slot: u32) -> Cow<'_, Env> { let mut env = arena.env().clone(); env.local = Some(local_at(arena, slot)); + env.properties = Some(properties_at(arena, slot, &arena.effective_style(slot))); Cow::Owned(env) } +/// The values of the custom properties `style`'s lengths read at `slot` +/// (LLP 1123 D5), each resolved where it is declared. +pub(crate) fn properties_at(arena: &NodeArena, slot: u32, style: &StyleProps) -> Resolved { + let names = read_names(style); + if names.is_empty() { + return Resolved::default(); + } + // Every declaration first, so a walk past the bound invalidates every + // value, whatever order the rows read them in + let mut resolver = Resolver::new(arena); + let keys: Vec<_> = names.iter().map(|n| resolver.reach(slot, n)).collect(); + if resolver.exhausted { + return Resolved::default(); + } + let values = names + .into_iter() + .zip(keys) + .filter_map(|(name, key)| Some((name, resolver.value(&key?)?))) + .collect(); + Resolved(values) +} + +/// Whether a custom property `style`'s lengths read at `slot` reaches a +/// local inset, through any declaration it depends on. +pub(crate) fn properties_read_local(arena: &NodeArena, slot: u32, style: &StyleProps) -> bool { + let mut resolver = Resolver::new(arena); + for name in read_names(style) { + resolver.reach(slot, &name); + } + let local = |n: &Node| matches!(n, Node::Env(calc::EnvTerm::Local(_))); + resolver.exhausted + || resolver + .found + .values() + .any(|d| d.tree.as_ref().is_some_and(|t| t.any(&local))) +} + +/// The custom properties `style`'s lengths read, fallbacks included. +fn read_names(style: &StyleProps) -> Vec> { + let mut names = Vec::new(); + for id in style.mask.iter() { + if let RowValue::Dimension(Dimension::Compare(c)) = style.get(id) { + c.properties(&mut names); + } + } + names +} + +/// The most declarations one node's lengths reach: past it every value is +/// invalid, as CSS Variables 1 §3.3 has an over-long expansion. +const MAX_DECLARATIONS: usize = 1024; + +/// A declaration: the node that declares a name, and the name. +type Key = (u32, Arc); + +/// Resolves custom properties where they are declared (CSS Variables 1 +/// §2.3). It first finds every declaration a reader depends on, fallbacks +/// included, and the cycles among them (§2.3, by Tarjan's algorithm), whose +/// every member is invalid; then it substitutes the rest, each `var()` in a +/// declaration reading the declaring node's own values and a capture its +/// local inset. +struct Resolver<'a> { + arena: &'a NodeArena, + found: BTreeMap, + /// Tarjan's stack of declarations whose component is open. + stack: Vec, + /// Whether the walk passed [`MAX_DECLARATIONS`]. + exhausted: bool, +} + +struct Declared { + /// Its value's tree; `None` where it holds none. + tree: Option, + /// Tarjan's visit index and low link. + index: usize, + low: usize, + open: bool, + cyclic: bool, + /// Its substituted value, once known; `Some(None)` where it is invalid. + value: Option>, +} + +impl<'a> Resolver<'a> { + fn new(arena: &'a NodeArena) -> Self { + Resolver { + arena, + found: BTreeMap::new(), + stack: Vec::new(), + exhausted: false, + } + } + + /// `name`'s declaration as `from` has it, the nearest at or above it, + /// visited with all it depends on; `None` where nothing declares it. + fn reach(&mut self, from: u32, name: &Arc) -> Option { + let (slot, declared) = self.declaring(from, name)?; + let key = (slot, name.clone()); + if !self.found.contains_key(&key) { + self.visit(key.clone(), &declared); + } + Some(key) + } + + fn declaring(&self, from: u32, name: &str) -> Option<(u32, Dimension)> { + let mut at = Some(from); + while let Some(slot) = at { + if let RowValue::SafeAreaProperties(own) = + self.arena.style(slot).get(StyleId::SafeAreaProperties) + { + if let Some(d) = own.get(name) { + return Some((slot, d.clone())); + } + } + at = self.arena.parent(slot); + } + None + } + + fn visit(&mut self, key: Key, declared: &Dimension) { + let index = self.found.len(); + if index >= MAX_DECLARATIONS { + self.exhausted = true; + } + let tree = calc::tree_of(declared); + let mut names = Vec::new(); + if let Some(t) = &tree { + t.names(&mut names); + } + self.found.insert( + key.clone(), + Declared { + tree, + index, + low: index, + open: true, + cyclic: false, + value: None, + }, + ); + self.stack.push(key.clone()); + let mut low = index; + let mut looped = false; + for name in names { + if self.exhausted { + break; + } + let Some((slot, d)) = self.declaring(key.0, &name) else { + continue; + }; + let dep = (slot, name); + looped |= dep == key; + match self.found.get(&dep) { + None => { + self.visit(dep.clone(), &d); + low = low.min(self.found[&dep].low); + } + Some(seen) if seen.open => low = low.min(seen.index), + Some(_) => {} + } + } + self.found.get_mut(&key).expect("visited").low = low; + if low == index { + let at = self + .stack + .iter() + .rposition(|k| *k == key) + .expect("on the stack"); + let component = self.stack.split_off(at); + let cyclic = component.len() > 1 || looped; + for k in component { + let d = self.found.get_mut(&k).expect("visited"); + d.open = false; + d.cyclic = cyclic; + } + } + } + + /// A visited declaration's value, substituted where it is declared; + /// `None` where it is invalid: in a cycle, reading an undefined + /// environment value, or too long. + fn value(&mut self, key: &Key) -> Option { + if self.exhausted { + return None; + } + let d = self.found.get(key)?; + if let Some(value) = &d.value { + return value.clone(); + } + let tree = d.tree.clone().filter(|_| !d.cyclic); + let local = local_at(self.arena, key.0); + let value = tree + .and_then(|tree| { + calc::substitute(&tree, &|edge| local[edge as usize], &mut |name| { + let dep = self.reach(key.0, name)?; + self.value(&dep) + }) + }) + .map(simplify::simplify) + .filter(|v| !calc::undefined_in(v, self.arena.env()) && calc::within_expansion(v)); + self.found.get_mut(key).expect("visited").value = Some(value.clone()); + value + } +} + impl NodeArena { /// The environment a box's lengths resolve against (LLP 1123 D9): the /// document's, with the box's own local insets where its style reads @@ -145,6 +507,8 @@ fn resolve( } let mut env = env.clone(); env.local = Some(local); + // An override reads no custom property, so a `var()` of one takes its fallback + env.properties = Some(Resolved::default()); d.at_basis(&env, 0.0) } _ => base[i], @@ -154,23 +518,24 @@ fn resolve( } /// A box moved to another parent, created ones included, may be in another -/// owner now: what in its subtree reads a local inset is derived again. -/// Whether anything was. +/// owner, and below other declarations, now: what in its subtree reads a +/// local inset or a custom property is derived again. Whether anything was. pub(crate) fn moved(arena: &mut NodeArena, layout: &mut dyn LayoutMirror, slot: u32) -> bool { - if !arena.blocks.has_locals() { + let locals = arena.blocks.has_locals(); + if !locals && arena.declaring_slots.is_empty() { return false; } + let mut receipt = crate::CommitReceipt::default(); let mut any = false; for s in arena.subtree(slot) { - if !reads_local(&arena.effective_style(s)) { - continue; + let style = arena.effective_style(s); + let reads = reads_properties(&style) + || locals && !rows_where(&style, calc::Comparison::reads_local).is_empty(); + drop(style); + if reads { + rederive(arena, layout, s, false, &mut receipt); + any = true; } - if let Some(node) = arena.taffy(s) { - layout.restyle(arena, s, node); - layout.mark_dirty(node); - } - arena.flags_mut(s).insert(NodeFlags::STYLE_DIRTY); - any = true; } any } @@ -202,9 +567,8 @@ impl Kernel { return Ok(false); } self.arena.blocks.set_local(slot, insets); - let readers: Vec = (self.arena.iter_live()) - .filter(|&s| s == slot || self.arena.is_ancestor(slot, s)) - .filter(|&s| reads_local(&self.arena.effective_style(s))) + let readers: Vec = (self.arena.subtree(slot).into_iter()) + .filter(|&s| reads_insets(&self.arena, s, &self.arena.effective_style(s))) .collect(); self.restyle_readers(&readers); Ok(!readers.is_empty()) @@ -241,6 +605,7 @@ impl Kernel { // A node gone (a leaving view's last style) reads the root's None => Env { local: Some(Edge::ALL.map(|e| self.arena.env().root_inset(e))), + properties: Some(Default::default()), ..self.env() }, } @@ -253,13 +618,11 @@ impl Kernel { if let Some(r) = &mut self.region { r.invalidate(); } + let mut unmirrored = crate::layout::Unmirrored; + let layout = self.layout.as_deref_mut().unwrap_or(&mut unmirrored); + let mut receipt = crate::CommitReceipt::default(); for &slot in readers { - if let (Some(node), Some(layout)) = (self.arena.taffy(slot), self.layout.as_deref_mut()) - { - layout.restyle(&self.arena, slot, node); - layout.mark_dirty(node); - } - self.arena.flags_mut(slot).insert(NodeFlags::STYLE_DIRTY); + rederive(&mut self.arena, layout, slot, true, &mut receipt); } // A replayed row checks its styles, not what they now resolve to if let Some(tree) = self.layout.as_deref_mut().and_then(|l| l.tree()) { @@ -271,3 +634,7 @@ impl Kernel { #[cfg(test)] #[path = "owner_tests.rs"] mod tests; + +#[cfg(test)] +#[path = "property_tests.rs"] +mod property_tests; diff --git a/kernel/src/kernel/owner_tests.rs b/kernel/src/kernel/owner_tests.rs index ffc585a0e..3d1866efe 100644 --- a/kernel/src/kernel/owner_tests.rs +++ b/kernel/src/kernel/owner_tests.rs @@ -5,7 +5,7 @@ use crate::id::Offer; use crate::wire::Op; use crate::{HostCover, NodeType, StyleId, StyleValue}; -fn style(id: ViewId, rows: &[(StyleId, &str)]) -> Op { +pub(super) fn style(id: ViewId, rows: &[(StyleId, &str)]) -> Op { let mut patch = StyleProps::default(); for (row, value) in rows { let value = match value.parse::() { @@ -20,7 +20,7 @@ fn style(id: ViewId, rows: &[(StyleId, &str)]) -> Op { } } -fn create(ids: impl IntoIterator) -> Vec { +pub(super) fn create(ids: impl IntoIterator) -> Vec { (ids.into_iter()) .map(|id| Op::CreateView { id, @@ -29,7 +29,7 @@ fn create(ids: impl IntoIterator) -> Vec { .collect() } -fn children(id: ViewId, children: &[ViewId]) -> Op { +pub(super) fn children(id: ViewId, children: &[ViewId]) -> Op { Op::SetChildren { id, children: children.to_vec(), @@ -217,12 +217,16 @@ fn the_term_parses_writes_back_and_crosses_the_wire() { "var(--exact-safe-area-inset-top, 4px)", "var(--exact-accent)", "var(--exact-safe-area-inset-middle)", - "calc(var(--Exact-safe-area-inset-top) + 1px)", ] { let mut props = StyleProps::default(); let text = StyleValue::Text(refused.into()); assert!(props.set_dynamic(TOP, &text).is_err(), "{refused}"); } + // Custom property names are case-sensitive: this is an author's, which a + // node may declare (LLP 1123 D5) + let mut props = StyleProps::default(); + let text = StyleValue::Text("calc(var(--Exact-safe-area-inset-top) + 1px)".into()); + assert!(props.set_dynamic(TOP, &text).is_ok()); } #[test] diff --git a/kernel/src/kernel/property_tests.rs b/kernel/src/kernel/property_tests.rs new file mode 100644 index 000000000..06fed91b5 --- /dev/null +++ b/kernel/src/kernel/property_tests.rs @@ -0,0 +1,381 @@ +//! Custom properties in a tree (LLP 1123 D5): declared on a node, read in +//! its subtree's lengths, captured from an owner's inset. +use super::tests::{children, create, style}; +use super::*; +use crate::id::Offer; +use crate::wire::Op; +use crate::{NodeType, StyleId, StyleMask}; + +const TOP: StyleId = StyleId::PaddingTop; +const PROPERTIES: StyleId = StyleId::SafeAreaProperties; + +/// 1 the root, 2 a box, 3 a box in 2 that pads its top by `pad`, 4 a box in 3. +fn tree(declared: &str, pad: &str) -> Kernel { + let mut k = Kernel::with_monospace(); + let mut ops = create(1..=4); + ops.push(style( + 1, + &[(StyleId::Height, "844"), (PROPERTIES, declared)], + )); + ops.push(style(3, &[(TOP, pad)])); + ops.push(style(4, &[(StyleId::Height, "10")])); + ops.extend([children(1, &[2]), children(2, &[3]), children(3, &[4])]); + ops.push(Op::AttachRoot { id: 1 }); + k.apply(0, 1, &ops).unwrap(); + k +} + +fn y(k: &mut Kernel, id: ViewId) -> f32 { + k.compute_layout(1, Offer::definite(390.0, 844.0)).unwrap(); + k.node(id).unwrap().frame.y +} + +#[test] +fn a_descendant_pads_by_a_property_its_ancestor_declares() { + let mut k = tree("--gap: 8px; --pad: calc(var(--gap) * 2)", "var(--pad)"); + assert_eq!(y(&mut k, 4), 16.0); + // A change to the declaration reaches the reader below it + k.apply( + 0, + 2, + &[style( + 1, + &[(PROPERTIES, "--gap: 10px; --pad: calc(var(--gap) * 3)")], + )], + ) + .unwrap(); + assert_eq!(y(&mut k, 4), 30.0); + // A declaration between them adds to the inherited ones, and shadows its own name + k.apply(0, 3, &[style(2, &[(PROPERTIES, "--pad: 4px")])]) + .unwrap(); + assert_eq!(y(&mut k, 4), 4.0); +} + +#[test] +fn a_fallback_stands_in_for_an_undefined_or_invalid_property() { + let mut k = tree("--a: var(--b); --b: var(--a)", "var(--a, 7px)"); + assert_eq!(y(&mut k, 4), 7.0, "a cycle is guaranteed-invalid"); + let mut k = tree("--gap: 8px", "calc(var(--missing, 2px) + var(--gap))"); + assert_eq!(y(&mut k, 4), 10.0); + // Without one, the length is invalid at computed-value time: its initial value + let mut k = tree("--gap: 8px", "var(--missing)"); + assert_eq!(y(&mut k, 4), 0.0); +} + +#[test] +fn a_capture_hands_an_outer_owners_inset_to_a_nested_owner() { + // 1 root, 2 an outer owner (inset 100) that captures its top, 3 an inner + // owner (inset 30) in it, 4 a box in 3 that pads by the capture, 5 in 4 + let mut k = Kernel::with_monospace(); + let mut ops = create(1..=5); + ops.push(style(1, &[(StyleId::Height, "844")])); + ops.push(style( + 2, + &[(PROPERTIES, "--outer-top: var(--exact-safe-area-inset-top)")], + )); + ops.push(style(4, &[(TOP, "var(--outer-top)")])); + ops.push(style(5, &[(StyleId::Height, "10")])); + ops.extend([ + children(1, &[2]), + children(2, &[3]), + children(3, &[4]), + children(4, &[5]), + ]); + ops.push(Op::AttachRoot { id: 1 }); + k.apply(0, 1, &ops).unwrap(); + k.set_local_insets(2, Some([100.0, 0.0, 0.0, 0.0])).unwrap(); + k.set_local_insets(3, Some([30.0, 0.0, 0.0, 0.0])).unwrap(); + assert_eq!( + y(&mut k, 5), + 100.0, + "the outer owner's, not the nearest one's 30" + ); + // The capture follows the outer owner's inset + assert!(k.set_local_insets(2, Some([64.0, 0.0, 0.0, 0.0])).unwrap()); + assert_eq!(y(&mut k, 5), 64.0); +} + +#[test] +fn a_property_with_a_value_is_defined_whatever_its_fallback_reads() { + // The fallback reads a title-bar area the document does not have + let mut k = tree("--gap: 8px", "var(--gap, env(titlebar-area-height))"); + assert_eq!(y(&mut k, 4), 8.0); + let mut k = tree("--other: 8px", "var(--gap, env(titlebar-area-height))"); + assert_eq!(y(&mut k, 4), 0.0, "the fallback taken is undefined"); +} + +#[test] +fn an_env_with_a_fallback_reads_a_property_beside_it() { + // `env()` with a fallback is held as text, substituted per node + let mut k = tree( + "--gap: 8px", + "calc(env(safe-area-inset-top, 3px) + var(--gap))", + ); + assert_eq!(y(&mut k, 4), 8.0); + k.apply(0, 2, &[style(1, &[(PROPERTIES, "--gap: 5px")])]) + .unwrap(); + assert_eq!(y(&mut k, 4), 5.0); +} + +#[test] +fn a_property_of_rem_follows_the_root_font_size() { + let mut k = tree("--pad: 2rem", "var(--pad)"); + assert_eq!(y(&mut k, 4), 32.0); + k.set_root_font_size(20.0).unwrap(); + k.apply(0, 2, &[]).unwrap(); + assert_eq!(y(&mut k, 4), 40.0); +} + +#[test] +fn every_member_of_a_cycle_is_invalid_whatever_a_fallback_reaches() { + // A fallback's reference is an edge too, used or not (CSS Variables 1 §2.3) + let cases = [ + ("--a: var(--b, var(--a)); --b: 1px", "var(--a, 7px)"), + ( + "--a: calc(var(--b) + var(--c)); --b: var(--a); --c: var(--a, 3px)", + "var(--c, 7px)", + ), + ( + "--ok: 1px; --a: var(--ok, var(--b)); --b: var(--a)", + "var(--a, 7px)", + ), + ( + "--ok: 1px; --a: var(--ok, var(--b)); --b: var(--a)", + "var(--b, 7px)", + ), + ( + "--a: calc(var(--a) + var(--b)); --b: var(--a, 5px)", + "var(--b, 7px)", + ), + ]; + for (declared, pad) in cases { + let mut k = tree(declared, pad); + assert_eq!(y(&mut k, 4), 7.0, "{declared} read as {pad}"); + } + // What a cycle's member reads outside it stays valid + let mut k = tree("--ok: 2px; --a: var(--b); --b: var(--a)", "var(--ok, 7px)"); + assert_eq!(y(&mut k, 4), 2.0); +} + +#[test] +fn an_expansion_past_the_author_limits_is_invalid() { + // 64 values at --p5, past the 32 every consumer of a tree holds an author's to + let mut declared = vec!["--p0: min(1%, 1px)".to_string()]; + for i in 1..=5 { + declared.push(format!( + "--p{i}: calc(var(--p{}) + var(--p{}))", + i - 1, + i - 1 + )); + } + let mut k = tree(&declared.join("; "), "var(--p5, 7px)"); + assert_eq!(y(&mut k, 4), 7.0); + let mut k = tree(&declared.join("; "), "var(--p4, 7px)"); + assert_eq!(y(&mut k, 4), 16.0, "32 values hold: sixteen 1px"); +} + +#[test] +fn a_walk_past_the_declaration_bound_invalidates_every_value_in_either_order() { + let mut declared = vec!["--ok: 1px; --p0: 1px".to_string()]; + for i in 1..1100 { + declared.push(format!("--p{i}: var(--p{})", i - 1)); + } + let declared = declared.join("; "); + let mut a = tree(&declared, "calc(var(--ok, 2px) + var(--p1099, 7px))"); + let mut b = tree(&declared, "calc(var(--p1099, 7px) + var(--ok, 2px))"); + assert_eq!(y(&mut a, 4), 9.0, "both fallbacks"); + assert_eq!(y(&mut b, 4), 9.0); +} + +#[test] +fn a_long_expansion_is_invalid() { + // Each level doubles the one before (CSS Variables 1 §3.3) + let mut declared = vec!["--p0: 1%".to_string()]; + for i in 1..=16 { + declared.push(format!( + "--p{i}: calc(var(--p{}) + env(safe-area-inset-top) + var(--p{}))", + i - 1, + i - 1 + )); + } + let mut k = tree(&declared.join("; "), "var(--p16, 7px)"); + assert_eq!(y(&mut k, 4), 7.0); +} + +#[test] +fn an_undefined_environment_value_invalidates_its_declaration() { + let mut k = tree("--pad: env(titlebar-area-height)", "var(--pad, 7px)"); + assert_eq!(y(&mut k, 4), 7.0, "no title-bar area"); + let area = crate::Rect { + x: 0.0, + y: 0.0, + width: 390.0, + height: 28.0, + }; + k.set_env(k.env().with_titlebar_area(Some(area))).unwrap(); + assert_eq!(y(&mut k, 4), 28.0); + k.set_env(k.env().with_titlebar_area(None)).unwrap(); + assert_eq!(y(&mut k, 4), 7.0); +} + +#[test] +fn a_text_length_names_a_property_in_any_case() { + let mut k = tree( + "--gap: 8px", + "calc(env(safe-area-inset-top, 3px) + VAR(--gap))", + ); + assert_eq!(y(&mut k, 4), 8.0); +} + +#[test] +fn a_declaration_removed_or_shadowed_shows_the_one_above() { + // 2 declares its own --pad over the root's + let mut k = tree("--pad: 8px", "var(--pad)"); + k.apply(0, 2, &[style(2, &[(PROPERTIES, "--pad: 4px")])]) + .unwrap(); + assert_eq!(y(&mut k, 4), 4.0); + // A change above a nearer declaration reaches nothing below it + k.apply(0, 3, &[style(1, &[(PROPERTIES, "--pad: 9px")])]) + .unwrap(); + assert_eq!(y(&mut k, 4), 4.0); + // Removing the nearer one shows the root's + k.apply( + 0, + 4, + &[Op::ClearStyle { + id: 2, + mask: StyleMask::of(PROPERTIES), + written: false, + }], + ) + .unwrap(); + assert_eq!(y(&mut k, 4), 9.0); + // A declaration of a name that reads that name reads its own: a cycle + k.apply( + 0, + 5, + &[style(2, &[(PROPERTIES, "--pad: calc(var(--pad) * 2)")])], + ) + .unwrap(); + assert_eq!(y(&mut k, 4), 0.0); + // A declaration that reads a changed name carries the change below it + k.apply( + 0, + 6, + &[style(2, &[(PROPERTIES, "--pad: calc(var(--base) * 2)")])], + ) + .unwrap(); + k.apply( + 0, + 7, + &[style(1, &[(PROPERTIES, "--pad: 9px; --base: 5px")])], + ) + .unwrap(); + assert_eq!(y(&mut k, 4), 10.0); +} + +#[test] +fn a_moved_reader_reads_its_new_ancestors_declarations() { + // 1 the root, 2 declares --pad 8, 3 declares --pad 20, 4 pads by it, in 2, 5 in 4 + let mut k = Kernel::with_monospace(); + let mut ops = create(1..=5); + ops.push(style(1, &[(StyleId::Height, "844")])); + ops.push(style(2, &[(PROPERTIES, "--pad: 8px")])); + ops.push(style(3, &[(PROPERTIES, "--pad: 20px")])); + ops.push(style(4, &[(TOP, "var(--pad, 3px)")])); + ops.push(style(5, &[(StyleId::Height, "10")])); + ops.extend([children(1, &[2, 3]), children(2, &[4]), children(4, &[5])]); + ops.push(Op::AttachRoot { id: 1 }); + k.apply(0, 1, &ops).unwrap(); + let top = |k: &mut Kernel| { + k.compute_layout(1, Offer::definite(390.0, 844.0)).unwrap(); + k.node(5).unwrap().frame.y + }; + assert_eq!(top(&mut k), 8.0); + k.apply(0, 2, &[children(2, &[]), children(3, &[4])]) + .unwrap(); + assert_eq!(top(&mut k), 20.0, "no owner has local insets"); + // Under the root, which declares none, the fallback + k.apply(0, 3, &[children(3, &[]), children(1, &[2, 3, 4])]) + .unwrap(); + assert_eq!(top(&mut k), 3.0); +} + +#[test] +fn a_percentage_resolves_against_each_readers_own_basis() { + // 1 the root declares --w 50%; 2 (200 wide) holds 4, 3 (300 wide) holds 5 + let mut k = Kernel::with_monospace(); + let mut ops = create(1..=5); + ops.push(style( + 1, + &[(StyleId::Height, "844"), (PROPERTIES, "--w: 50%")], + )); + ops.push(style(2, &[(StyleId::Width, "200")])); + ops.push(style(3, &[(StyleId::Width, "300")])); + ops.push(style(4, &[(StyleId::Width, "var(--w)")])); + ops.push(style(5, &[(StyleId::Width, "var(--w)")])); + ops.extend([children(1, &[2, 3]), children(2, &[4]), children(3, &[5])]); + ops.push(Op::AttachRoot { id: 1 }); + k.apply(0, 1, &ops).unwrap(); + k.compute_layout(1, Offer::definite(390.0, 844.0)).unwrap(); + assert_eq!(k.node(4).unwrap().frame.width, 100.0); + assert_eq!(k.node(5).unwrap().frame.width, 150.0); +} + +#[test] +fn an_image_in_a_paragraph_measures_it_again_when_its_property_changes() { + // 1 declares --h; 2 a paragraph of 3 ("ab") and 4, an image --h tall + let mut k = Kernel::with_monospace(); + let mut ops = vec![ + Op::CreateView { + id: 1, + node_type: NodeType::View, + }, + Op::CreateView { + id: 2, + node_type: NodeType::Text, + }, + Op::CreateView { + id: 3, + node_type: NodeType::Text, + }, + Op::CreateView { + id: 4, + node_type: NodeType::Image, + }, + Op::SetProp { + id: 3, + prop: crate::PropId::Text, + value: "ab".into(), + }, + Op::SetProp { + id: 4, + prop: crate::PropId::ImageSource, + value: "app:/a.png".into(), + }, + ]; + ops.push(style( + 1, + &[(StyleId::Width, "400"), (PROPERTIES, "--h: 10px")], + )); + ops.push(style(2, &[(StyleId::FontSize, "16")])); + ops.push(style( + 4, + &[(StyleId::Width, "10"), (StyleId::Height, "var(--h)")], + )); + ops.extend([children(2, &[3, 4]), children(1, &[2])]); + ops.push(Op::AttachRoot { id: 1 }); + k.apply(0, 1, &ops).unwrap(); + let height = |k: &mut Kernel| { + k.compute_layout(1, Offer::definite(400.0, 600.0)).unwrap(); + k.node(4).unwrap().frame.height + }; + assert_eq!(height(&mut k), 10.0); + k.apply(0, 2, &[style(1, &[(PROPERTIES, "--h: 30px")])]) + .unwrap(); + assert_eq!(height(&mut k), 30.0); + assert!( + k.node(2).unwrap().frame.height > 30.0, + "the line grew to hold it" + ); +} diff --git a/kernel/src/style.rs b/kernel/src/style.rs index cb4478a7e..afa19f652 100644 --- a/kernel/src/style.rs +++ b/kernel/src/style.rs @@ -36,6 +36,7 @@ mod keyword; pub use keyword::SizeKeyword; mod handles; mod intern; +pub mod safe_area_properties; pub use calc::Comparison; use handles::calc_handle; pub(crate) use handles::{calc_handle_in, resolve_calc, tree_handle, LayoutEnv}; @@ -900,6 +901,8 @@ pub enum RowValue<'a> { AnimationRange(&'a crate::timeline::AnimationRange), /// CSS `timeline-scope` (LLP 1057.003 D4). TimelineScope(&'a crate::timeline::TimelineScope), + /// A node's runtime custom properties (LLP 1123 D5). + SafeAreaProperties(&'a crate::style::safe_area_properties::SafeAreaProperties), /// CSS `scroll-timeline-name` or `view-timeline-name` (LLP 1057.003 D5). TimelineName(&'a crate::timeline::TimelineName), /// CSS `view-timeline-inset` (LLP 1057.003 D5). diff --git a/kernel/src/style/calc/mod.rs b/kernel/src/style/calc/mod.rs index d51ab5044..4890d79d6 100644 --- a/kernel/src/style/calc/mod.rs +++ b/kernel/src/style/calc/mod.rs @@ -9,9 +9,10 @@ //! @ref LLP 1001 §2 mod parse; -mod simplify; +pub(crate) mod simplify; mod substitute; mod text; +pub(crate) use text::ident; mod wire; pub use parse::nonnegative_row; @@ -96,23 +97,24 @@ impl EnvTerm { } } +/// `var(--name)` of an author's custom property (LLP 1123 D5), read in a +/// length: the property's value where the reading node has one, else the +/// fallback; with neither, the length is invalid at computed-value time. +#[derive(Debug, Clone, PartialEq)] +pub struct Var { + /// The property's name, with its leading `--`. + pub name: Arc, + /// What stands in where the property has no value. + pub fallback: Option>, +} + /// `node` with every local inset (`EnvTerm::Local`) replaced by its points -/// under `env`. -fn localize(node: &Node, env: &Env) -> Node { - let all = |c: &[Node]| c.iter().map(|n| localize(n, env)).collect(); - match node { - Node::Env(EnvTerm::Local(edge)) => Node::Value(f64::from(env.local_inset(*edge)), Unit::Px), - Node::Value(..) | Node::Env(..) => node.clone(), - Node::Sum(c) => Node::Sum(all(c)), - Node::Product(c) => Node::Product(all(c)), - Node::Min(c) => Node::Min(all(c)), - Node::Max(c) => Node::Max(all(c)), - Node::Negate(c) => Node::Negate(Box::new(localize(c, env))), - Node::Invert(c) => Node::Invert(Box::new(localize(c, env))), - Node::Clamp(c) => Node::Clamp(Box::new( - c.each_ref().map(|n| n.as_ref().map(|n| localize(n, env))), - )), - } +/// under `env`, and every custom property by its value there (LLP 1123 D5); +/// `None` where a property has neither a value nor a fallback. +fn localize(node: &Node, env: &Env) -> Option { + substitute(node, &|edge| env.local_inset(edge), &mut |name| { + env.property(name).cloned() + }) } /// A calculation tree as §10.10 builds one and §10.10.1 leaves it: numeric @@ -126,6 +128,8 @@ pub enum Node { /// `env()` without a fallback: a substitution of a length, which a tree /// may hold as a leaf (one with a fallback is held as text, [`Entry`]). Env(EnvTerm), + /// `var()` of an author's custom property, resolved per node. + Var(Var), /// Its children added. Sum(Vec), /// Its children multiplied. @@ -149,6 +153,7 @@ impl PartialEq for Node { match (self, other) { (Value(a, u), Value(b, v)) => a.to_bits() == b.to_bits() && u == v, (Env(a), Env(b)) => a == b, + (Var(a), Var(b)) => a == b, (Sum(a), Sum(b)) | (Product(a), Product(b)) | (Min(a), Min(b)) | (Max(a), Max(b)) => { a == b } @@ -164,6 +169,10 @@ impl Node { fn children(&self) -> impl Iterator { let (nodes, optional): (&[Node], &[Option]) = match self { Node::Value(..) | Node::Env(..) => (&[], &[]), + Node::Var(v) => ( + v.fallback.as_deref().map_or(&[][..], std::slice::from_ref), + &[], + ), Node::Sum(c) | Node::Product(c) | Node::Min(c) | Node::Max(c) => (c, &[]), Node::Negate(c) | Node::Invert(c) => (std::slice::from_ref(c), &[]), Node::Clamp(c) => (&[], c.as_slice()), @@ -172,10 +181,20 @@ impl Node { } /// Whether a node anywhere in it satisfies `f`. - fn any(&self, f: &dyn Fn(&Node) -> bool) -> bool { + pub(crate) fn any(&self, f: &dyn Fn(&Node) -> bool) -> bool { f(self) || self.children().any(|c| c.any(f)) } + /// Each custom property it reads, fallbacks included. + pub(crate) fn names(&self, out: &mut Vec>) { + if let Node::Var(v) = self { + if !out.contains(&v.name) { + out.push(v.name.clone()); + } + } + self.children().for_each(|c| c.names(out)); + } + /// The value under `env`, a percentage of `basis`, in IEEE-754 `f64` /// as §10.9.2 has it inside a tree (an infinity or a NaN included); /// `None` where a segment is undefined or a percentage has no basis. @@ -188,6 +207,10 @@ impl Node { Unit::Rem => f64::from(env.root_font_size) * v, }, Node::Env(term) => term.value(env)?, + Node::Var(v) => match env.property(&v.name) { + Some(value) => value.value(env, basis)?, + None => v.fallback.as_ref()?.value(env, basis)?, + }, Node::Sum(c) => { let mut total = 0.0; for n in c { @@ -311,6 +334,143 @@ pub(crate) fn lone_env(term: EnvTerm) -> Dimension { dimension(Node::Env(term)) } +/// The tree a length is (LLP 1123 D5): a compact form's, or a +/// calculation's own; `None` for `auto`, a size keyword or a text a row +/// substitutes. +pub(crate) fn tree_of(d: &Dimension) -> Option { + let plus = |term: EnvTerm, x: f32| match x { + 0.0 => Node::Env(term), + _ => Node::Sum(vec![Node::Env(term), Node::Value(f64::from(x), Unit::Px)]), + }; + Some(match d { + // A size keyword is no length a tree holds + Dimension::Auto | Dimension::Keyword(_) => return None, + Dimension::Points(v) => Node::Value(f64::from(*v), Unit::Px), + Dimension::Percent(p) => Node::Value(f64::from(*p), Unit::Percent), + Dimension::Calc(p, x) => Node::Sum(vec![ + Node::Value(f64::from(*p), Unit::Percent), + Node::Value(f64::from(*x), Unit::Px), + ]), + Dimension::Env(edge, x) => plus(EnvTerm::Inset(*edge), *x), + Dimension::Region(region, edge, x) => plus(EnvTerm::Region(*region, *edge), *x), + Dimension::Segment(var, a, b, x) => plus(EnvTerm::Segment(*var, *a, *b), *x), + Dimension::Viewport(unit, n) => Node::Value(f64::from(*n), Unit::Viewport(*unit)), + Dimension::Compare(c) => return c.tree(|t| t.clone()), + }) +} + +/// Whether `node` reads an environment value `env` leaves undefined, which +/// makes what holds it invalid at computed-value time (CSS Environment +/// Variables 1 §3); a custom property is read as its value, else its +/// fallback (CSS Variables 1 §3). +pub(crate) fn undefined_in(node: &Node, env: &Env) -> bool { + match node { + // A local inset is always defined, and only a node's environment has it + Node::Env(EnvTerm::Local(_)) => false, + Node::Env(term) => term.value(env).is_none(), + Node::Var(v) => match (env.property(&v.name), &v.fallback) { + (Some(value), _) => undefined_in(value, env), + (None, Some(fallback)) => undefined_in(fallback, env), + (None, None) => true, + }, + n => n.children().any(|c| undefined_in(c, env)), + } +} + +/// Whether `node` is small enough to hold once its custom properties are +/// substituted: CSS Variables 1 §3.3 has a long expansion invalid, and the +/// bound is the one every consumer of a tree holds an author's to (CSS +/// Values 4 §10.8's values and levels, which the wire and the Apple host +/// check). +pub(crate) fn within_expansion(node: &Node) -> bool { + wire::within_author_limits(node) +} + +/// A length's CSS: a lone value as itself, any other tree as a math +/// function, a text as written. +pub(crate) fn length_css(d: &Dimension, out: &mut String) { + let tree = match d { + Dimension::Compare(c) => match c.tree(|t| text::length(t, out)) { + Some(()) => return, + None => return c.css(out), + }, + d => tree_of(d), + }; + match tree { + Some(t) => text::length(&t, out), + None => out.push_str("auto"), + } +} + +/// `node` with each local inset as `local` gives it and each custom +/// property as `property` resolves it (LLP 1123 D5); `None` where a +/// property has neither a value nor a fallback. +pub(crate) fn substitute( + node: &Node, + local: &dyn Fn(Edge) -> f32, + property: &mut dyn FnMut(&Arc) -> Option, +) -> Option { + let all = |c: &[Node], property: &mut dyn FnMut(&Arc) -> Option| { + c.iter() + .map(|n| substitute(n, local, property)) + .collect::>>() + }; + Some(match node { + Node::Env(EnvTerm::Local(edge)) => Node::Value(f64::from(local(*edge)), Unit::Px), + Node::Var(v) => match property(&v.name) { + Some(value) => value, + None => substitute(v.fallback.as_ref()?, local, property)?, + }, + Node::Value(..) | Node::Env(..) => node.clone(), + Node::Sum(c) => Node::Sum(all(c, property)?), + Node::Product(c) => Node::Product(all(c, property)?), + Node::Min(c) => Node::Min(all(c, property)?), + Node::Max(c) => Node::Max(all(c, property)?), + Node::Negate(c) => Node::Negate(Box::new(substitute(c, local, property)?)), + Node::Invert(c) => Node::Invert(Box::new(substitute(c, local, property)?)), + Node::Clamp(c) => { + let [lo, v, hi] = c.as_ref(); + // `none` stays `none`; an argument that substitutes to nothing is invalid + let mut one = |n: &Option| match n { + Some(n) => substitute(n, local, property).map(Some), + None => Some(None), + }; + Node::Clamp(Box::new([one(lo)?, one(v)?, one(hi)?])) + } + }) +} + +/// Each author's custom property a text's `var()`s name, fallbacks +/// included, by CSS's tokens: a function's name in any case, a property's +/// as written. +fn text_properties(text: &str, out: &mut Vec>) { + use cssparser::{Parser, ParserInput, Token}; + fn walk(p: &mut Parser<'_, '_>, out: &mut Vec>) { + while let Ok(token) = p.next() { + let var = matches!(token, Token::Function(name) if name.eq_ignore_ascii_case("var")); + if !matches!(token, Token::Function(_) | Token::ParenthesisBlock) { + continue; + } + let _ = p.parse_nested_block(|p| { + if var { + if let Ok(Token::Ident(name)) = p.next() { + let name: &str = name; + if crate::style::safe_area_properties::is_author_name(name) + && !out.iter().any(|n| &**n == name) + { + out.push(name.into()); + } + } + } + walk(p, out); + Ok::<_, cssparser::ParseError<'_, ()>>(()) + }); + } + } + let mut input = ParserInput::new(text); + walk(&mut Parser::new(&mut input), out); +} + /// A calculation a row holds: a handle to its interned entry. #[derive(Clone)] pub struct Comparison(Arc, Entry>>); @@ -402,6 +562,11 @@ impl Comparison { } } + /// Whether it is held as a tree, not as a text a row substitutes. + pub(crate) fn is_tree(&self) -> bool { + self.tree(|_| ()).is_some() + } + /// `f` of the tree, or `None` for a text, without copying either. fn tree(&self, f: impl FnOnce(&Node) -> T) -> Option { self.with(|e| match e { @@ -447,13 +612,7 @@ impl Comparison { /// whichever argument it is in, or a text substituted is no value of its /// row (CSS Environment Variables 1 §3). pub(crate) fn undefined(&self, env: &Env) -> bool { - // A local inset is always defined, and only a node's environment has it - let undefined = |n: &Node| match n { - Node::Env(EnvTerm::Local(_)) => false, - Node::Env(term) => term.value(env).is_none(), - _ => false, - }; - self.tree(|t| t.any(&undefined)).unwrap_or_else(|| { + self.tree(|t| undefined_in(t, env)).unwrap_or_else(|| { self.substituted(env) .is_none_or(|d| d.undefined_segment(env)) }) @@ -512,6 +671,30 @@ impl Comparison { }) } + /// Whether it reads an author's custom property (LLP 1123 D5), which + /// resolves per node: in a tree, at a leaf; a text whose `env()` has a + /// fallback, wherever it names one. + pub(crate) fn reads_custom(&self) -> bool { + match &self.0.value { + Entry::Tree(t) => t.any(&|n| matches!(n, Node::Var(_))), + Entry::Text { text, .. } => { + let mut names = Vec::new(); + text_properties(text, &mut names); + !names.is_empty() + } + } + } + + /// The custom properties it reads, each name with its `--`, fallbacks + /// included (LLP 1123 D5): a tree's at its leaves, a text's wherever a + /// `var()` of an author's name stands in it. + pub(crate) fn properties(&self, out: &mut Vec>) { + match &self.0.value { + Entry::Tree(t) => t.names(out), + Entry::Text { text, .. } => text_properties(text, out), + } + } + /// Whether it reads the local inset at `edge`. pub(crate) fn reads_local_edge(&self, edge: Edge) -> bool { self.with(|e| match e { @@ -522,14 +705,19 @@ impl Comparison { }) } - /// The tree with its local insets as `env` has them, in points, as the - /// dimension that holds it; `None` when it reads none. A tree handed to - /// layout, where only the window's environment is known, is localized - /// first (LLP 1123 D5). + /// The tree with its local insets and custom properties as `env` has + /// them, as the dimension that holds it, `Auto` (the row's initial + /// value) where a property is invalid; `None` when it reads neither. A + /// tree handed to layout, where only the window's environment is known, + /// is localized first (LLP 1123 D5). pub(crate) fn localized(&self, env: &Env) -> Option { self.tree(|t| { - t.any(&|n| matches!(n, Node::Env(EnvTerm::Local(_)))) - .then(|| dimension(simplify::simplify(localize(t, env)))) + t.any(&|n| matches!(n, Node::Env(EnvTerm::Local(_)) | Node::Var(_))) + .then(|| { + let t = localize(t, env).map(simplify::simplify); + t.filter(within_expansion) + .map_or(Dimension::Auto, dimension) + }) }) .flatten() } diff --git a/kernel/src/style/calc/parse.rs b/kernel/src/style/calc/parse.rs index d2cefbab1..f5accda50 100644 --- a/kernel/src/style/calc/parse.rs +++ b/kernel/src/style/calc/parse.rs @@ -2,7 +2,7 @@ //! (CSS Values 4 §10.8–§10.10). `cssparser` handles CSS tokenization; numeric //! values are read from the source as `f64` because its tokens store `f32`. //! -//! Unsupported: `em`/`rem` (font resolution happens after commit) and unit +//! Unsupported: `em` (font resolution happens after commit) and unit //! algebra beyond multiplying or dividing a length by a number. use super::super::env::{self, EnvRefusal}; @@ -19,10 +19,12 @@ pub(crate) mod refusal { pub(crate) const RELATIVE: &str = "em is not supported inside calc(), min(), max() or clamp(); write rem or px"; pub(crate) const UNITLESS: &str = "a number where a length goes inside calc(), min(), max() or clamp() takes a unit, as CSS requires, zero too: 0px, 15px"; - pub(crate) const NOT_A_LENGTH: &str = "calc(), min(), max() and clamp() take px (or rem, in, cm, mm, q, pt, pc, ch, lh) lengths, percentages, env(safe-area-inset-*), env(viewport-segment-* x y), env(titlebar-area-*), var(--exact-safe-area-inset-*), viewport lengths (vw, vh, vmin, vmax, svh, lvh, dvh, …), numbers and e, pi, infinity and NaN"; + pub(crate) const NOT_A_LENGTH: &str = "calc(), min(), max() and clamp() take px (or rem, in, cm, mm, q, pt, pc, ch, lh) lengths, percentages, env(safe-area-inset-*), env(viewport-segment-* x y), env(titlebar-area-*), var(--name) of a custom property a node declares, var(--exact-safe-area-inset-*), viewport lengths (vw, vh, vmin, vmax, svh, lvh, dvh, …), numbers and e, pi, infinity and NaN"; pub(crate) const FUNCTION: &str = - "inside a length the functions are calc(), min(), max(), clamp(), env() and var(--exact-safe-area-inset-*)"; - pub(crate) const VAR: &str = "a length reads one custom property, its content owner's safe-area inset: var(--exact-safe-area-inset-top), -right, -bottom or -left"; + "inside a length the functions are calc(), min(), max(), clamp(), env() and var()"; + pub(crate) const VAR: &str = "a length's var() reads a custom property a node declares (var(--name)) or the content owner's safe-area inset (var(--exact-safe-area-inset-top), -right, -bottom or -left); other --exact- names are the host's and none is defined"; + pub(crate) const VAR_LENGTH: &str = + "a custom property here is a length, so its fallback is a length too"; pub(crate) const VAR_FALLBACK: &str = "var(--exact-safe-area-inset-*) takes no fallback: every host defines it"; pub(crate) const NONE: &str = @@ -332,7 +334,7 @@ impl Calc { match name.as_str() { // `env()` substitutes a length: no level of the calculation "env" if !self.grid => p.parse_nested_block(|p| self.env(p, depth)), - "var" if !self.grid => p.parse_nested_block(|p| self.var(p)), + "var" if !self.grid => p.parse_nested_block(|p| self.var(p, depth)), "calc" => { let depth = self.deeper(p, depth)?; p.parse_nested_block(|p| self.whole(p, depth)) @@ -475,24 +477,44 @@ impl Calc { Ok((node, ty)) } - /// `var(--exact-safe-area-inset-)`, the local inset (LLP 1123 D9): - /// the one custom property a length reads, without a fallback. Its name - /// is matched as written, as a custom property's is. - fn var<'i>(&mut self, p: &mut Parser<'i, '_>) -> Parsed<'i, (Node, Ty)> { + /// `var(--exact-safe-area-inset-)`, the local inset (LLP 1123 D9), + /// without a fallback; or `var(--name, )`, an author's custom + /// property, a length (D5). A name is matched as written, as a custom + /// property's is. + fn var<'i>(&mut self, p: &mut Parser<'i, '_>, depth: usize) -> Parsed<'i, (Node, Ty)> { self.count(p)?; - let edge = match p.expect_ident() { - Ok(name) => name - .strip_prefix(env::LOCAL_PREFIX) - .and_then(env::Edge::from_name), - Err(_) => None, + let name = match p.expect_ident_cloned() { + Ok(name) => name, + Err(_) => return why(p, refusal::VAR), }; - let Some(edge) = edge else { + if let Some(edge) = name + .strip_prefix(env::LOCAL_PREFIX) + .and_then(env::Edge::from_name) + { + if !p.is_exhausted() { + return why(p, refusal::VAR_FALLBACK); + } + return Ok((Node::Env(EnvTerm::Local(edge)), Ty::Length)); + } + if !crate::style::safe_area_properties::is_author_name(&name) { return why(p, refusal::VAR); - }; - if !p.is_exhausted() { - return why(p, refusal::VAR_FALLBACK); } - Ok((Node::Env(EnvTerm::Local(edge)), Ty::Length)) + let fallback = match p.is_exhausted() { + true => None, + false => { + p.expect_comma()?; + // One value, a tree's operand wherever the call stands: CSS substitutes a + // fallback's tokens, so a sum written bare would group differently + let (fallback, ty) = self.value(p, depth)?; + p.expect_exhausted()?; + if ty != Ty::Length { + return why(p, refusal::VAR_LENGTH); + } + Some(Box::new(fallback)) + } + }; + let name = name.as_ref().into(); + Ok((Node::Var(super::Var { name, fallback }), Ty::Length)) } /// `env( *)`: the variable. One with a fallback makes the diff --git a/kernel/src/style/calc/simplify.rs b/kernel/src/style/calc/simplify.rs index 7c0a8d75e..6886f9aed 100644 --- a/kernel/src/style/calc/simplify.rs +++ b/kernel/src/style/calc/simplify.rs @@ -8,7 +8,7 @@ use super::{pick, Node, Unit}; /// The tree `root` simplified, every NaN the one NaN: CSS writes a NaN as /// `NaN`, whatever its sign or payload (§10.13), so the tree holds no other. -pub(super) fn simplify(root: Node) -> Node { +pub(crate) fn simplify(root: Node) -> Node { canonical(fold(root)) } @@ -17,6 +17,10 @@ fn canonical(n: Node) -> Node { match n { Node::Value(v, unit) if v.is_nan() => Node::Value(f64::NAN, unit), Node::Value(..) | Node::Env(..) => n, + Node::Var(v) => Node::Var(super::Var { + fallback: v.fallback.map(|f| Box::new(canonical(*f))), + ..v + }), Node::Sum(c) => Node::Sum(all(c)), Node::Product(c) => Node::Product(all(c)), Node::Min(c) => Node::Min(all(c)), @@ -30,6 +34,10 @@ fn canonical(n: Node) -> Node { fn fold(root: Node) -> Node { match root { Node::Value(..) | Node::Env(..) => root, + Node::Var(v) => Node::Var(super::Var { + fallback: v.fallback.map(|f| Box::new(fold(*f))), + ..v + }), Node::Min(c) => min_max(c.into_iter().map(fold).collect(), false), Node::Max(c) => min_max(c.into_iter().map(fold).collect(), true), Node::Clamp(c) => clamp(c.map(|a| a.map(fold))), diff --git a/kernel/src/style/calc/text.rs b/kernel/src/style/calc/text.rs index 651953231..8087f0d1a 100644 --- a/kernel/src/style/calc/text.rs +++ b/kernel/src/style/calc/text.rs @@ -5,6 +5,21 @@ use super::{EnvTerm, Node, Unit}; +/// `name` as a CSS identifier, escaped where it must be. +pub(crate) fn ident(name: &str, out: &mut String) { + // Writing to a String cannot fail + let _ = cssparser::serialize_identifier(name, out); +} + +/// A length's tree as CSS: a lone value as itself, anything else as a +/// math function. +pub(crate) fn length(root: &Node, out: &mut String) { + match root { + Node::Value(v, unit) => value(*v, *unit, out), + _ => math_function(root, out), + } +} + /// "Serialize a math function" whose tree is `root`. pub(super) fn math_function(root: &Node, out: &mut String) { match root { @@ -23,7 +38,7 @@ pub(super) fn math_function(root: &Node, out: &mut String) { out.push(')'); } // A non-math function as normal - Node::Env(..) => tree(root, out), + Node::Env(..) | Node::Var(..) => tree(root, out), _ => { out.push_str("calc("); out.push_str(stripped(&serialized(root))); @@ -64,6 +79,16 @@ fn tree(n: &Node, out: &mut String) { match n { Node::Value(v, unit) => value(*v, *unit, out), Node::Env(term) => env(*term, out), + Node::Var(v) => { + out.push_str("var("); + ident(&v.name, out); + // A fallback is written as a length, which stands alone where a row's value does + if let Some(fallback) = &v.fallback { + out.push_str(", "); + length(fallback, out); + } + out.push(')'); + } Node::Min(_) | Node::Max(_) | Node::Clamp(_) => math_function(n, out), Node::Negate(c) => { out.push_str("(-1 * "); diff --git a/kernel/src/style/calc/wire.rs b/kernel/src/style/calc/wire.rs index 297da9bdd..25c571d4c 100644 --- a/kernel/src/style/calc/wire.rs +++ b/kernel/src/style/calc/wire.rs @@ -25,7 +25,8 @@ pub(super) const MAX_LEVELS: usize = 2 * super::MAX_DEPTH + 2; /// (0–3 an inset's edge, 8–13 a segment's variable, then its two indices, /// 16–35 a layout region's inset, 36–39 a title-bar area variable); /// a list's `u8` count; clamp's three presence bytes, each before its -/// argument. +/// argument; 10 an author's custom property (LLP 1123 D5), its name as the +/// codec's string, then its fallback's presence byte and the fallback. pub(super) fn encode(entry: &Entry, w: &mut Writer) { match entry { Entry::Tree(n) => node_out(n, w), @@ -87,6 +88,11 @@ fn node_out(n: &Node, w: &mut Writer) { w.u8(8); c.iter().for_each(|a| optional(a.as_ref(), w)); } + Node::Var(v) => { + w.u8(10); + w.string(&v.name); + optional(v.fallback.as_deref(), w); + } } } @@ -143,7 +149,7 @@ pub(super) fn within_author_limits(tree: &Node) -> bool { fn authored(n: &Node, opened: bool) -> (usize, usize) { let function = matches!(n, Node::Min(_) | Node::Max(_) | Node::Clamp(_)); let product = matches!(n, Node::Product(_)); - let mut values = usize::from(matches!(n, Node::Value(..) | Node::Env(..))); + let mut values = usize::from(matches!(n, Node::Value(..) | Node::Env(..) | Node::Var(..))); let mut deepest = 0; for c in n.children() { let (v, l) = authored(c, product && matches!(c, Node::Sum(_))); @@ -209,6 +215,13 @@ fn node(r: &mut Reader<'_>, level: usize, nodes: &mut usize) -> Option { optional(r, nodes)?, optional(r, nodes)?, ])), + 10 => { + let name = r.string().ok()?; + Node::Var(super::Var { + name: name.into(), + fallback: optional(r, nodes)?.map(Box::new), + }) + } _ => return None, }) } diff --git a/kernel/src/style/env.rs b/kernel/src/style/env.rs index bfab8764a..eb7e6f58c 100644 --- a/kernel/src/style/env.rs +++ b/kernel/src/style/env.rs @@ -349,6 +349,10 @@ pub struct Env { /// document's environment has none, and a local inset resolved against /// it is a caller's mistake ([`Env::local_inset`]). pub local: Option<[f32; 4]>, + /// The values of the custom properties one node's lengths read (LLP + /// 1123 D5), set, as `local` is, only in an environment made for that + /// node. + pub properties: Option, } impl Default for Env { @@ -381,6 +385,7 @@ impl Env { root_font_size: crate::style::relative::MEDIUM, root_local: None, local: None, + properties: None, } } @@ -399,6 +404,20 @@ impl Env { } } + /// An author's custom property's value at the node this environment was + /// made for (LLP 1123 D5); `None` where it is undeclared or invalid. One + /// with no node is the document's, and reading it is a caller's mistake, + /// as for a local inset ([`misread`]). + pub fn property(&self, name: &str) -> Option<&crate::style::calc::Node> { + match &self.properties { + Some(properties) => properties.get(name), + None => { + misread_var(name); + None + } + } + } + /// The session root's local inset at `edge` (LLP 1123 D9): the host's, /// else the safe-area inset. pub fn root_inset(&self, edge: Edge) -> f32 { @@ -840,12 +859,13 @@ pub fn uses_env(style: &crate::StyleProps) -> bool { } /// The rows of `style` whose engine value a root font size can change: a -/// calculation or a grid template that holds a `rem`. +/// calculation or a grid template that holds a `rem`, or a calculation that +/// reads a custom property, which may hold one (LLP 1123 D5). pub(crate) fn root_font_readers(style: &crate::StyleProps) -> crate::StyleMask { let mut rows = crate::StyleMask::EMPTY; for id in style.mask.iter() { let reads = match style.get(id) { - crate::RowValue::Dimension(Dimension::Compare(c)) => c.reads_rem(), + crate::RowValue::Dimension(Dimension::Compare(c)) => c.reads_rem() || c.reads_custom(), _ => match id { crate::StyleId::GridTemplateColumns => style.rare.grid_template_columns.reads_rem(), crate::StyleId::GridTemplateRows => style.rare.grid_template_rows.reads_rem(), @@ -896,22 +916,37 @@ static WARNED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::ne /// tests always); otherwise the read takes the session root's inset, which /// a development build says once on the console. fn misread(edge: Edge) { + report(&format!( + "var(--exact-safe-area-inset-{}) resolved against the document's environment: \ + resolve a box's lengths with NodeArena::env_of or Kernel::env_of (LLP 1123 D9); \ + the session root's inset stands in", + edge.name() + )); +} + +/// A box's custom property read against the document's environment (LLP +/// 1123 D5), which has none: the property takes its fallback, as one +/// undeclared does. +fn misread_var(name: &str) { + report(&format!( + "var({name}) resolved against the document's environment: resolve a box's lengths \ + with NodeArena::env_of or Kernel::env_of (LLP 1123 D5); the fallback stands in" + )); +} + +/// Stop a test, or a process with `EXACT_STRICT_LOCAL_INSETS=1`, at a +/// length a reader resolved against the document's environment; else say so +/// once in a development build. +fn report(message: &str) { use std::sync::atomic::Ordering::Relaxed; let strict = cfg!(test) || *STRICT.get_or_init(|| { std::env::var_os("EXACT_STRICT_LOCAL_INSETS").is_some_and(|v| v == "1") }); - let message = || { - format!( - "var(--exact-safe-area-inset-{}) resolved against the document's environment: \ - resolve a box's lengths with NodeArena::env_of or Kernel::env_of (LLP 1123 D9)", - edge.name() - ) - }; if strict { - panic!("{}", message()); + panic!("{message}"); } if cfg!(debug_assertions) && !WARNED.swap(true, Relaxed) { - eprintln!("exact: {}; the session root's inset stands in", message()); + eprintln!("exact: {message}"); } } diff --git a/kernel/src/style/finite.rs b/kernel/src/style/finite.rs index 112d34c56..0b140c5f5 100644 --- a/kernel/src/style/finite.rs +++ b/kernel/src/style/finite.rs @@ -31,6 +31,7 @@ impl RowValue<'_> { | RowValue::DragTimeline(_) | RowValue::AnimationTimeline(_) | RowValue::TimelineScope(_) + | RowValue::SafeAreaProperties(_) | RowValue::TimelineName(_) | RowValue::BackgroundImage(_) | RowValue::TextShadow(_) diff --git a/kernel/src/style/safe_area_properties.rs b/kernel/src/style/safe_area_properties.rs new file mode 100644 index 000000000..881ee9e60 --- /dev/null +++ b/kernel/src/style/safe_area_properties.rs @@ -0,0 +1,143 @@ +//! An author's custom properties (@ref LLP 1123 D5; CSS Variables 1), which +//! the safe-area API reads in lengths: `--hero-top` set to +//! `var(--exact-safe-area-inset-top)` captures a node's inset for its +//! subtree, which reads it as `var(--hero-top)`. +//! +//! They have CSS's unregistered semantics, held typed: each value is a +//! length, since only a length reads one, and its `var()`s are substituted +//! where it is declared, so a capture holds the declaring node's inset in +//! points. A reader resolves each property it names at the nearest node at or +//! above it that declares one ([`crate::kernel::owner::properties_at`]). One +//! that reads an undefined property without a fallback, or that is in a +//! dependency cycle, is the guaranteed-invalid value: every `var()` of it +//! takes its fallback. + +use super::calc::Node; +use super::{Dimension, StyleId, StyleValue}; +use cssparser::{Delimiter, ParseError, Parser, ParserInput, Token}; +use std::sync::Arc; + +/// Names the host defines (LLP 1081 D5), which no author declares. +pub const HOST_PREFIX: &str = "--exact-"; + +/// Whether `name` is `--` and an identifier an author may declare. +pub fn is_author_name(name: &str) -> bool { + name.len() > 2 && name.starts_with("--") && !name.starts_with(HOST_PREFIX) +} + +/// One node's declarations in written order, each name with its leading +/// `--`. A later declaration of a name replaces an earlier one. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct SafeAreaProperties(Arc<[(Arc, Dimension)]>); + +impl SafeAreaProperties { + /// `--a: ; --b: `, each name an author's and each value + /// one [`Self::value`] takes; `None` otherwise. No declaration at all is + /// a node that declares none. + pub fn parse(css: &str) -> Option { + let mut input = ParserInput::new(css); + let mut p = Parser::new(&mut input); + let mut out: Vec<(Arc, Dimension)> = Vec::new(); + loop { + p.skip_whitespace(); + if p.is_exhausted() { + break; + } + let name: Arc = match p.next() { + Ok(Token::Ident(name)) if is_author_name(name) => name.as_ref().into(), + _ => return None, + }; + p.expect_colon().ok()?; + let start = p.position(); + p.parse_until_before(Delimiter::Semicolon, |p| { + while p.next_including_whitespace_and_comments().is_ok() {} + Ok::<_, ParseError<'_, ()>>(()) + }) + .ok()?; + let value = Self::value(p.slice_from(start))?; + out.retain(|(n, _)| *n != name); + out.push((name, value)); + if p.expect_semicolon().is_err() && !p.is_exhausted() { + return None; + } + } + Some(SafeAreaProperties(out.into())) + } + + /// `name` as CSS writes it, escaped where it must be. + pub fn write_name(name: &str, out: &mut String) { + super::calc::ident(name, out); + } + + /// One declaration's value: a length a calculation tree holds, px and + /// the absolute units, `rem`, a percentage, a viewport unit, `env()` + /// without a fallback, `var()`, or a math function of these; `None` + /// otherwise. An `env()` with a fallback is held as text a row + /// substitutes, so a declaration refuses it. + pub fn value(text: &str) -> Option { + match length(text)? { + Dimension::Compare(c) if !c.is_tree() => None, + d => Some(d), + } + } + + /// The declarations as [`Self::parse`] reads them. + pub fn css(&self) -> String { + let mut out = String::new(); + for (i, (name, value)) in self.iter().enumerate() { + if i > 0 { + out.push_str("; "); + } + Self::write_name(name, &mut out); + out.push_str(": "); + super::calc::length_css(value, &mut out); + } + out + } + + /// Each declaration in the order written, a later one of a name having + /// replaced an earlier one. + pub fn iter(&self) -> impl Iterator { + self.0.iter().map(|(n, v)| (&**n, v)) + } + + /// What this node declares `name` as, where it declares it. + pub fn get(&self, name: &str) -> Option<&Dimension> { + self.0.iter().find(|(n, _)| &**n == name).map(|(_, v)| v) + } +} + +/// A declaration's value as a length a calculation holds: a margin's, or +/// a bare `rem`, which a row converts where it is set and a tree holds as a +/// leaf. `em`, a text style and a platform length (`-exact-hairline`) +/// convert at their row too, and a tree has no leaf for them. +fn length(text: &str) -> Option { + let text = text.trim_matches(['\t', '\n', '\u{c}', '\r', ' ']); + if let Some((super::relative::Unit::Rem, n)) = super::relative::parse(text) { + return Some(super::calc::dimension(Node::Value( + f64::from(n), + super::calc::Unit::Rem, + ))); + } + StyleValue::Text(text.into()) + .dimension(StyleId::MarginTop, false) + .ok() +} + +/// The values of the custom properties one node's lengths read, each with +/// its `var()`s substituted where it is declared; a property that is +/// undeclared or invalid there is absent. A node reads few, so a list +/// holds them, and one that reads none allocates nothing. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Resolved(pub(crate) Vec<(Arc, Node)>); + +impl Resolved { + /// `name`'s value at the node; `None` where it is undeclared or invalid. + pub fn get(&self, name: &str) -> Option<&Node> { + self.0.iter().find(|(n, _)| &**n == name).map(|(_, v)| v) + } +} + +#[cfg(test)] +#[path = "safe_area_properties_tests.rs"] +mod tests; diff --git a/kernel/src/style/safe_area_properties_tests.rs b/kernel/src/style/safe_area_properties_tests.rs new file mode 100644 index 000000000..fc3f03764 --- /dev/null +++ b/kernel/src/style/safe_area_properties_tests.rs @@ -0,0 +1,53 @@ +use super::*; + +#[test] +fn declarations_are_authors_names_and_lengths() { + let p = SafeAreaProperties::parse(" --gap : 8px ; --pad: calc(var(--gap) * 2);--gap: 12px; ") + .unwrap(); + assert_eq!(p.css(), "--pad: calc(2 * var(--gap)); --gap: 12px"); + assert_eq!(SafeAreaProperties::parse(&p.css()), Some(p)); + // Every length a calculation tree holds, as written; a name escaped where it must be + let each = SafeAreaProperties::parse( + "--a: 2rem; --b: 50%; --c: 10vw; --d: env(safe-area-inset-top); --e: 1in; --f\\?: var(--exact-safe-area-inset-top); --g: var(--a, calc(10% + 2px))", + ) + .unwrap(); + let css = "--a: 2rem; --b: 50%; --c: 10vw; --d: env(safe-area-inset-top); --e: 96px; --f\\?: var(--exact-safe-area-inset-top); --g: var(--a, calc(10% + 2px))"; + assert_eq!(each.css(), css); + assert_eq!(SafeAreaProperties::parse(css), Some(each)); + // No declaration is a node that declares none + assert_eq!( + SafeAreaProperties::parse(" "), + Some(SafeAreaProperties::default()) + ); + for bad in [ + "gap: 8px", + "--exact-safe-area-inset-top: 0px", + "--a: 1px !important", + "--a: red", + "--a: auto", + "--a: var(--b, red)", + "--a 1px", + "--a: 1px --b: 2px", + // A font-relative length converts where its row is set, so a declaration takes `rem` + "--a: 1em", + // An `env()` with a fallback is a text a row substitutes, so no tree holds it + "--a: env(safe-area-inset-top, 4px)", + "--a: red env(safe-area-inset-top, 0px)", + // Outside a math function a fallback stands alone + "--a: var(--b, 10% + 2px)", + ] { + assert_eq!(SafeAreaProperties::parse(bad), None, "{bad:?}"); + } + assert_eq!( + SafeAreaProperties::value("1px; --b: 8px"), + None, + "one value" + ); + // A fallback is one value wherever the call stands: CSS substitutes its + // tokens, so a bare sum would group differently + assert_eq!( + SafeAreaProperties::value("calc(2 * var(--m, 1px + 2px))"), + None + ); + assert!(SafeAreaProperties::value("calc(2 * var(--m, calc(1px + 2px)))").is_some()); +} diff --git a/kernel/src/txn.rs b/kernel/src/txn.rs index f9d8fc017..cdfd6f4f4 100644 --- a/kernel/src/txn.rs +++ b/kernel/src/txn.rs @@ -842,6 +842,7 @@ pub(crate) fn continue_document( if changed.is_empty() { continue; } + let declared = crate::kernel::owner::declared_before(arena, slot, changed); let excluded = crate::flow::is_exclusion(arena, slot); let named = arena.named_text_style(slot).is_some(); arena.patch_style(slot, patch); @@ -859,6 +860,11 @@ pub(crate) fn continue_document( } touched.push(arena.key(slot)); propagate_inherited(arena, layout, slot, changed, touched, receipt); + if let Some(old) = declared { + crate::kernel::owner::declarations_changed( + arena, layout, slot, &old, touched, receipt, + ); + } } Op::ClearStyle { id, mask, written } => { let slot = live_slot(arena, op_index, *id)?; @@ -866,6 +872,7 @@ pub(crate) fn continue_document( if changed.is_empty() { continue; } + let declared = crate::kernel::owner::declared_before(arena, slot, changed); let excluded = crate::flow::is_exclusion(arena, slot); let named = arena.named_text_style(slot).is_some(); arena.clear_style(slot, *mask, *written); @@ -879,6 +886,11 @@ pub(crate) fn continue_document( segmented::style_changed(arena, layout, slot, changed, touched); touched.push(arena.key(slot)); propagate_inherited(arena, layout, slot, changed, touched, receipt); + if let Some(old) = declared { + crate::kernel::owner::declarations_changed( + arena, layout, slot, &old, touched, receipt, + ); + } } Op::SetChildren { id, children } => { let slot = live_slot(arena, op_index, *id)?; @@ -1399,7 +1411,7 @@ fn view_box_changed( receipt.layout_invalidated = true; } -fn style_changed( +pub(crate) fn style_changed( arena: &mut NodeArena, layout: &mut dyn LayoutMirror, slot: u32, diff --git a/kernel/src/wire/codec.rs b/kernel/src/wire/codec.rs index db947fbda..f201b7cdb 100644 --- a/kernel/src/wire/codec.rs +++ b/kernel/src/wire/codec.rs @@ -753,7 +753,7 @@ mod tests { // Recomputed when the schema changes; the digest test prints the value. // Apple JSON record and inline style declarations participate (LLP 1172.001 E4), // even when the EXWF codec bytes above stay unchanged. - assert_eq!(SCHEMA_DIGEST, 0x363269dc528cd274); + assert_eq!(SCHEMA_DIGEST, 0xb69ef2eef7155882); } #[test] diff --git a/kernel/tables/schema.json b/kernel/tables/schema.json index f79d1b92f..2da5890f1 100644 --- a/kernel/tables/schema.json +++ b/kernel/tables/schema.json @@ -5252,6 +5252,14 @@ ], "cold": true, "_comment": "LLP 1061 D7: :active translate, added to the authored translation on the host press clock; percentages resolve against the border box. No layout or motion-engine target." + }, + { + "bit": 255, + "field": "safe_area_properties", + "rare": true, + "codec": "safe-area-properties", + "layout": true, + "_comment": "@ref LLP 1123 D5: an author's custom properties, the `--name=\"\"` attributes a node declares, as CSS text `--a: ; --b: `. CSS Variables 1's unregistered semantics, held typed: each value is a length, since only a length reads one, and its `var()`s are substituted where it is declared, so a capture (`var(--exact-safe-area-inset-top)`) holds the declaring node's inset. A length reads one through `var(--name, fallback)`, resolved at the nearest node that declares it. The row is the node's own; a change restyles the subtree's readers." } ], "_transitions": "The `transition` row is CSS `transition` (LLP 1002): count u8 (≤8), then per declaration property u8 (0 all, then 1 + `Property`: 1 translate, 2 scale, 3 rotate, 4 opacity, 5 height, 6 stroke-dashoffset, 7 r, 8 color, 9 background-color, 10 fill, 11 stroke, 12 cx, 13 cy, 14 x, 15 y, 16 rx, 17 ry, 18 border-top-color, 19 border-right-color, 20 border-bottom-color, 21 border-left-color, 22 -exact-tint-color, 23 box-shadow — LLP 1062; 24, box-shadow's colour alone, is refused; 25 font-weight, 26 font-stretch, 27 font-variation-settings — LLP 1019 §13 D10; 28 is CSS's `border-color` shorthand; 29 is a path's `d`, LLP 1055.000 D15; 30 is `filter`, LLP 1003.002), duration f32 s, delay f32 s, easing u8 (0 linear, 1 ease, 2 ease-in, 3 ease-out, 4 ease-in-out, 5 cubic-bezier + 4×f32, 6 steps + u16 count + u8 position, 7 spring + f32 stiffness/damping/mass, 8 linear() + u8 count + count×(f32 input, f32 output)). Its Rust type lives in exact-motion; the kernel owns the bytes.", diff --git a/kernel/tests/it/compare.rs b/kernel/tests/it/compare.rs index a384cf612..1246616fa 100644 --- a/kernel/tests/it/compare.rs +++ b/kernel/tests/it/compare.rs @@ -358,7 +358,7 @@ fn forms_outside_the_grammar_are_refused_by_name() { "em is not supported", ), ("max(env(safe-area-inset-middle), 1px)", "env() names"), - ("max(var(--inset), 1px)", "one custom property"), + ("max(var(--exact-inset), 1px)", "are the host's"), ("max(attr(x), 1px)", "the functions are"), ("max(1px, auto)", "take px"), ( diff --git a/kernel/tests/it/main.rs b/kernel/tests/it/main.rs index 00ff58540..2a5d380f7 100644 --- a/kernel/tests/it/main.rs +++ b/kernel/tests/it/main.rs @@ -53,6 +53,7 @@ mod paint; mod paragraph_stamp; mod presence; mod presented_height; +mod property_cost; mod reader; mod regions; mod rem; diff --git a/kernel/tests/it/property_cost.rs b/kernel/tests/it/property_cost.rs new file mode 100644 index 000000000..ba4ed4e57 --- /dev/null +++ b/kernel/tests/it/property_cost.rs @@ -0,0 +1,269 @@ +//! What custom properties cost (LLP 1123 D5), against the same tree with +//! literal lengths and with local-inset readers: 2,000 readers, each eight +//! boxes below the root that declares what they read; then changes no reader +//! sees, and a long chain of declarations. Ignored, since it times; run it +//! with +//! `cargo test --release -p exact-kernel --test it property_cost -- --ignored --nocapture`. + +use exact_kernel::{Kernel, NodeType, Offer, Op, StyleId, StyleProps, StyleValue}; +use std::time::{Duration, Instant}; + +const READERS: u32 = 2_000; +const DEPTH: u32 = 8; + +fn style(id: u32, rows: &[(StyleId, &str)]) -> Op { + let mut patch = StyleProps::default(); + for (row, text) in rows { + patch + .set_dynamic(*row, &StyleValue::Text((*text).into())) + .unwrap(); + } + Op::SetStyle { + id, + patch: Box::new(patch), + } +} + +/// The root (1) declares `declared`; each reader pads its top by `pad` +/// below a chain of `DEPTH` boxes of its own. +fn build(declared: Option<&str>, pad: &str) -> (Kernel, Vec) { + let mut k = Kernel::with_monospace(); + let mut ops = vec![Op::CreateView { + id: 1, + node_type: NodeType::View, + }]; + let mut root: Vec<(StyleId, &str)> = vec![(StyleId::Height, "844px")]; + if let Some(d) = declared { + root.push((StyleId::SafeAreaProperties, d)); + } + ops.push(style(1, &root)); + let (mut next, mut tops, mut readers) = (2, Vec::new(), Vec::new()); + for _ in 0..READERS { + let mut parent = 0; + for level in 0..=DEPTH { + ops.push(Op::CreateView { + id: next, + node_type: NodeType::View, + }); + if level == 0 { + tops.push(next); + } else { + ops.push(Op::SetChildren { + id: parent, + children: vec![next], + }); + } + parent = next; + next += 1; + } + ops.push(style( + parent, + &[(StyleId::PaddingTop, pad), (StyleId::Height, "1px")], + )); + readers.push(parent); + } + ops.push(Op::SetChildren { + id: 1, + children: tops, + }); + ops.push(Op::AttachRoot { id: 1 }); + k.apply(0, 1, &ops).unwrap(); + (k, readers) +} + +fn layout(k: &mut Kernel) { + k.compute_layout(1, Offer::definite(390.0, 844.0)).unwrap(); +} + +/// The median of `runs` timings of `f`. +fn median(runs: usize, mut f: impl FnMut() -> Duration) -> Duration { + let mut all: Vec = (0..runs).map(|_| f()).collect(); + all.sort(); + all[runs / 2] +} + +#[test] +#[ignore = "times; run with --release --ignored --nocapture"] +fn property_cost() { + let cases: [(&str, Option<&str>, &str); 4] = [ + ("literal 8px", None, "8px"), + ("var(--pad)", Some("--pad: 8px"), "var(--pad)"), + ( + "capture var(--top)", + Some("--top: var(--exact-safe-area-inset-top)"), + "var(--top)", + ), + ("local inset", None, "var(--exact-safe-area-inset-top)"), + ]; + for (name, declared, pad) in cases { + let build_time = median(9, || { + let t = Instant::now(); + let (mut k, _) = build(declared, pad); + layout(&mut k); + t.elapsed() + }); + let (mut k, readers) = build(declared, pad); + layout(&mut k); + let steady = median(21, || { + let t = Instant::now(); + layout(&mut k); + t.elapsed() + }); + // A change every reader sees: the declaration, the root's inset, or each literal + let mut flip = false; + let change = median(21, || { + flip = !flip; + let v = if flip { "9px" } else { "8px" }; + let t = Instant::now(); + match (declared, pad) { + (Some(d), _) if d.starts_with("--pad") => { + k.apply( + 0, + 2, + &[style( + 1, + &[(StyleId::SafeAreaProperties, &format!("--pad: {v}"))], + )], + ) + .unwrap(); + } + (Some(_), _) | (None, "var(--exact-safe-area-inset-top)") => { + let top = if flip { 9.0 } else { 8.0 }; + k.set_local_insets(1, Some([top, 0.0, 0.0, 0.0])).unwrap(); + } + _ => { + let ops: Vec = readers + .iter() + .map(|&r| style(r, &[(StyleId::PaddingTop, v)])) + .collect(); + k.apply(0, 2, &ops).unwrap(); + } + } + layout(&mut k); + t.elapsed() + }); + let y = k.node(*readers.last().unwrap()).unwrap(); + println!( + "{name:>20}: build+layout {build_time:>9.2?} steady layout {steady:>9.2?} change+layout {change:>9.2?} (last reader's content y {})", + y.frame.y + ); + } +} + +/// Changes no reader's value depends on: a declaration nobody reads, an +/// owner's inset under readers of a literal property, and a change hidden +/// below a nearer declaration of the same name. Each reports the commit and +/// the layout apart, with the nodes the commit touched and the frames the +/// layout changed. +#[test] +#[ignore = "times; run with --release --ignored --nocapture"] +fn property_cost_of_unseen_changes() { + let report = + |name: &str, k: &mut Kernel, change: &mut dyn FnMut(&mut Kernel, bool) -> Option| { + let (mut flip, mut commits, mut layouts, mut touched, mut moved) = + (false, Vec::new(), Vec::new(), None, 0); + for _ in 0..21 { + flip = !flip; + let t = Instant::now(); + touched = change(k, flip); + commits.push(t.elapsed()); + let t = Instant::now(); + moved = k + .compute_layout(1, Offer::definite(390.0, 844.0)) + .unwrap() + .changed + .len(); + layouts.push(t.elapsed()); + } + commits.sort(); + layouts.sort(); + let touched = touched.map_or("touched nodes unreported".into(), |n: usize| { + format!("{n} nodes touched") + }); + println!( + "{name:>34}: commit {:>9.2?} ({touched}) layout {:>9.2?} ({moved} frames changed)", + commits[10], layouts[10] + ); + }; + let (mut k, _) = build(Some("--pad: 8px; --unread: 1px"), "var(--pad)"); + layout(&mut k); + report("an unread declaration", &mut k, &mut |k, flip| { + let v = if flip { + "--pad: 8px; --unread: 2px" + } else { + "--pad: 8px; --unread: 1px" + }; + k.apply(0, 2, &[style(1, &[(StyleId::SafeAreaProperties, v)])]) + .unwrap() + .touched + .len() + .into() + }); + report("an inset under literal readers", &mut k, &mut |k, flip| { + let top = if flip { 9.0 } else { 8.0 }; + k.set_local_insets(1, Some([top, 0.0, 0.0, 0.0])).unwrap(); + // `set_local_insets` reports only whether any was + None + }); + // Each reader's chain declares --pad again at its top box + let (mut k, _) = build(Some("--pad: 8px"), "var(--pad)"); + let tops: Vec = (0..READERS) + .map(|i| { + style( + 2 + i * (DEPTH + 1), + &[(StyleId::SafeAreaProperties, "--pad: 6px")], + ) + }) + .collect(); + k.apply(0, 2, &tops).unwrap(); + layout(&mut k); + report( + "a change below nearer declarations", + &mut k, + &mut |k, flip| { + let v = if flip { "--pad: 9px" } else { "--pad: 8px" }; + k.apply(0, 3, &[style(1, &[(StyleId::SafeAreaProperties, v)])]) + .unwrap() + .touched + .len() + .into() + }, + ); + // For scale: a change every reader sees + let (mut k, _) = build(Some("--pad: 8px"), "var(--pad)"); + layout(&mut k); + report("a change every reader sees", &mut k, &mut |k, flip| { + let v = if flip { "--pad: 9px" } else { "--pad: 8px" }; + k.apply(0, 3, &[style(1, &[(StyleId::SafeAreaProperties, v)])]) + .unwrap() + .touched + .len() + .into() + }); +} + +/// A chain of declarations, each reading the one before twice: what one +/// reader's resolution costs as it grows, to the expansion bound. +#[test] +#[ignore = "times; run with --release --ignored --nocapture"] +fn property_cost_of_a_doubling_chain() { + for levels in [8, 12, 16] { + let mut declared = vec!["--p0: 1%".to_string()]; + for i in 1..=levels { + declared.push(format!( + "--p{i}: calc(var(--p{}) + env(safe-area-inset-top) + var(--p{}))", + i - 1, + i - 1 + )); + } + let declared = declared.join("; "); + let pad = format!("var(--p{levels}, 7px)"); + let build_time = median(9, || { + let t = Instant::now(); + let (mut k, _) = build(Some(&declared), &pad); + layout(&mut k); + t.elapsed() + }); + println!("{levels:>2} levels: build+layout of {READERS} readers {build_time:>9.2?}"); + } +} diff --git a/kernel/tests/it/style_dynamic.rs b/kernel/tests/it/style_dynamic.rs index e23df5a45..59871c50e 100644 --- a/kernel/tests/it/style_dynamic.rs +++ b/kernel/tests/it/style_dynamic.rs @@ -954,6 +954,7 @@ fn every_row_writes_its_own_field_and_no_other() { StyleValue::Text("blur(12px) saturate(1.14)".into()), StyleValue::Text("flip-block, flip-inline".into()), StyleValue::Text("\"wght\" 650".into()), + StyleValue::Text("--gap: 8px".into()), ]; let mut unwritten = Vec::new(); let base = StyleProps::default(); diff --git a/runner/src/agent/row.rs b/runner/src/agent/row.rs index b03b487a0..0dbaeb594 100644 --- a/runner/src/agent/row.rs +++ b/runner/src/agent/row.rs @@ -137,6 +137,7 @@ pub fn row_json(row: StyleId, v: RowValue<'_>, out: &mut String) { RowValue::AnimationTimeline(t) => quote(&t.css(), out), RowValue::AnimationRange(r) => quote(&r.css(), out), RowValue::TimelineScope(s) => quote(&s.css(), out), + RowValue::SafeAreaProperties(c) => quote(&c.css(), out), RowValue::TimelineName(n) => quote(&n.css(), out), RowValue::ViewTimelineInset(i) => quote(&i.css(), out), RowValue::PositionTryFallbacks(s) => quote(&s.css(), out),