From e05e0462af847514ebc01ab7ad0a969aee235773 Mon Sep 17 00:00:00 2001 From: codecaaron Date: Fri, 27 Nov 2026 23:30:07 -0500 Subject: [PATCH 01/13] test(extract): drop Rust unit tests and test-only hooks Keeps the 411 tests that drive the whole extraction or system-loading pipeline in process. Removes 36 unit test modules, the named unit subsets in analyze_css, engine and system-loader, the test-only helpers they used, six public functions with no production caller, and the PROBED, OPENINGS and DIRECTORY_READS instrumentation. Co-Authored-By: Claude Fable 5.2 --- .../crates/extractor/src/analyze_css.rs | 385 ---- .../extract/crates/extractor/src/assemble.rs | 114 - .../crates/extractor/src/assemble/config.rs | 139 -- .../extractor/src/assemble/source_edit.rs | 148 -- .../extract/crates/extractor/src/ast_store.rs | 22 - .../crates/extractor/src/builtin_aliases.rs | 46 - .../crates/extractor/src/chain_merge.rs | 268 --- .../crates/extractor/src/chain_walk.rs | 481 ---- .../crates/extractor/src/cross_file.rs | 118 - packages/extract/crates/extractor/src/css.rs | 1948 ----------------- .../crates/extractor/src/declarations.rs | 31 - .../crates/extractor/src/dynamic_meta.rs | 52 - packages/extract/crates/extractor/src/emit.rs | 105 - .../extract/crates/extractor/src/engine.rs | 96 +- packages/extract/crates/extractor/src/eval.rs | 901 -------- .../extract/crates/extractor/src/evaluator.rs | 308 --- .../extract/crates/extractor/src/facts.rs | 578 ----- .../crates/extractor/src/family_members.rs | 5 +- packages/extract/crates/extractor/src/flow.rs | 150 -- .../crates/extractor/src/forced_usage.rs | 225 -- .../extract/crates/extractor/src/identity.rs | 76 - packages/extract/crates/extractor/src/ids.rs | 69 - .../extract/crates/extractor/src/jsx_scan.rs | 1011 --------- packages/extract/crates/extractor/src/lib.rs | 10 - packages/extract/crates/extractor/src/link.rs | 134 -- .../extract/crates/extractor/src/owned_ast.rs | 36 - .../extract/crates/extractor/src/pipeline.rs | 207 -- .../crates/extractor/src/property_names.rs | 136 -- .../extract/crates/extractor/src/reconcile.rs | 443 ---- .../crates/extractor/src/runtime_assets.rs | 78 - .../crates/extractor/src/selector_group.rs | 73 - .../crates/extractor/src/selector_subject.rs | 53 - .../crates/extractor/src/static_value.rs | 42 - .../extract/crates/extractor/src/theme.rs | 1712 --------------- .../crates/extractor/src/transforms.rs | 466 ---- .../extractor/src/transforms/reference.rs | 141 -- .../crates/extractor/src/usage_facts.rs | 546 ----- .../crates/system-loader/src/executor.rs | 14 - .../extract/crates/system-loader/src/lib.rs | 948 -------- .../crates/system-loader/src/module_table.rs | 51 - .../crates/system-loader/src/resolution.rs | 170 -- 41 files changed, 2 insertions(+), 12534 deletions(-) diff --git a/packages/extract/crates/extractor/src/analyze_css.rs b/packages/extract/crates/extractor/src/analyze_css.rs index 1b4cc83b8..1de920ed7 100644 --- a/packages/extract/crates/extractor/src/analyze_css.rs +++ b/packages/extract/crates/extractor/src/analyze_css.rs @@ -1550,14 +1550,6 @@ fn runtime_imports_of(files: &BTreeMap, inputs: &CssInputs) - imports } -#[cfg(test)] -thread_local! { - /// Every base a probe looked up on this thread, for the coverage - /// contract between `prepare` and analysis. - pub(crate) static PROBED: std::cell::RefCell> = - const { std::cell::RefCell::new(std::collections::BTreeSet::new()) }; -} - /// The probes made over one analysed path set, by base. A probe reads only /// the set's keys and the inputs (extensions, evidence, system modules), /// which hold still while the scope is open, so its outcome holds for every @@ -1657,8 +1649,6 @@ fn probe_files(base: &str, files: &BTreeMap, inputs: &CssInputs) - fn probe_files_uncached(base: &str, files: &BTreeMap, inputs: &CssInputs) -> ProbeOutcome { use animus_system_loader::resolution::{extension_policy, Probe, Seen}; - #[cfg(test)] - PROBED.with(|probed| probed.borrow_mut().insert(base.to_string())); // The analyzed set is keyed by each file's own spelling, so a lookup is // exact: a specifier that differs only in case names no analyzed file. let policy = match &inputs.analysis_context.extensions { @@ -13056,25 +13046,6 @@ mod tests { out.diagnostics.iter().filter(|d| d.kind == kind).collect() } - /// Contract: a skip's record loses only the code its reason named, - /// wherever the reason put it, and keeps every other word. - #[test] - fn a_skip_loses_only_its_own_code() { - let code = "animus.selector.unsupported-subject"; - assert_eq!( - split_code(&format!("[skip] A: property 'k' — no subject ({code})")), - ("[skip] A: property 'k' — no subject".to_string(), Some(code.to_string())) - ); - assert_eq!( - split_code(&format!("[skip] A: property 'k' — no subject ({code}) in const 'held'")), - ("[skip] A: property 'k' — no subject in const 'held'".to_string(), Some(code.to_string())) - ); - assert_eq!( - split_code(&format!("[skip] A: property 'k' — Button (animus.tsx) (src/Card.tsx:3) ({code})")), - ("[skip] A: property 'k' — Button (animus.tsx) (src/Card.tsx:3)".to_string(), Some(code.to_string())) - ); - } - fn analyze_with_total_system_floor( entries: &[(&str, &str)], inputs: &CssInputs, @@ -13292,41 +13263,6 @@ mod tests { assert_eq!(out.missing_inputs, [], "{:?}", out.diagnostics); } - #[test] - fn component_order_excludes_unresolvable_extensions_and_sorts_parents_first() { - let counter = ParseCounter::new(0); - let mut files = BTreeMap::new(); - for (path, source) in [ - ( - "base.tsx", - "export const Base = ds.styles({ display: 'block' }).asElement('div');", - ), - ( - "child.tsx", - "export const Child = ds.styles({ display: 'flex' }).asElement('div');", - ), - ( - "skip.tsx", - "export const Skip = ds.styles({ display: 'grid' }).asElement('div');", - ), - ] { - let ast = OwnedAst::parse(path.to_string(), source.to_string(), &counter); - files.insert( - path.to_string(), - extract_file_facts_with_prefix(&ast, "animus"), - ); - } - - let parent_map = - FxHashMap::from_iter([("child.tsx::Child".to_string(), "base.tsx::Base".to_string())]); - let unresolvable_extensions = FxHashSet::from_iter(["skip.tsx::Skip".to_string()]); - - assert_eq!( - sorted_resolvable_component_ids(&files, &parent_map, &unresolvable_extensions, &mut Vec::new()), - vec!["base.tsx::Base", "child.tsx::Child"] - ); - } - /// Contract: extraction never drops a component silently over its /// extensions. A component on an extension cycle, or extending through a /// binding its module declares by more than one chain (`var A = …; const @@ -13359,102 +13295,6 @@ mod tests { assert!(output.css.contains("color: green"), "{}", output.css); } - #[test] - fn component_order_omits_cycles_and_keeps_survivors_sorted() { - let counter = ParseCounter::new(0); - let mut files = BTreeMap::new(); - for (path, source) in [ - ( - "cycle-a.tsx", - "export const CycleA = ds.styles({ display: 'block' }).asElement('div');", - ), - ( - "cycle-b.tsx", - "export const CycleB = ds.styles({ display: 'flex' }).asElement('div');", - ), - ( - "survivors.tsx", - "export const Z = ds.styles({ display: 'grid' }).asElement('div');\n\ - export const A = ds.styles({ display: 'inline' }).asElement('div');", - ), - ] { - let ast = OwnedAst::parse(path.to_string(), source.to_string(), &counter); - files.insert( - path.to_string(), - extract_file_facts_with_prefix(&ast, "animus"), - ); - } - - let parent_map = FxHashMap::from_iter([ - ( - "cycle-a.tsx::CycleA".to_string(), - "cycle-b.tsx::CycleB".to_string(), - ), - ( - "cycle-b.tsx::CycleB".to_string(), - "cycle-a.tsx::CycleA".to_string(), - ), - ]); - - assert_eq!( - sorted_resolvable_component_ids(&files, &parent_map, &FxHashSet::default(), &mut Vec::new()), - vec!["survivors.tsx::A", "survivors.tsx::Z"] - ); - } - - #[test] - fn import_source_resolution_follows_v1_order() { - let mut files: BTreeMap = BTreeMap::new(); - files.insert("src/ui/button.tsx".into(), ()); - files.insert("lib/theme.ts".into(), ()); - let mut inputs = CssInputs::default(); - inputs.path_aliases.push(AliasEntry { - pattern: "@ui/".into(), - replacement: "src/ui/".into(), - alias_type: AliasType::Prefix, - }); - inputs - .package_map - .insert("@corp/tokens".into(), "vendor/tokens.ts".into()); - - assert_eq!( - resolve_import_source("src/app.tsx", "./ui/button", &files, &inputs).as_deref(), - Some("src/ui/button.tsx") - ); - assert_eq!( - resolve_import_source("x.tsx", "@ui/button", &files, &inputs).as_deref(), - Some("src/ui/button.tsx") - ); - assert_eq!( - resolve_import_source("x.tsx", "@corp/tokens", &files, &inputs).as_deref(), - Some("vendor/tokens.ts") - ); - assert_eq!( - resolve_import_source("x.tsx", "not-mapped", &files, &inputs), - None - ); - } - - #[test] - fn node_next_specifiers_resolve_to_their_typescript_sources() { - let mut files: BTreeMap = BTreeMap::new(); - for path in ["src/signals.ts", "src/icon.tsx", "src/real.js", "src/real.ts", "src/m.mts"] { - files.insert(path.into(), ()); - } - let inputs = CssInputs::default(); - let resolve = |spec| resolve_import_source("src/app.tsx", spec, &files, &inputs); - - assert_eq!(resolve("./signals.js").as_deref(), Some("src/signals.ts")); - assert_eq!(resolve("./icon.js").as_deref(), Some("src/icon.tsx")); - assert_eq!(resolve("./real.js").as_deref(), Some("src/real.js")); - assert_eq!(resolve("./m.mjs").as_deref(), Some("src/m.mts")); - // Exact case, as Node, TypeScript and the hosts read it: `.JS` is no - // emitted `.js`. - assert_eq!(resolve("./signals.JS"), None); - assert_eq!(resolve("./icon.jsx").as_deref(), Some("src/icon.tsx")); - assert_eq!(resolve("./missing.js"), None); - } - #[test] fn base_css_flows_through_sheets_and_layers() { let out = analyze( @@ -13551,17 +13391,6 @@ mod tests { ); } - #[test] - fn external_file_containment_normalizes_windows_separators() { - let dirs = vec!["kit/src".to_string()]; - assert!(is_external_file("kit\\src\\Card.tsx", &dirs)); - assert!(is_external_file( - "kit/src/Card.tsx", - &["kit\\src".to_string()] - )); - assert!(!is_external_file("kit\\src-extra\\Card.tsx", &dirs)); - } - #[test] fn dev_mode_keeps_unused_components() { let mut inputs = test_inputs(); @@ -13900,29 +13729,6 @@ mod tests { assert_eq!(candidates[0].token.as_deref(), Some("colors.0")); } - #[test] - fn scale_key_shape_predicate_bounds() { - assert!(is_scale_key_shaped_value("externalAccent")); - assert!(is_scale_key_shaped_value("16")); - assert!(is_scale_key_shaped_value("accent.solid")); - assert!(is_scale_key_shaped_value("red")); - assert!(!is_scale_key_shaped_value("var(--x)")); - assert!(!is_scale_key_shaped_value("#fff")); - assert!(!is_scale_key_shaped_value("0 0 4px")); - assert!(!is_scale_key_shaped_value("-4")); - assert!(!is_scale_key_shaped_value("a..b")); - assert!(!is_scale_key_shaped_value("")); - } - - #[test] - fn is_external_file_requires_directory_boundary() { - let dirs = vec!["kit/src".to_string()]; - assert!(is_external_file("kit/src/Card.tsx", &dirs)); - assert!(!is_external_file("kit/srcx/Card.tsx", &dirs)); - assert!(!is_external_file("src/App.tsx", &dirs)); - assert!(!is_external_file("kit/src", &dirs)); - } - #[test] fn resolving_scale_key_does_not_warn() { let out = analyze( @@ -13978,61 +13784,6 @@ mod tests { assert!(diagnostics_of(&out, "warn").is_empty(), "{:?}", out.diagnostics); } - #[test] - fn token_shape_admits_only_bare_dotted_identifiers() { - assert!(is_token_shaped_value("accent.solid")); - assert!(is_token_shaped_value("colors.accent.solid-2")); - assert!(is_token_shaped_value("a.b")); - assert!(!is_token_shaped_value("red")); - assert!(!is_token_shaped_value("not-allowed")); - assert!(!is_token_shaped_value("2px solid accent.solid")); - assert!(!is_token_shaped_value("Inter, sans-serif")); - assert!(!is_token_shaped_value("var(--current-bg)")); - assert!(!is_token_shaped_value("url(a.png)")); - assert!(!is_token_shaped_value("\"a.b\"")); - assert!(!is_token_shaped_value("{colors.missing}")); - assert!(!is_token_shaped_value("--color-primary")); - assert!(!is_token_shaped_value("1.5rem")); - assert!(!is_token_shaped_value("transforms.")); - assert!(!is_token_shaped_value("a..b")); - assert!(!is_token_shaped_value(".leading")); - assert!(!is_token_shaped_value("")); - assert!(!is_token_shaped_value("こんにちは.solid")); - } - - #[test] - fn scale_family_covers_config_fan_out_and_color_pass_through() { - let inputs = CssInputs::from_json( - None, - None, - None, - Some( - r#"{"px": {"property": "padding", "properties": ["paddingLeft", "paddingRight"], "scale": "space"}, - "display": {"property": "display"}}"#, - ), - None, - None, - None, - None, - None, - None, - None, - None, - None, - false, - ) - .unwrap(); - let props = scale_family_css_properties(&inputs.config, &inputs.theme); - assert!(props.contains_key("padding")); - assert!(props.contains_key("padding-left")); - assert!(props.contains_key("padding-right")); - // Scale-less config entries carry no theme meaning. - assert!(!props.contains_key("display")); - // Color-family pass-throughs join without a propConfig entry. - assert!(props.contains_key("outline-color")); - assert!(props.contains_key("border-inline-start-color")); - } - #[test] fn brace_leak_shed_still_wins_over_token_warn() { // Exactly one warn: the shed pre-empts the token-shape warn. @@ -19025,14 +18776,6 @@ export const App = () => = [ - ("x.ts", "export const Root = ds.styles({ display: 'grid' }).asElement('div');".to_string()), - ("y.ts", "export const Root = ds.styles({ display: 'block' }).asElement('div');".to_string()), - ("a.ts", "export * as ns from './x';".to_string()), - ("b.ts", "export * as ns from './y';".to_string()), - ("both.ts", format!("export * from './a';\nexport * from './b';\n{root}")), - ("open.ts", format!("export * from './a';\nexport * from './missing';\n{root}")), - ("none.ts", format!("export const other = 1;\n{root}")), - ( - "app.ts", - "import { ns as amb } from './both';\nimport { ns as opn } from './open';\nimport { ns as abs } from './none';".to_string(), - ), - ] - .into_iter() - .map(|(path, source)| { - let ast = crate::owned_ast::OwnedAst::parse(path.to_string(), source, &counter); - (path.to_string(), crate::facts::extract_file_facts(&ast)) - }) - .collect(); - let inputs = test_inputs(); - let links = crate::link::ProjectLinks::link(&files, &inputs); - let evaluated: FxHashSet = - ["x.ts::Root", "y.ts::Root", "both.ts::Root", "open.ts::Root", "none.ts::Root"].into_iter().map(String::from).collect(); - let by_binding: IdsByBinding = - [("Root".to_string(), evaluated.iter().cloned().collect::>())].into_iter().collect(); - for tag in ["amb.Root", "opn.Root", "abs.Root"] { - let ids = resolve_usage_identity("app.ts", tag, &files, &inputs, &links, &evaluated, &by_binding); - assert!(ids.is_empty(), "{tag}: {ids:?}"); - } - } - - #[test] - fn an_exported_namespace_is_one_only_where_the_module_table_resolves_it() { - // Two stars bringing in different namespaces, or one beside an - // unresolved path, name no namespace. - let counter = crate::owned_ast::ParseCounter::new(0); - let files: BTreeMap = [ - ("x.ts", "export const X = 1;"), - ("y.ts", "export const Y = 1;"), - ("a.ts", "export * as ns from './x';"), - ("b.ts", "export * as ns from './y';"), - ("both.ts", "export * from './a';\nexport * from './b';"), - ("open.ts", "export * from './a';\nexport * from './missing';"), - ("one.ts", "export * from './a';"), - ("app.ts", "import { ns } from './both';\nimport { ns as only } from './one';"), - ] - .into_iter() - .map(|(path, source)| { - let ast = crate::owned_ast::OwnedAst::parse(path.to_string(), source.to_string(), &counter); - (path.to_string(), crate::facts::extract_file_facts(&ast)) - }) - .collect(); - let inputs = test_inputs(); - let links = crate::link::ProjectLinks::link(&files, &inputs); - let namespace = |module: &str| { - crate::family_members::namespace_export(module.to_string(), "ns".to_string(), &files, &inputs, &links) - }; - assert_eq!(namespace("both.ts"), None); - assert_eq!(namespace("open.ts"), None); - assert_eq!(namespace("one.ts"), Some("x.ts".to_string())); - // A named import of such a namespace holds the same answer. - let held = |local: &str| { - crate::family_members::local_namespace("app.ts", &files["app.ts"], local, &files, &inputs, &links) - }; - assert_eq!(held("ns"), None); - assert_eq!(held("only"), Some("x.ts".to_string())); - } - - #[test] - fn a_family_export_is_declared_only_where_the_module_table_resolves_it() { - // An ambiguous or open export declares nothing; only a resolved - // binding is declared, and never the first star's candidate. - let counter = crate::owned_ast::ParseCounter::new(0); - let files: BTreeMap = [ - ("a.ts", "export const X = 1;"), - ("b.ts", "export const X = 2;"), - ("both.ts", "export * from './a';\nexport * from './b';"), - ("open.ts", "export * from './a';\nexport * from './missing';"), - ("one.ts", "export * from './a';"), - ] - .into_iter() - .map(|(path, source)| { - let ast = crate::owned_ast::OwnedAst::parse(path.to_string(), source.to_string(), &counter); - (path.to_string(), crate::facts::extract_file_facts(&ast)) - }) - .collect(); - let links = crate::link::ProjectLinks::link(&files, &test_inputs()); - let declared = |module: &str| declared_export(module, "X".to_string(), &files, &links); - assert_eq!(declared("both.ts"), None); - assert_eq!(declared("open.ts"), None); - assert_eq!(declared("one.ts"), Some(("a.ts".to_string(), "X".to_string(), "X".to_string()))); - } - #[test] fn an_extension_parent_its_module_does_not_export_is_not_inherited() { // The module table resolves no export `Parent`: the import names @@ -20152,35 +19796,6 @@ export const App = () => = [ - ("r.tsx", format!("const R = {component};\nexport const Other = 1;\n")), - ("a.tsx", format!("export const X = {component};\n")), - ("b.tsx", format!("export const X = {component};\n")), - ("barrel.tsx", "export * from './a';\nexport * from './b';\n".to_string()), - ("app.tsx", "import * as ns from './r';\nimport { X } from './barrel';\n".to_string()), - ] - .into_iter() - .map(|(path, source)| { - let ast = crate::owned_ast::OwnedAst::parse(path.to_string(), source, &counter); - (path.to_string(), crate::facts::extract_file_facts(&ast)) - }) - .collect(); - let inputs = test_inputs(); - let links = crate::link::ProjectLinks::link(&files, &inputs); - let evaluated: FxHashSet = ["r.tsx::R", "a.tsx::X", "b.tsx::X"].into_iter().map(String::from).collect(); - assert!(resolve_identity("app.tsx", "ns.R", &files, &inputs, &links, &evaluated, None).is_empty()); - let mut declared = resolve_declared_identity("app.tsx", "X", &files, &inputs, &links, &evaluated); - declared.sort(); - assert_eq!(declared, ["a.tsx::X", "b.tsx::X"]); - } - #[test] fn direct_renders_still_prune_unused_options() { let app = "import { R } from './r';\nexport const App = () => ;\n"; diff --git a/packages/extract/crates/extractor/src/assemble.rs b/packages/extract/crates/extractor/src/assemble.rs index 4621eb072..de8731ae4 100644 --- a/packages/extract/crates/extractor/src/assemble.rs +++ b/packages/extract/crates/extractor/src/assemble.rs @@ -378,117 +378,3 @@ pub fn assemble_replacements( } Ok(out) } - -/// Fact construction shared by this module's and its submodules' tests. -#[cfg(test)] -pub(crate) mod test_support { - use crate::facts::{extract_file_facts, FileFacts}; - use crate::owned_ast::{OwnedAst, ParseCounter}; - - pub(crate) fn facts_for(path: &str, source: &str) -> FileFacts { - let counter = ParseCounter::new(0); - let ast = OwnedAst::parse(path.to_string(), source.to_string(), &counter); - extract_file_facts(&ast) - } -} - -#[cfg(test)] -mod tests { - use super::test_support::facts_for; - use super::*; - - #[test] - fn class_name_shape() { - let name = make_class_name("Box", "a.tsx::Box", "animus"); - assert!(name.starts_with("animus-Box-")); - assert_eq!(name.len(), "animus-Box-".len() + 8); - assert_eq!(content_hash("a"), content_hash("a")); - assert_ne!(content_hash("a"), content_hash("b")); - } - - #[test] - fn simple_element_replacement_matches_v1_shape() { - let facts = facts_for( - "a.tsx", - "export const Box = ds.styles({ p: 4 }).asElement('div');", - ); - let text = generate_replacement("a.tsx", &facts.chains[0], "animus", None, ConfigInputs { group_registry: &FxHashMap::default(), variant_options: false, trusted_factories: true }, &GeneratedNames::exports()).unwrap(); - let class = class_name_for("a.tsx", "Box", "animus"); - assert_eq!(text, format!("/* @__PURE__ */ createComponent('div', '{class}', {{}})")); - } - - #[test] - fn variants_compounds_states_config_is_sorted_and_shaped() { - let facts = facts_for( - "b.tsx", - r#"export const Btn = ds - .variant({ prop: 'size', variants: { sm: {}, lg: {} }, defaultVariant: 'sm' }) - .compound({ variant: 'ghost', size: 'sm' }, { p: 1 }) - .states({ loading: {} }) - .asElement('button');"#, - ); - let text = generate_replacement("b.tsx", &facts.chains[0], "animus", None, ConfigInputs { group_registry: &FxHashMap::default(), variant_options: false, trusted_factories: true }, &GeneratedNames::exports()).unwrap(); - // Compound conditions are sorted (size before variant) for - // determinism. - assert!(text.contains(r#""conditions":{"size":"sm","variant":"ghost"}"#), "got {text}"); - // Contract: an emitted variant config carries no options list for - // the official runtime, which reads only the prop and its default; - // a custom runtime's carries the list. - assert!(text.contains(r#""variants":{"size":{"default":"sm"}}"#), "got {text}"); - let custom = generate_replacement("b.tsx", &facts.chains[0], "animus", None, ConfigInputs { group_registry: &FxHashMap::default(), variant_options: true, trusted_factories: true }, &GeneratedNames::exports()).unwrap(); - assert!(custom.contains(r#""variants":{"size":{"options":["sm","lg"],"default":"sm"}}"#), "got {custom}"); - assert!(text.contains(r#""states":["loading"]"#)); - // A positional compound name is the runtime's to derive. - assert!(!text.contains("--compound-0"), "got {text}"); - } - - #[test] - fn system_stage_fails_loud_pending_config() { - let facts = facts_for( - "c.tsx", - "export const Box = ds.system({ space: true }).asElement('div');", - ); - let err = generate_replacement("c.tsx", &facts.chains[0], "animus", None, ConfigInputs { group_registry: &FxHashMap::default(), variant_options: false, trusted_factories: true }, &GeneratedNames::exports()).unwrap_err(); - match err { - AssembleError::NeedsConfig(msg) => assert!(msg.contains("row 07")), - } - } - - #[test] - fn class_resolver_shape() { - let facts = facts_for("d.tsx", "export const card = ds.styles({ p: 8 }).asClass();"); - let text = generate_replacement("d.tsx", &facts.chains[0], "animus", None, ConfigInputs { group_registry: &FxHashMap::default(), variant_options: false, trusted_factories: true }, &GeneratedNames::exports()).unwrap(); - assert!(text.starts_with("/* @__PURE__ */ createClassResolver('animus-card-"), "got {text}"); - } - - /// Contract: an emitted component factory call carries a pure - /// annotation, and a user expression is never covered by one. The - /// factories are pure at construction; the arguments Animus emits are - /// literals, generated names and captured callbacks (a function or arrow - /// expression, or an identifier). An asComponent target read through a - /// member path can run a getter, so that call stays unmarked, and so does - /// every call into a custom runtimeImport. - #[test] - fn emitted_factory_calls_are_pure_and_never_cover_a_user_expression() { - let replacement = |file: &str, source: &str| { - let facts = facts_for(file, source); - generate_replacement(file, &facts.chains[0], "animus", None, ConfigInputs { group_registry: &FxHashMap::default(), variant_options: false, trusted_factories: true }, &GeneratedNames::exports()).unwrap() - }; - for (file, source) in [ - ("a.tsx", "export const Box = ds.styles({ p: 4 }).asElement('div');"), - ("b.tsx", "import { Link } from 'router';\nexport const Anchor = ds.styles({ p: 4 }).asComponent(Link);"), - ("c.tsx", "export const card = ds.styles({ p: 8 }).asClass();"), - ] { - let text = replacement(file, source); - assert!(text.starts_with(PURE_ANNOTATION), "unmarked: {text}"); - assert_eq!(text.matches("@__PURE__").count(), 1, "{text}"); - } - let member = replacement("d.tsx", "import { motion } from 'motion';\nexport const Fade = ds.styles({ p: 4 }).asComponent(motion.div);"); - assert!(!member.contains("@__PURE__"), "a member target is marked: {member}"); - assert!(member.starts_with("createComponent(motion.div,"), "{member}"); - // A custom runtimeImport's factories may register what they make. - let facts = facts_for("e.tsx", "export const card = ds.styles({ p: 8 }).asClass();"); - let custom = generate_replacement("e.tsx", &facts.chains[0], "animus", None, ConfigInputs { group_registry: &FxHashMap::default(), variant_options: true, trusted_factories: false }, &GeneratedNames::exports()).unwrap(); - assert!(custom.starts_with("createClassResolver("), "a custom runtime's call is marked: {custom}"); - } -} diff --git a/packages/extract/crates/extractor/src/assemble/config.rs b/packages/extract/crates/extractor/src/assemble/config.rs index b220e8934..b799eeea0 100644 --- a/packages/extract/crates/extractor/src/assemble/config.rs +++ b/packages/extract/crates/extractor/src/assemble/config.rs @@ -521,142 +521,3 @@ impl ObjectLiteral { out } } - -#[cfg(test)] -mod tests { - use std::collections::HashMap; - - use super::super::test_support::facts_for; - use super::*; - use crate::dynamic_meta::{DeclarationPropMeta, DynamicPropMeta, ValuePropMeta}; - - fn value_meta(name: &str) -> ValuePropMeta { - ValuePropMeta { - var_name: format!("--animus-{name}"), - slot_class: format!("animus-dyn-{name}"), - property: "width".into(), - negative: false, - strict: false, - keywords: Vec::new(), - properties: Vec::new(), - transform_name: None, - transform_id: None, - transform_fn_source: None, - scale_values: BTreeMap::new(), - current_var: None, - production_conditions: None, - declared_numeric: false, - tables: Default::default(), - } - } - - fn config_for(source: &str, payload: &ReplacementPayload) -> String { - let facts = facts_for("box.tsx", source); - let registry: FxHashMap> = - [("space".to_string(), vec!["p".to_string(), "m".to_string()])].into_iter().collect(); - build_config( - "box.tsx", - "Box", - &facts.chains[0], - "animus", - Some(payload), - super::super::ConfigInputs { group_registry: ®istry, variant_options: false, trusted_factories: true }, - &super::super::GeneratedNames::exports(), - ) - .unwrap() - } - - #[test] - fn config_object_carries_every_field_in_order() { - let sized = ValuePropMeta { - negative: true, - strict: true, - keywords: vec!["auto".into()], - properties: vec!["width".into(), "height".into()], - transform_name: Some("size".into()), - transform_id: Some("theme.ts#size".into()), - scale_values: [("sm".to_string(), json!("4px"))].into_iter().collect(), - current_var: Some("--current-size".into()), - production_conditions: None, - ..value_meta("sized") - }; - let lifted = ValuePropMeta { - transform_fn_source: Some("(v) => v * 2".into()), - ..value_meta("lift") - }; - let tone = DeclarationPropMeta { - kind: "declarations", - slot_class: "animus-dyn-tone".into(), - member_vars: [("color".to_string(), "--animus-tone-color".to_string())].into_iter().collect(), - declaration_scale_values: BTreeMap::new(), - production_conditions: None, - tables: Default::default(), - }; - let payload = ReplacementPayload { - system_prop_names: vec!["bg".into(), "p".into()], - system_group_names: vec!["space".into()], - custom_prop_class_map: Some(HashMap::from([( - "sized".to_string(), - HashMap::from([("sm".to_string(), "animus-uc-1".to_string())]), - )])), - custom_dynamic_config: Some(HashMap::from([ - ("sized".to_string(), DynamicPropMeta::Value(sized)), - ("lift".to_string(), DynamicPropMeta::Value(lifted)), - ("tone".to_string(), DynamicPropMeta::Declarations(tone)), - ])), - typed_custom_props: vec!["sized".into()], - reads_typed_system_props: true, - ..ReplacementPayload::default() - }; - let config = config_for( - "export const Box = ds.variant({ prop: 'size', variants: { sm: {} } }).states({ busy: {} }).asElement('div');", - &payload, - ); - assert_eq!( - config, - concat!( - r#"{"variants":{"size":{}},"states":["busy"],"#, - r#""systemPropNames":[].concat(systemPropGroups.space,["bg","lift","sized","tone"]),"#, - r#""customPropMap":{"sized":{"sm":"animus-uc-1"}},"#, - r#""typedCustomProps":["sized"],"#, - r#""typedSystemProps":typedSystemProps,"#, - r#""customDynamicConfig":{"#, - r#""lift":{"varName":"--animus-lift","slotClass":"animus-dyn-lift","property":"width","transform":(v) => v * 2},"#, - r#""sized":{"varName":"--animus-sized","slotClass":"animus-dyn-sized","property":"width","#, - r#""properties":["width","height"],"negative":true,"strict":true,"keywords":["auto"],"#, - r#""transformName":"size","transform":transforms["theme.ts#size"],"scaleValues":{"sm":"4px"},"#, - r#""currentVar":"--current-size"},"#, - r#""tone":{"kind":"declarations","slotClass":"animus-dyn-tone","#, - r#""memberVars":{"color":"--animus-tone-color"},"declarationScaleValues":{}}}}"#, - ) - ); - } - - #[test] - fn config_object_without_variants_starts_from_its_first_field() { - let plain = "export const Box = ds.styles({}).asElement('div');"; - let names_only = ReplacementPayload { - system_prop_names: vec!["bg".into()], - reads_typed_system_props: true, - ..ReplacementPayload::default() - }; - assert_eq!( - config_for(plain, &names_only), - r#"{"systemPropNames":["bg"],"typedSystemProps":typedSystemProps}"# - ); - let groups_only = ReplacementPayload { - system_prop_names: vec!["p".into()], - system_group_names: vec!["space".into()], - ..ReplacementPayload::default() - }; - assert_eq!( - config_for(plain, &groups_only), - r#"{"systemPropNames":[].concat(systemPropGroups.space)}"# - ); - let typed_only = ReplacementPayload { - typed_custom_props: vec!["sized".into()], - ..ReplacementPayload::default() - }; - assert_eq!(config_for(plain, &typed_only), r#"{"typedCustomProps":["sized"]}"#); - } -} diff --git a/packages/extract/crates/extractor/src/assemble/source_edit.rs b/packages/extract/crates/extractor/src/assemble/source_edit.rs index 24ecf288e..5be4bec63 100644 --- a/packages/extract/crates/extractor/src/assemble/source_edit.rs +++ b/packages/extract/crates/extractor/src/assemble/source_edit.rs @@ -192,151 +192,3 @@ pub fn directive_and_imports( None => (import_lines.to_string(), Vec::new()), } } - -#[cfg(test)] -mod tests { - use super::*; - use crate::assemble::test_support::facts_for; - - fn directive_and_imports_for( - source: &str, - import_lines: &str, - needs_use_client: bool, - ) -> (String, Vec<(u32, u32)>) { - let facts = facts_for("directive.tsx", source); - directive_and_imports( - source, - import_lines, - needs_use_client, - facts.directive_prologue.as_ref(), - ) - } - - fn directive_prefix_and_body_for( - source: String, - needs_use_client: bool, - ) -> (String, String) { - let facts = facts_for("directive.tsx", &source); - directive_prefix_and_body( - source, - needs_use_client, - facts.directive_prologue.as_ref(), - ) - } - - #[test] - fn strip_semantics_match_v1_line_quirks() { - let src = "import { A, B } from './x';\nimport {\n C,\n} from './y';\nimport { D, E } from './x';\nconst k = 1;\n"; - let removals = - consumed_import_removals(src, &["./x", "./y"], &["A", "B", "D"]); - // Line 1: all extracted → removed. The multi-line ./y import is - // never stripped. The D,E line keeps E, so it stays. - assert_eq!(removals.len(), 1); - assert_eq!(removals[0].0, 0); - let out = crate::emit::apply_plan( - src, - &crate::emit::EmissionPlan { removals, ..Default::default() }, - ) - .unwrap(); - assert!(!out.code.contains("{ A, B }")); - assert!(out.code.contains("C,")); - assert!(out.code.contains("{ D, E }")); - } - - #[test] - fn directive_at_offset_zero_moves_above_imports() { - let src = "'use client';\nconst x = 1;\n"; - let (prepend, removals) = - directive_and_imports_for(src, "import Z from 'z';\n", false); - let out = crate::emit::apply_plan( - src, - &crate::emit::EmissionPlan { prepend, removals, ..Default::default() }, - ) - .unwrap(); - assert!(out.code.starts_with("'use client';\nimport Z from 'z';\nconst x = 1;")); - } - - #[test] - fn comment_preceded_directive_keeps_prologue_above_imports() { - let src = "// note\n'use client';\nconst x = 1;\n"; - let (prepend, removals) = - directive_and_imports_for(src, "import Z from 'z';\n", false); - let out = crate::emit::apply_plan( - src, - &crate::emit::EmissionPlan { prepend, removals, ..Default::default() }, - ) - .unwrap(); - assert!( - out.code - .starts_with("// note\n'use client';\nimport Z from 'z';\nconst x = 1;"), - "got {}", - out.code - ); - } - - #[test] - fn prologue_prefix_comment_then_directive() { - let (prefix, rest) = directive_prefix_and_body_for( - "// note\n'use client';\nconst x = 1;\n".to_string(), - false, - ); - assert_eq!(prefix, "// note\n'use client';\n"); - assert_eq!(rest, "const x = 1;\n"); - } - - #[test] - fn prologue_prefix_blank_line_then_directive() { - let (prefix, rest) = directive_prefix_and_body_for( - "\n\n'use client';\nconst x = 1;\n".to_string(), - false, - ); - assert_eq!(prefix, "\n\n'use client';\n"); - assert_eq!(rest, "const x = 1;\n"); - } - - #[test] - fn prologue_prefix_directive_then_blank_line_strips_one_blank() { - let (prefix, rest) = directive_prefix_and_body_for( - "'use client';\n\nimport { ds } from './x';\n".to_string(), - false, - ); - assert_eq!(prefix, "'use client';\n"); - assert_eq!(rest, "import { ds } from './x';\n"); - } - - #[test] - fn prologue_recognizes_multiple_directives_and_block_comments() { - let (prefix, rest) = directive_prefix_and_body_for( - "/* header */\n'use strict';\n// mid\n\"use client\"\nconst x = 1;\n".to_string(), - false, - ); - assert_eq!(prefix, "/* header */\n'use strict';\n// mid\n\"use client\"\n"); - assert_eq!(rest, "const x = 1;\n"); - } - - #[test] - fn non_directive_string_is_not_a_prologue() { - // A string literal in expression position is not a directive, nor - // is one consumed by a member expression. - let (prefix, rest) = - directive_prefix_and_body_for("const s = 'use client';\n".to_string(), false); - assert_eq!(prefix, ""); - assert_eq!(rest, "const s = 'use client';\n"); - let (prefix, _) = - directive_prefix_and_body_for( - "'use client'.length;\nconst x = 1;\n".to_string(), - false, - ); - assert_eq!(prefix, ""); - } - - #[test] - fn needs_use_client_appends_below_existing_prologue() { - let (prefix, rest) = directive_prefix_and_body_for( - "'use strict';\nconst x = 1;\n".to_string(), - true, - ); - assert_eq!(prefix, "'use strict';\n'use client';\n"); - assert_eq!(rest, "const x = 1;\n"); - } -} diff --git a/packages/extract/crates/extractor/src/ast_store.rs b/packages/extract/crates/extractor/src/ast_store.rs index 76ea6a14a..bf74e1e9d 100644 --- a/packages/extract/crates/extractor/src/ast_store.rs +++ b/packages/extract/crates/extractor/src/ast_store.rs @@ -73,25 +73,3 @@ impl AstStore { self.asts.par_iter_mut().zip(inputs).map(|(ast, input)| step(ast, input)).collect() } } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn n_files_parse_exactly_n_times() { - let entries: Vec = (0..8) - .map(|i| FileEntry { - path: format!("f{i}.tsx"), - source: format!("export const C{i} =
;"), - }) - .collect(); - let store = AstStore::build(entries); - assert_eq!(store.len(), 8); - assert_eq!(store.parse_count(), 8); - // Reading every program re-parses nothing. - let total: usize = store.iter().map(|a| a.program().body.len()).sum(); - assert_eq!(total, 8); - assert_eq!(store.parse_count(), 8); - } -} diff --git a/packages/extract/crates/extractor/src/builtin_aliases.rs b/packages/extract/crates/extractor/src/builtin_aliases.rs index 42a2cc0cf..3c86fd8f2 100644 --- a/packages/extract/crates/extractor/src/builtin_aliases.rs +++ b/packages/extract/crates/extractor/src/builtin_aliases.rs @@ -95,49 +95,3 @@ pub fn is_built_in_condition(name: &str, value: &Value) -> bool { built_in == name && *value == json!({ "value": condition, "order": order, "kind": kind }) }) } - -#[cfg(test)] -mod tests { - use crate::analyze_css::CssInputs; - - /// One of the table's two maps, as its JSON. - fn json_part(key: &str) -> String { - let all: serde_json::Value = serde_json::from_str(&super::json()).unwrap(); - all[key].to_string() - } - - fn fingerprint(selectors: Option<&str>, conditions: Option<&str>) -> String { - CssInputs::from_json(None, None, None, None, None, selectors, conditions, None, None, None, None, None, None, false) - .unwrap() - .system_fingerprint("animus") - } - - /// Contract: the system fingerprint leaves out each built-in alias a - /// system keeps unchanged, so a system holding every built-in, one, or - /// none names its classes alike, and an Animus version that adds a - /// built-in renames no class. A custom alias and a built-in it - /// overrides still name them; the maps' order does not. - #[test] - fn the_fingerprint_leaves_unchanged_built_in_aliases_out() { - let none = fingerprint(None, None); - let empty = fingerprint(Some("{}"), Some("{}")); - let all = fingerprint(Some(&json_part("selectors")), Some(&json_part("conditions"))); - let one = fingerprint( - Some(r#"{"_hover":"&:hover"}"#), - Some(r#"{"_print":{"value":"@media print","order":320,"kind":"media"}}"#), - ); - assert_eq!(empty, all); - assert_eq!(empty, one); - assert_ne!(none, empty, "no alias map at all is not an empty one"); - let custom = fingerprint(Some(r#"{"_hover":"&:hover","_groupHover":".group:hover &"}"#), Some("{}")); - let overridden = fingerprint(Some(r#"{"_hover":"&:hover:not(:active)"}"#), Some("{}")); - let condition = fingerprint(Some("{}"), Some(r#"{"_print":{"value":"@media print","order":500,"kind":"media"}}"#)); - assert_ne!(custom, empty); - assert_ne!(overridden, empty); - assert_ne!(condition, empty, "a built-in at another order is no built-in"); - // The maps' order is no part of it: a team's alias that a later - // Animus builds in under its name moves in the serialized order. - let reordered = fingerprint(Some(r#"{"_b":"& b","_a":"& a"}"#), Some("{}")); - assert_eq!(reordered, fingerprint(Some(r#"{"_a":"& a","_b":"& b"}"#), Some("{}"))); - } -} diff --git a/packages/extract/crates/extractor/src/chain_merge.rs b/packages/extract/crates/extractor/src/chain_merge.rs index eb3d273d5..c8107026f 100644 --- a/packages/extract/crates/extractor/src/chain_merge.rs +++ b/packages/extract/crates/extractor/src/chain_merge.rs @@ -357,271 +357,3 @@ pub fn topological_sort(nodes: &[ProvenanceNode]) -> TopoResult { TopoResult::Sorted(sorted) } - -/// Merge a parent and child component config field by field: parent-only -/// fields survive, shared fields deep-merge with the child winning. -#[cfg(test)] -pub fn merge_chain_configs( - parent_config: &FxHashMap, - child_config: &FxHashMap, -) -> FxHashMap { - let empty_obj = Value::Object(Map::new()); - let mut merged: FxHashMap = FxHashMap::default(); - - let all_keys: FxHashSet<&String> = parent_config.keys().chain(child_config.keys()).collect(); - - for key in all_keys { - let parent_val = parent_config.get(key).unwrap_or(&empty_obj); - let child_val = child_config.get(key); - - let result = match child_val { - Some(cv) => deep_merge(parent_val, cv), - None => parent_val.clone(), - }; - - merged.insert(key.clone(), result); - } - - merged -} - -#[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - - #[test] - fn merge_flat_objects() { - let parent = json!({ "a": 1, "b": 2 }); - let child = json!({ "b": 3, "c": 4 }); - let result = deep_merge(&parent, &child); - assert_eq!(result, json!({ "a": 1, "b": 3, "c": 4 })); - } - - #[test] - fn merge_nested_objects() { - let parent = json!({ "a": { "x": 1 } }); - let child = json!({ "a": { "y": 2 } }); - let result = deep_merge(&parent, &child); - assert_eq!(result, json!({ "a": { "x": 1, "y": 2 } })); - } - - #[test] - fn child_overrides_scalar() { - let parent = json!({ "a": 1 }); - let child = json!({ "a": 2 }); - let result = deep_merge(&parent, &child); - assert_eq!(result, json!({ "a": 2 })); - } - - #[test] - fn child_replaces_array() { - let parent = json!({ "a": [1, 2] }); - let child = json!({ "a": [3] }); - let result = deep_merge(&parent, &child); - assert_eq!(result, json!({ "a": [3] })); - } - - #[test] - fn child_changes_type() { - let parent = json!({ "a": 1 }); - let child = json!({ "a": { "x": 2 } }); - let result = deep_merge(&parent, &child); - assert_eq!(result, json!({ "a": { "x": 2 } })); - } - - #[test] - fn parent_only_keys_preserved() { - let parent = json!({ "a": 1, "b": 2 }); - let child = json!({ "a": 3 }); - let result = deep_merge(&parent, &child); - assert_eq!(result, json!({ "a": 3, "b": 2 })); - } - - #[test] - fn deep_nested_merge() { - let parent = json!({ "a": { "b": { "x": 1, "y": 2 } } }); - let child = json!({ "a": { "b": { "y": 99, "z": 3 } } }); - let result = deep_merge(&parent, &child); - assert_eq!(result, json!({ "a": { "b": { "x": 1, "y": 99, "z": 3 } } })); - } - - #[test] - fn empty_parent() { - let parent = json!({}); - let child = json!({ "a": 1 }); - let result = deep_merge(&parent, &child); - assert_eq!(result, json!({ "a": 1 })); - } - - #[test] - fn empty_child() { - let parent = json!({ "a": 1 }); - let child = json!({}); - let result = deep_merge(&parent, &child); - assert_eq!(result, json!({ "a": 1 })); - } - - fn node(id: &str, parent: Option<&str>) -> ProvenanceNode { - ProvenanceNode { - component_id: id.to_string(), - parent_id: parent.map(|s| s.to_string()), - } - } - - #[test] - fn sorts_simple_chain() { - let nodes = vec![node("C", Some("B")), node("B", Some("A")), node("A", None)]; - match topological_sort(&nodes) { - TopoResult::Sorted(order) => { - let a = order.iter().position(|x| x == "A").unwrap(); - let b = order.iter().position(|x| x == "B").unwrap(); - let c = order.iter().position(|x| x == "C").unwrap(); - assert!(a < b, "A must come before B"); - assert!(b < c, "B must come before C"); - } - TopoResult::Cycle(..) => panic!("expected sorted result"), - } - } - - #[test] - fn sorts_forest() { - let nodes = vec![ - node("A", None), - node("B", Some("A")), - node("C", None), - node("D", Some("C")), - ]; - match topological_sort(&nodes) { - TopoResult::Sorted(order) => { - assert_eq!(order.len(), 4); - let a = order.iter().position(|x| x == "A").unwrap(); - let b = order.iter().position(|x| x == "B").unwrap(); - let c = order.iter().position(|x| x == "C").unwrap(); - let d = order.iter().position(|x| x == "D").unwrap(); - assert!(a < b, "A must come before B"); - assert!(c < d, "C must come before D"); - } - TopoResult::Cycle(..) => panic!("expected sorted result"), - } - } - - #[test] - fn detects_cycle() { - let nodes = vec![node("A", Some("B")), node("B", Some("A"))]; - match topological_sort(&nodes) { - TopoResult::Cycle(cycle, _) => { - assert!(cycle.contains(&"A".to_string()) || cycle.contains(&"B".to_string())); - } - TopoResult::Sorted(_) => panic!("expected cycle detection"), - } - } - - #[test] - fn roots_first() { - let nodes = vec![node("B", Some("A")), node("A", None)]; - match topological_sort(&nodes) { - TopoResult::Sorted(order) => { - let a = order.iter().position(|x| x == "A").unwrap(); - let b = order.iter().position(|x| x == "B").unwrap(); - assert!(a < b, "A (root) must come before B (child)"); - } - TopoResult::Cycle(..) => panic!("expected sorted result"), - } - } - - #[test] - fn single_node() { - let nodes = vec![node("A", None)]; - match topological_sort(&nodes) { - TopoResult::Sorted(order) => { - assert_eq!(order, vec!["A".to_string()]); - } - TopoResult::Cycle(..) => panic!("expected sorted result"), - } - } - - fn make_config(entries: &[(&str, Value)]) -> FxHashMap { - entries - .iter() - .map(|(k, v)| (k.to_string(), v.clone())) - .collect() - } - - #[test] - fn merges_base_styles() { - let parent = make_config(&[("baseStyles", json!({ "padding": "8px" }))]); - let child = make_config(&[("baseStyles", json!({ "color": "red" }))]); - let result = merge_chain_configs(&parent, &child); - assert_eq!( - result["baseStyles"], - json!({ "padding": "8px", "color": "red" }) - ); - } - - #[test] - fn merges_variants_additively() { - let parent = make_config(&[( - "variants", - json!({ "size": { "sm": { "fontSize": "12px" } } }), - )]); - let child = make_config(&[( - "variants", - json!({ "color": { "blue": { "color": "blue" } } }), - )]); - let result = merge_chain_configs(&parent, &child); - assert!(result["variants"]["size"].is_object()); - assert!(result["variants"]["color"].is_object()); - } - - #[test] - fn child_overrides_variant_option() { - let parent = make_config(&[( - "variants", - json!({ "fill": { "bg": "blue" } }), - )]); - let child = make_config(&[( - "variants", - json!({ "fill": { "bg": "green" } }), - )]); - let result = merge_chain_configs(&parent, &child); - assert_eq!(result["variants"]["fill"]["bg"], json!("green")); - } - - #[test] - fn merges_groups() { - let parent = make_config(&[("activeGroups", json!({ "space": true }))]); - let child = make_config(&[("activeGroups", json!({ "color": true }))]); - let result = merge_chain_configs(&parent, &child); - assert_eq!(result["activeGroups"]["space"], json!(true)); - assert_eq!(result["activeGroups"]["color"], json!(true)); - } - - #[test] - fn child_only_field() { - let parent = make_config(&[("baseStyles", json!({ "display": "flex" }))]); - let child = make_config(&[( - "statesConfig", - json!({ "loading": { "opacity": 0 } }), - )]); - let result = merge_chain_configs(&parent, &child); - assert!(result.contains_key("statesConfig")); - assert_eq!(result["statesConfig"]["loading"]["opacity"], json!(0)); - assert!(result.contains_key("baseStyles")); - } - - #[test] - fn parent_only_field_preserved() { - let parent = make_config(&[ - ("baseStyles", json!({ "padding": "4px" })), - ("custom", json!({ "size": { "property": "flexBasis" } })), - ]); - let child = make_config(&[("baseStyles", json!({ "color": "blue" }))]); - let result = merge_chain_configs(&parent, &child); - assert!(result.contains_key("custom")); - assert_eq!( - result["custom"]["size"]["property"], - json!("flexBasis") - ); - } -} diff --git a/packages/extract/crates/extractor/src/chain_walk.rs b/packages/extract/crates/extractor/src/chain_walk.rs index 153b6b835..601ffb062 100644 --- a/packages/extract/crates/extractor/src/chain_walk.rs +++ b/packages/extract/crates/extractor/src/chain_walk.rs @@ -134,484 +134,3 @@ pub struct ObjectMemberChain { pub key: String, pub root: String, } - -#[cfg(test)] -mod tests { - use super::*; - use crate::owned_ast::OwnedAst; - - fn parse_chains(source: &str) -> Vec { - let counter = crate::owned_ast::ParseCounter::new(0); - let ast = OwnedAst::parse("test.tsx".into(), source.into(), &counter); - walk_program(ast.program()) - } - - #[test] - fn finds_simple_styles_chain() { - let chains = parse_chains( - r#" - import { animus } from '@animus-ui/core'; - const Box = animus.styles({ display: 'flex' }).asElement('div'); - "#, - ); - assert_eq!(chains.len(), 1); - let chain = &chains[0]; - assert_eq!(chain.binding, "Box"); - assert_eq!(chain.terminal, TerminalKind::AsElement); - assert_eq!(chain.tag, "div"); - assert_eq!(chain.stages.len(), 1); - assert_eq!(chain.stages[0].method, "styles"); - assert!(chain.extractable); - assert_eq!(chain.extends_from, None); - } - - #[test] - fn finds_styles_variant_chain() { - let chains = parse_chains( - r#" - import { animus } from '@animus-ui/core'; - const Btn = animus - .styles({ p: 0 }) - .variant({ variants: { fill: { bg: 'blue' } } }) - .asElement('button'); - "#, - ); - assert_eq!(chains.len(), 1); - let chain = &chains[0]; - assert_eq!(chain.binding, "Btn"); - assert_eq!(chain.tag, "button"); - assert_eq!(chain.stages.len(), 2); - assert_eq!(chain.stages[0].method, "styles"); - assert_eq!(chain.stages[1].method, "variant"); - assert!(chain.extractable); - assert_eq!(chain.extends_from, None); - } - - #[test] - fn groups_is_extractable() { - let chains = parse_chains( - r#" - import { animus } from '@animus-ui/core'; - const Box = animus - .styles({ display: 'flex' }) - .system({ layout: true }) - .asElement('div'); - "#, - ); - assert_eq!(chains.len(), 1); - assert!(chains[0].extractable); - assert!(chains[0] - .stages - .iter() - .any(|s| s.method == "system")); - assert_eq!(chains[0].extends_from, None); - } - - #[test] - fn extracts_as_component_on_primary_chain() { - let chains = parse_chains( - r#" - import { animus } from '@animus-ui/core'; - const FlowLink = animus - .styles({ fontWeight: 400 }) - .asComponent(Link); - "#, - ); - assert_eq!(chains.len(), 1); - assert!(chains[0].extractable); - assert_eq!(chains[0].terminal, TerminalKind::AsComponent); - assert_eq!(chains[0].tag, "Link"); - assert_eq!(chains[0].extends_from, None); - } - - #[test] - fn extracts_as_component_with_inline_as_assertion() { - let chains = parse_chains( - r#" - import { animus } from '@animus-ui/core'; - const FlowLink = animus - .styles({ fontWeight: 400 }) - .asComponent(Link as React.ComponentType); - "#, - ); - assert_eq!(chains.len(), 1); - assert!(chains[0].extractable); - assert_eq!(chains[0].tag, "Link"); - } - - #[test] - fn extracts_as_component_with_satisfies_assertion() { - let chains = parse_chains( - r#" - import { animus } from '@animus-ui/core'; - const FlowLink = animus - .styles({ fontWeight: 400 }) - .asComponent(Link satisfies LinkLike); - "#, - ); - assert_eq!(chains.len(), 1); - assert!(chains[0].extractable); - assert_eq!(chains[0].tag, "Link"); - } - - #[test] - fn extracts_as_element_with_const_assertion() { - let chains = parse_chains( - r#" - import { animus } from '@animus-ui/core'; - const Box = animus.styles({ display: 'flex' }).asElement('div' as const); - "#, - ); - assert_eq!(chains.len(), 1); - assert!(chains[0].extractable); - assert_eq!(chains[0].tag, "div"); - } - - #[test] - fn extracts_as_component_with_static_member_target() { - let chains = parse_chains( - r#" - import { animus } from '@animus-ui/core'; - const Wrapped = animus.styles({ p: 8 }).asComponent(Compound.Item); - "#, - ); - assert_eq!(chains.len(), 1); - assert!(chains[0].extractable); - assert_eq!(chains[0].tag, "Compound.Item"); - } - - #[test] - fn extracts_as_component_with_asserted_static_member_target() { - let chains = parse_chains( - r#" - import { animus } from '@animus-ui/core'; - const Wrapped = animus - .styles({ p: 8 }) - .asComponent(Compound.Item as unknown as typeof Compound.Item); - "#, - ); - assert_eq!(chains.len(), 1); - assert!(chains[0].extractable); - assert_eq!(chains[0].tag, "Compound.Item"); - } - - #[test] - fn extracts_deep_static_member_paths_with_inner_assertions() { - let chains = parse_chains( - r#" - import { animus } from '@animus-ui/core'; - const Wrapped = animus - .styles({ p: 8 }) - .asComponent((Ns as any).Compound.Item); - "#, - ); - assert_eq!(chains.len(), 1); - assert!(chains[0].extractable); - assert_eq!(chains[0].tag, "Ns.Compound.Item"); - } - - #[test] - fn bails_on_computed_member_as_component_target() { - // Computed access bails even with a literal key. - let chains = parse_chains( - r#" - import { animus } from '@animus-ui/core'; - const Wrapped = animus.styles({ p: 8 }).asComponent(Compound['Item']); - "#, - ); - assert_eq!(chains.len(), 1); - assert!(!chains[0].extractable); - assert!(chains[0] - .bail_reason - .as_deref() - .unwrap_or_default() - .contains("static identifier or member path")); - assert_ne!(chains[0].tag, "unknown"); - } - - #[test] - fn bails_on_unresolvable_as_component_target() { - // An unresolvable target must bail to the runtime path: a placeholder - // identifier would emit `createComponent(unknown, …)` and throw. - let chains = parse_chains( - r#" - import { animus } from '@animus-ui/core'; - const FlowLink = animus - .styles({ fontWeight: 400 }) - .asComponent(withRouter(Link)); - "#, - ); - assert_eq!(chains.len(), 1); - assert!(!chains[0].extractable); - assert!(chains[0] - .bail_reason - .as_deref() - .unwrap_or_default() - .contains("asComponent")); - assert_ne!(chains[0].tag, "unknown"); - } - - #[test] - fn finds_multiple_chains() { - let chains = parse_chains( - r#" - import { animus } from '@animus-ui/core'; - const A = animus.styles({ p: 0 }).asElement('div'); - const B = animus.styles({ m: 0 }).asElement('span'); - "#, - ); - assert_eq!(chains.len(), 2); - assert_eq!(chains[0].binding, "A"); - assert_eq!(chains[1].binding, "B"); - assert_eq!(chains[0].extends_from, None); - assert_eq!(chains[1].extends_from, None); - } - - #[test] - fn finds_exported_chains() { - let chains = parse_chains( - r#" - import { animus } from '@animus-ui/core'; - export const Box = animus.styles({ display: 'flex' }).asElement('div'); - "#, - ); - assert_eq!(chains.len(), 1); - assert_eq!(chains[0].binding, "Box"); - assert_eq!(chains[0].extends_from, None); - } - - #[test] - fn extracts_binding_name() { - let chains = parse_chains( - r#" - import { animus } from '@animus-ui/core'; - const ButtonContainer = animus.styles({ p: 0 }).asElement('button'); - "#, - ); - assert_eq!(chains[0].binding, "ButtonContainer"); - assert_eq!(chains[0].extends_from, None); - } - - #[test] - fn props_is_extractable() { - let chains = parse_chains( - r#" - import { animus } from '@animus-ui/core'; - const Cell = animus - .styles({ py: 12 }) - .props({ size: { property: 'flexBasis' } }) - .asElement('div'); - "#, - ); - assert_eq!(chains.len(), 1); - assert!(chains[0].extractable); - assert!(chains[0] - .stages - .iter() - .any(|s| s.method == "props")); - assert_eq!(chains[0].extends_from, None); - } - - #[test] - fn handles_states() { - let chains = parse_chains( - r#" - import { animus } from '@animus-ui/core'; - const Layout = animus - .styles({ position: 'relative' }) - .states({ loading: { opacity: 0 } }) - .asElement('div'); - "#, - ); - assert_eq!(chains.len(), 1); - assert!(chains[0].extractable); - assert_eq!(chains[0].stages.len(), 2); - assert_eq!(chains[0].stages[1].method, "states"); - assert_eq!(chains[0].extends_from, None); - } - - #[test] - fn ignores_non_animus_code() { - let chains = parse_chains( - r#" - const x = 1; - const y = someOtherLib.method().build(); - function foo() { return 42; } - "#, - ); - assert_eq!(chains.len(), 0); - } - - #[test] - fn still_bails_on_extend() { - let chains = parse_chains( - r#" - import { animus } from '@animus-ui/core'; - const Extended = animus - .styles({ display: 'flex' }) - .extend(BaseStyles) - .asElement('div'); - "#, - ); - assert_eq!(chains.len(), 1); - assert!(!chains[0].extractable); - assert!(chains[0] - .bail_reason - .as_ref() - .unwrap() - .contains("extend")); - } - - #[test] - fn groups_and_styles_extractable() { - let chains = parse_chains( - r#" - import { animus } from '@animus-ui/core'; - const Box = animus - .styles({ display: 'flex' }) - .system({ layout: true }) - .asElement('div'); - "#, - ); - assert_eq!(chains.len(), 1); - assert!(chains[0].extractable); - assert_eq!(chains[0].stages.len(), 2); - assert_eq!(chains[0].stages[0].method, "styles"); - assert_eq!(chains[0].stages[1].method, "system"); - assert_eq!(chains[0].extends_from, None); - } - - #[test] - fn extension_chain_recognized() { - let chains = parse_chains( - r#" - const Extended = Button.extend().styles({ borderRadius: 8 }).asElement('button'); - "#, - ); - assert_eq!(chains.len(), 1); - let chain = &chains[0]; - assert_eq!(chain.binding, "Extended"); - assert_eq!(chain.terminal, TerminalKind::AsElement); - assert_eq!(chain.tag, "button"); - assert!(chain.extractable); - assert_eq!(chain.extends_from, Some("Button".to_string())); - assert_eq!(chain.stages.len(), 1); - assert_eq!(chain.stages[0].method, "styles"); - } - - #[test] - fn extension_chain_with_as_component() { - let chains = parse_chains( - r#" - const NavLink = Link.extend().states({ active: { fontWeight: 700 } }).asComponent(NextLink); - "#, - ); - assert_eq!(chains.len(), 1); - let chain = &chains[0]; - assert_eq!(chain.binding, "NavLink"); - assert_eq!(chain.terminal, TerminalKind::AsComponent); - assert_eq!(chain.tag, "NextLink"); - assert!(chain.extractable); - assert_eq!(chain.extends_from, Some("Link".to_string())); - assert_eq!(chain.stages.len(), 1); - assert_eq!(chain.stages[0].method, "states"); - } - - #[test] - fn extension_chain_extends_from_set() { - let chains = parse_chains( - r#" - const Child = Anchor.extend().styles({ color: 'blue' }).asElement('a'); - "#, - ); - assert_eq!(chains.len(), 1); - assert_eq!(chains[0].extends_from, Some("Anchor".to_string())); - } - - #[test] - fn primary_chain_as_component_is_extractable() { - let chains = parse_chains( - r#" - import { animus } from '@animus-ui/core'; - const StyledLink = animus.styles({ color: 'blue' }).asComponent(Link); - "#, - ); - assert_eq!(chains.len(), 1); - assert!(chains[0].extractable); - assert_eq!(chains[0].terminal, TerminalKind::AsComponent); - assert_eq!(chains[0].tag, "Link"); - assert_eq!(chains[0].extends_from, None); - } - - #[test] - fn extend_with_args_still_bails() { - let chains = parse_chains( - r#" - import { animus } from '@animus-ui/core'; - const Extended = animus.styles({ p: 0 }).extend(Base).asElement('div'); - "#, - ); - assert_eq!(chains.len(), 1); - assert!(!chains[0].extractable); - assert!(chains[0] - .bail_reason - .as_ref() - .unwrap() - .contains("extend")); - } - - #[test] - fn extension_and_primary_in_same_file() { - let chains = parse_chains( - r#" - import { animus } from '@animus-ui/core'; - const A = animus.styles({ display: 'flex' }).asElement('div'); - const B = A.extend().styles({ color: 'red' }).asElement('div'); - "#, - ); - assert_eq!(chains.len(), 2); - - let a = &chains[0]; - assert_eq!(a.binding, "A"); - assert!(a.extractable); - assert_eq!(a.extends_from, None); - - let b = &chains[1]; - assert_eq!(b.binding, "B"); - assert!(b.extractable); - assert_eq!(b.extends_from, Some("A".to_string())); - assert_eq!(b.stages.len(), 1); - assert_eq!(b.stages[0].method, "styles"); - } - - #[test] - fn bails_on_unknown_method() { - let chains = parse_chains( - r#" - import { animus } from '@animus-ui/core'; - const Box = animus.styles({ display: 'flex' }).unknownMethod({}).asElement('div'); - "#, - ); - assert_eq!(chains.len(), 1); - let chain = &chains[0]; - assert!(!chain.extractable); - assert!(chain - .bail_reason - .as_ref() - .unwrap() - .contains("unknown chain method")); - } - - #[test] - fn bails_on_unknown_method_in_extension() { - let chains = parse_chains( - r#" - const Button2 = Button.extend().styles({ color: 'blue' }).futureAPI({}).asElement('button'); - "#, - ); - assert_eq!(chains.len(), 1); - let chain = &chains[0]; - assert!(!chain.extractable); - assert!(chain.bail_reason.is_some()); - } -} diff --git a/packages/extract/crates/extractor/src/cross_file.rs b/packages/extract/crates/extractor/src/cross_file.rs index cff8479b1..3567119b5 100644 --- a/packages/extract/crates/extractor/src/cross_file.rs +++ b/packages/extract/crates/extractor/src/cross_file.rs @@ -194,121 +194,3 @@ pub fn resolve_cross_file( state_names, } } - -#[cfg(test)] -mod tests { - use super::*; - use crate::facts::extract_file_facts; - use crate::owned_ast::{OwnedAst, ParseCounter}; - - fn project(entries: &[(&str, &str)]) -> BTreeMap { - let counter = ParseCounter::new(0); - entries - .iter() - .map(|(path, source)| { - let ast = OwnedAst::parse(path.to_string(), source.to_string(), &counter); - (path.to_string(), extract_file_facts(&ast)) - }) - .collect() - } - - #[test] - fn metadata_collection_does_not_depend_on_usage() { - let files = project(&[( - "facts.tsx", - "export const Card = ds.variant({ prop: 'tone', variants: { quiet: {}, loud: {} } }).states({ selected: {} }).asClass();\nconst Root = ds.styles({}).asElement('div');\nexport const Family = compose({ Root }, { shared: {} });", - )]); - - let metadata = collect_component_metadata(&files); - - assert!(metadata.component_names.contains("Card")); - assert!(metadata.component_names.contains("Root")); - assert!(metadata.class_resolvers.contains("Card")); - assert!(metadata.slot_bindings.contains("Root")); - assert!(metadata.variant_options["Card"]["tone"].contains("quiet")); - assert!(metadata.state_names["Card"].contains("selected")); - } - - #[test] - fn non_object_states_do_not_create_empty_metadata() { - let files = project(&[( - "facts.tsx", - "const STATES = 'not-an-object';\nexport const Card = ds.states(STATES).asClass();", - )]); - - let metadata = collect_component_metadata(&files); - - assert!(!metadata.state_names.contains_key("Card")); - } - - #[test] - fn rendered_usage_resolves_from_collected_metadata() { - let files = project(&[ - ( - "button.tsx", - "export const Button = ds.styles({ p: 4 }).asElement('button');", - ), - ( - "app.tsx", - "import { Button as TestButton } from './button';\nexport const App = () => ;", - ), - ]); - let metadata = collect_component_metadata(&files); - - let rendered = collect_rendered_components(&files, &metadata); - - assert!(rendered.contains("TestButton")); - assert!(!rendered.contains("Button")); - } - - #[test] - fn alias_import_renders_under_local_name() { - let files = project(&[ - ( - "button.tsx", - "export const Button = ds.styles({ p: 4 }).asElement('button');", - ), - ( - "app.tsx", - "import { Button as TestButton } from './button';\nexport const App = () => ;", - ), - ]); - let cf = resolve_cross_file(&files, BTreeMap::new()); - assert!(cf.rendered_components.contains("TestButton")); - assert!(!cf.rendered_components.contains("Button")); - } - - #[test] - fn as_class_and_compose_slots_render_unconditionally() { - let files = project(&[( - "mix.tsx", - "export const card = ds.styles({ p: 8 }).asClass();\nconst Root = ds.styles({}).asElement('div');\nexport const Fam = compose({ Root }, { shared: {} });", - )]); - let cf = resolve_cross_file(&files, BTreeMap::new()); - assert!(cf.rendered_components.contains("card")); - assert!(cf.rendered_components.contains("Root")); - } - - #[test] - fn variant_and_state_configs_derive_from_facts() { - let files = project(&[( - "btn.tsx", - "export const Btn = ds\n .variant({ prop: 'size', variants: { sm: {}, lg: {} } })\n .states({ loading: {}, disabled: {} })\n .asElement('button');", - )]); - let cf = resolve_cross_file(&files, BTreeMap::new()); - let opts = &cf.variant_options["Btn"]["size"]; - assert!(opts.contains("sm") && opts.contains("lg")); - assert!(cf.state_names["Btn"].contains("loading")); - } - - #[test] - fn member_tags_resolve_and_bailed_chains_do_not_register() { - let files = project(&[( - "fam.tsx", - "const Root = ds.styles({}).asElement('div');\nexport const Fam = compose({ Root }, { shared: {} });\nexport const Bad = ds.mystery({ x: 1 }).asElement('div');\nexport const App = () => ;", - )]); - let cf = resolve_cross_file(&files, BTreeMap::new()); - assert!(cf.rendered_components.contains("Root")); - assert!(!cf.component_names.contains("Bad")); - } -} diff --git a/packages/extract/crates/extractor/src/css.rs b/packages/extract/crates/extractor/src/css.rs index ef25b3035..80260c2df 100644 --- a/packages/extract/crates/extractor/src/css.rs +++ b/packages/extract/crates/extractor/src/css.rs @@ -427,49 +427,6 @@ fn layer_declaration() -> String { format!("@layer {};", layer_order().join(", ")) } -pub fn generate_css( - components: &[ComponentCss], - breakpoints: &BreakpointMap, -) -> String { - let mut output = String::new(); - - writeln!(output, "{}", layer_declaration()).unwrap(); - writeln!(output).unwrap(); - - let base_css = generate_layer_content(components, breakpoints, LayerKind::Base); - if !base_css.is_empty() { - writeln!(output, "@layer {} {{", layer_name("base")).unwrap(); - output.push_str(&base_css); - writeln!(output, "}}").unwrap(); - writeln!(output).unwrap(); - } - - let variants_css = generate_layer_content(components, breakpoints, LayerKind::Variants); - if !variants_css.is_empty() { - writeln!(output, "@layer {} {{", layer_name("variants")).unwrap(); - output.push_str(&variants_css); - writeln!(output, "}}").unwrap(); - writeln!(output).unwrap(); - } - - let compounds_css = generate_layer_content(components, breakpoints, LayerKind::Compounds); - if !compounds_css.is_empty() { - writeln!(output, "@layer {} {{", layer_name("compounds")).unwrap(); - output.push_str(&compounds_css); - writeln!(output, "}}").unwrap(); - writeln!(output).unwrap(); - } - - let states_css = generate_layer_content(components, breakpoints, LayerKind::States); - if !states_css.is_empty() { - writeln!(output, "@layer {} {{", layer_name("states")).unwrap(); - output.push_str(&states_css); - writeln!(output, "}}").unwrap(); - } - - output -} - /// `components` arrive in emission order, each with its `file::binding` id. pub fn generate_css_sheets_ordered( components: &[(String, ComponentCss)], @@ -581,50 +538,6 @@ pub fn generate_css_sheets_ordered( (sheets, fragments) } -enum LayerKind { - Base, - Variants, - Compounds, - States, -} - -fn generate_layer_content( - components: &[ComponentCss], - breakpoints: &BreakpointMap, - kind: LayerKind, -) -> String { - let mut output = String::new(); - - for component in components { - match kind { - LayerKind::Base => { - if let Some(base) = &component.base { - write_rule_block(&mut output, &component.class_name, base, breakpoints); - } - } - LayerKind::Variants => { - for (selector, styles) in component.variant_rules() { - write_rule_block(&mut output, &selector, styles, breakpoints); - } - } - LayerKind::Compounds => { - for (index, styles) in component.compounds.iter().enumerate() { - let selector = compound_class(&component.class_name, index); - write_rule_block(&mut output, &selector, styles, breakpoints); - } - } - LayerKind::States => { - for (state_name, styles) in &component.states { - let selector = format!("{}--{}", component.class_name, state_name); - write_rule_block(&mut output, &selector, styles, breakpoints); - } - } - } - } - - output -} - fn write_rule_block( output: &mut String, selector: &str, @@ -2076,1864 +1989,3 @@ pub fn slot_property_registrations<'a>( } names.iter().map(|name| format!("@property {name} {{ syntax: \"*\"; inherits: false; }}\n")).collect() } - -#[cfg(test)] -mod tests { - use rustc_hash::FxHashSet; - - use super::*; - use crate::theme::{ - Condition, ConditionAliasesMap, ConditionEmitOrder, ConditionedGroup, ContextualVarsMap, - SelectorAliasesMap, VariableMap, - }; - - fn empty_vars() -> VariableMap { - FxHashMap::default() - } - - #[test] - fn unit_fallback_predicts_only_bare_numbers() { - for (value, property) in [ - ("8", "padding"), - ("8 16", "margin"), - ("0 -4", "margin"), - ("+5", "margin"), - ("2 solid #333", "border"), - ] { - assert!(unit_fallback_rewrites(value, property), "{property}: {value}"); - } - for (value, property) in [ - ("#b1b1b7", "color"), - ("1px solid #333", "border"), - ("0px 0px 0px 1px #000", "box-shadow"), - ("\"ss01\"", "font-feature-settings"), - ("\"\\\"1\\\"\"", "content"), - ("U+0025-00FF", "unicode-range"), - ("'1'", "content"), - ("Inter4, sans-serif", "font-family"), - ("calc(100% - 16)", "width"), - ("8", "--gap"), - ("1.5", "line-height"), - ] { - assert!(!unit_fallback_rewrites(value, property), "{property}: {value}"); - } - } - - fn test_breakpoints() -> BreakpointMap { - let mut bp = FxHashMap::default(); - bp.insert("xs".to_string(), 480); - bp.insert("sm".to_string(), 768); - bp.insert("md".to_string(), 1024); - bp.insert("lg".to_string(), 1200); - bp.insert("xl".to_string(), 1440); - BreakpointMap::new(bp) - } - - struct TestUtilCtx { - config: PropConfigMap, - theme: FlatTheme, - vars: VariableMap, - ctx_vars: ContextualVarsMap, - bp_keys: FxHashSet, - aliases: SelectorAliasesMap, - conditions: ConditionAliasesMap, - } - - impl TestUtilCtx { - fn new(config: PropConfigMap, theme: FlatTheme, bp: &BreakpointMap) -> Self { - Self { - config, - theme, - vars: empty_vars(), - ctx_vars: ContextualVarsMap::default(), - bp_keys: bp.breakpoints.keys().cloned().collect(), - aliases: SelectorAliasesMap::default(), - conditions: ConditionAliasesMap::default(), - } - } - - fn ctx(&self) -> ResolveContext<'_> { - ResolveContext { - config: &self.config, - theme: &self.theme, - variable_map: &self.vars, - contextual_vars: &self.ctx_vars, - breakpoint_keys: &self.bp_keys, - selector_aliases: &self.aliases, - condition_aliases: &self.conditions, - transform_evaluator: None, - transform_failures: None, - token_misses: None, - dropped_keys: None, - numeric_properties: None, - numbers_take_px: false, - } - } - } - - fn container_group(prelude: &str, prop: &str, value: &str) -> ConditionedGroup { - ConditionedGroup::single( - Condition::Container(prelude.to_string()), - vec![CssDeclaration { property: prop.to_string(), value: value.to_string() }], - ConditionEmitOrder::Raw(0), - ) - } - - #[test] - fn condition_block_admitted_into_class_hash() { - let base = ResolvedStyles { - declarations: vec![CssDeclaration { property: "display".into(), value: "grid".into() }], - ..Default::default() - }; - let with_condition = ResolvedStyles { - declarations: vec![CssDeclaration { property: "display".into(), value: "grid".into() }], - conditioned: vec![container_group("@container (min-width: 400px)", "padding", "1rem")], - ..Default::default() - }; - let h_base = canonical_css_for_hash(&base); - let h_cond = canonical_css_for_hash(&with_condition); - assert_ne!(h_base, h_cond, "condition block must change the canonical hash input"); - assert_ne!(content_hash(&h_base), content_hash(&h_cond)); - } - - #[test] - fn different_condition_preludes_hash_differently() { - let a = ResolvedStyles { - conditioned: vec![container_group("@container (min-width: 400px)", "padding", "1rem")], - ..Default::default() - }; - let b = ResolvedStyles { - conditioned: vec![container_group("@container (min-width: 800px)", "padding", "1rem")], - ..Default::default() - }; - assert_ne!(canonical_css_for_hash(&a), canonical_css_for_hash(&b)); - } - - #[test] - fn write_rule_block_nests_condition_inside_layer_order() { - let styles = ResolvedStyles { - declarations: vec![CssDeclaration { property: "display".into(), value: "flex".into() }], - pseudo_selectors: vec![( - ":hover".into(), - vec![CssDeclaration { property: "color".into(), value: "red".into() }], - Default::default(), - )], - conditioned: vec![ - ConditionedGroup::breakpoint( - "sm", - vec![CssDeclaration { property: "gap".into(), value: "1rem".into() }], - ), - container_group("@container (min-width: 400px)", "font-size", "18px"), - ], - }; - let mut out = String::new(); - write_rule_block(&mut out, "animus-Box-abcd", &styles, &test_breakpoints()); - - let p_decl = out.find("display: flex").unwrap(); - let p_hover = out.find(":hover").unwrap(); - let p_mq = out.find("@media (min-width: 768px)").unwrap(); - let p_cont = out.find("@container (min-width: 400px)").unwrap(); - assert!(p_decl < p_hover, "declarations before pseudos"); - assert!(p_hover < p_mq, "pseudos before breakpoint MQ"); - assert!(p_mq < p_cont, "breakpoint MQ before condition"); - assert!(out.contains("@container (min-width: 400px) {\n .animus-Box-abcd {\n font-size: 18px;")); - } - - #[test] - fn emission_ordering_proof_declarations_pseudo_breakpoint_aliased_raw() { - let styles = ResolvedStyles { - declarations: vec![CssDeclaration { property: "display".into(), value: "flex".into() }], - pseudo_selectors: vec![( - ":hover".into(), - vec![CssDeclaration { property: "color".into(), value: "red".into() }], - Default::default(), - )], - conditioned: vec![ - ConditionedGroup::single( - Condition::Supports("@supports (display: grid)".into()), - vec![CssDeclaration { property: "display".into(), value: "grid".into() }], - ConditionEmitOrder::Raw(0), - ), - ConditionedGroup::single( - Condition::Media("@media (prefers-reduced-motion: reduce)".into()), - vec![CssDeclaration { property: "transition".into(), value: "none".into() }], - ConditionEmitOrder::Aliased(500), - ), - ConditionedGroup::breakpoint( - "sm", - vec![CssDeclaration { property: "gap".into(), value: "1rem".into() }], - ), - ], - }; - let mut out = String::new(); - write_rule_block(&mut out, "animus-Box-abcd", &styles, &test_breakpoints()); - - let ordered_markers = [ - "display: flex", - ":hover", - "@media (min-width: 768px)", - "@media (prefers-reduced-motion: reduce)", - "@supports (display: grid)", - ]; - let mut last = 0usize; - for marker in ordered_markers { - let pos = out.find(marker).unwrap_or_else(|| panic!("missing marker {marker} in:\n{out}")); - assert!(pos >= last, "marker {marker} out of order in:\n{out}"); - last = pos; - } - assert_eq!( - out, - " .animus-Box-abcd {\n display: flex;\n }\n\ - \x20 .animus-Box-abcd:hover {\n color: red;\n }\n\ - \x20 @media (min-width: 768px) {\n .animus-Box-abcd {\n gap: 1rem;\n }\n }\n\ - \x20 @media (prefers-reduced-motion: reduce) {\n .animus-Box-abcd {\n transition: none;\n }\n }\n\ - \x20 @supports (display: grid) {\n .animus-Box-abcd {\n display: grid;\n }\n }\n" - ); - } - - #[test] - fn generates_base_layer() { - let components = vec![ComponentCss { - variant_order: Vec::new(), - class_name: "animus-Box-abcd1234".to_string(), - base: Some(ResolvedStyles { - declarations: vec![ - CssDeclaration { - property: "padding".to_string(), - value: "0".to_string(), - }, - CssDeclaration { - property: "display".to_string(), - value: "inline-flex".to_string(), - }, - ], - pseudo_selectors: vec![], - conditioned: vec![], - }), - variants: vec![], - compounds: vec![], - states: vec![], - }]; - - let css = generate_css(&components, &test_breakpoints()); - assert!(css.contains("@layer anm-global, anm-base, anm-variants, anm-compounds, anm-states, anm-system, anm-custom;")); - assert!(css.contains("@layer anm-base {")); - assert!(css.contains(".animus-Box-abcd1234 {")); - assert!(css.contains("padding: 0;")); - assert!(css.contains("display: inline-flex;")); - } - - #[test] - fn generates_variant_layer() { - let components = vec![ComponentCss { - variant_order: Vec::new(), - class_name: "animus-Btn-1234abcd".to_string(), - base: None, - variants: vec![VariantCss { - prop: "variant".to_string(), - default_option: None, - options: vec![ - ( - "fill".to_string(), - ResolvedStyles { - declarations: vec![CssDeclaration { - property: "color".to_string(), - value: "var(--colors-background)".to_string(), - }], - pseudo_selectors: vec![], - conditioned: vec![], - }, - ), - ( - "stroke".to_string(), - ResolvedStyles { - declarations: vec![CssDeclaration { - property: "border".to_string(), - value: "1px solid".to_string(), - }], - pseudo_selectors: vec![], - conditioned: vec![], - }, - ), - ], - }], - compounds: vec![], - states: vec![], - }]; - - let css = generate_css(&components, &test_breakpoints()); - assert!(css.contains("@layer anm-variants {")); - assert!(css.contains(".animus-Btn-1234abcd--variant-fill {")); - assert!(css.contains(".animus-Btn-1234abcd--variant-stroke {")); - } - - #[test] - fn generates_state_layer() { - let components = vec![ComponentCss { - variant_order: Vec::new(), - class_name: "animus-Layout-deadbeef".to_string(), - base: None, - variants: vec![], - compounds: vec![], - states: vec![( - "loading".to_string(), - ResolvedStyles { - declarations: vec![CssDeclaration { - property: "opacity".to_string(), - value: "0".to_string(), - }], - pseudo_selectors: vec![], - conditioned: vec![], - }, - )], - }]; - - let css = generate_css(&components, &test_breakpoints()); - assert!(css.contains("@layer anm-states {")); - assert!(css.contains(".animus-Layout-deadbeef--loading {")); - assert!(css.contains("opacity: 0;")); - } - - #[test] - fn generates_pseudo_selectors() { - let components = vec![ComponentCss { - variant_order: Vec::new(), - class_name: "animus-Btn-aabb".to_string(), - base: Some(ResolvedStyles { - declarations: vec![], - pseudo_selectors: vec![( - ":hover".to_string(), - vec![CssDeclaration { - property: "color".to_string(), - value: "var(--colors-primary)".to_string(), - }], - Default::default(), - )], - conditioned: vec![], - }), - variants: vec![], - compounds: vec![], - states: vec![], - }]; - - let css = generate_css(&components, &test_breakpoints()); - assert!(css.contains(".animus-Btn-aabb:hover {")); - assert!(css.contains("color: var(--colors-primary);")); - } - - #[test] - fn generates_responsive_media() { - let components = vec![ComponentCss { - variant_order: Vec::new(), - class_name: "animus-Box-ccdd".to_string(), - base: Some(ResolvedStyles { - declarations: vec![CssDeclaration { - property: "font-size".to_string(), - value: "1rem".to_string(), - }], - pseudo_selectors: vec![], - conditioned: vec![ConditionedGroup::breakpoint( - "sm", - vec![CssDeclaration { - property: "font-size".to_string(), - value: "1.125rem".to_string(), - }], - )], - }), - variants: vec![], - compounds: vec![], - states: vec![], - }]; - - let css = generate_css(&components, &test_breakpoints()); - assert!(css.contains("font-size: 1rem;")); - assert!(css.contains("@media (min-width: 768px)")); - assert!(css.contains("font-size: 1.125rem;")); - } - - #[test] - fn content_hash_stable() { - let h1 = content_hash("test input"); - let h2 = content_hash("test input"); - assert_eq!(h1, h2); - assert_eq!(h1.len(), 8); - } - - #[test] - fn content_hash_unique() { - let h1 = content_hash("input a"); - let h2 = content_hash("input b"); - assert_ne!(h1, h2); - } - - /// The class attribute keeps a binding or option name as written; its - /// selector escapes what CSS would read as syntax. - #[test] - fn make_class_name_format() { - let name = make_class_name("ButtonContainer", "some-chain-data", "animus"); - assert!(name.starts_with("animus-ButtonContainer-")); - assert_eq!(name.len(), "animus-ButtonContainer-".len() + 8); - assert_eq!(class_selector(&format!("{name}--size-sm")), format!(".{name}--size-sm")); - let renamed = make_class_name("trackClass$1", "some-chain-data", "animus"); - assert!(renamed.starts_with("animus-trackClass$1-")); - assert_eq!( - class_selector(&format!("{renamed}--dir-md:flex-row")), - format!(".{}--dir-md\\:flex-row", renamed.replace('$', "\\$")) - ); - } - - #[test] - fn layer_declaration_order() { - let css = generate_css(&[], &test_breakpoints()); - assert!(css.starts_with("@layer anm-global, anm-base, anm-variants, anm-compounds, anm-states, anm-system, anm-custom;")); - } - - use crate::theme::{FlatTheme, PropConfig, PropConfigMap}; - use serde_json::json; - - fn utility_config() -> PropConfigMap { - let mut config = FxHashMap::default(); - config.insert( - "p".to_string(), - PropConfig { - property: "padding".to_string(), - properties: vec![], - negative: false, - scale: Some(serde_json::Value::String("space".to_string())), - transform: None, - transform_id: None, - current_var: None, - transform_fn_source: None, - callback: None, - strict: None, - declaration: Default::default(), - }, - ); - config.insert( - "mt".to_string(), - PropConfig { - property: "marginTop".to_string(), - properties: vec![], - negative: false, - scale: Some(serde_json::Value::String("space".to_string())), - transform: None, - transform_id: None, - current_var: None, - transform_fn_source: None, - callback: None, - strict: None, - declaration: Default::default(), - }, - ); - config.insert( - "display".to_string(), - PropConfig { - property: "display".to_string(), - properties: vec![], - negative: false, - scale: None, - transform: None, - transform_id: None, - current_var: None, - transform_fn_source: None, - callback: None, - strict: None, - declaration: Default::default(), - }, - ); - config - } - - fn utility_theme() -> FlatTheme { - let mut theme = FxHashMap::default(); - theme.insert("space.8".to_string(), "0.5rem".to_string()); - theme.insert("space.16".to_string(), "1rem".to_string()); - theme - } - - #[test] - fn generates_simple_utility() { - let bp = test_breakpoints(); - let tc = TestUtilCtx::new(utility_config(), utility_theme(), &bp); - let usages = vec![UtilityInput { - prop_name: "p".to_string(), - value: json!(8), - }]; - let out = resolve_utility_classes(&usages, &tc.ctx(), "animus", None).render(&bp, None, &[]); - assert!(out.css.contains("@layer anm-system {")); - assert!(out.css.contains("padding: 0.5rem;")); - assert!(out.css.contains(".animus-u-")); - } - - #[test] - fn generates_responsive_utility() { - let bp = test_breakpoints(); - let tc = TestUtilCtx::new(utility_config(), utility_theme(), &bp); - let usages = vec![UtilityInput { - prop_name: "mt".to_string(), - value: json!({ "_": 8, "sm": 16 }), - }]; - let out = resolve_utility_classes(&usages, &tc.ctx(), "animus", None).render(&bp, None, &[]); - assert!(out.css.contains("margin-top: 0.5rem;")); - assert!(out.css.contains("@media (min-width: 768px)")); - assert!(out.css.contains("margin-top: 1rem;")); - } - - #[test] - fn utility_class_name_deterministic() { - let bp = test_breakpoints(); - let tc = TestUtilCtx::new(utility_config(), utility_theme(), &bp); - let usages = vec![UtilityInput { - prop_name: "p".to_string(), - value: json!(8), - }]; - let out1 = resolve_utility_classes(&usages, &tc.ctx(), "animus", None).render(&bp, None, &[]); - let out2 = resolve_utility_classes(&usages, &tc.ctx(), "animus", None).render(&bp, None, &[]); - assert_eq!(out1.css, out2.css); - let map1 = &out1.class_map["p"]["8"]; - let map2 = &out2.class_map["p"]["8"]; - assert_eq!(map1, map2); - } - - #[test] - fn different_values_different_classes() { - let bp = test_breakpoints(); - let tc = TestUtilCtx::new(utility_config(), utility_theme(), &bp); - let usages = vec![ - UtilityInput { - prop_name: "p".to_string(), - value: json!(8), - }, - UtilityInput { - prop_name: "p".to_string(), - value: json!(16), - }, - ]; - let out = resolve_utility_classes(&usages, &tc.ctx(), "animus", None).render(&bp, None, &[]); - let class_8 = &out.class_map["p"]["8"]; - let class_16 = &out.class_map["p"]["16"]; - assert_ne!(class_8, class_16); - } - - #[test] - fn serialize_value_key_number() { - assert_eq!(serialize_value_key(&json!(8)), "8"); - assert_eq!(serialize_value_key(&json!(0)), "0"); - } - - #[test] - fn serialize_value_key_string() { - assert_eq!(serialize_value_key(&json!("flex")), "flex"); - } - - #[test] - fn serialize_value_key_responsive() { - let key = serialize_value_key(&json!({ "_": 8, "sm": 16 })); - assert_eq!(key, "_:8|sm:16"); - } - - #[test] - fn custom_prop_uses_custom_layer() { - let bp = test_breakpoints(); - let tc = TestUtilCtx::new(utility_config(), utility_theme(), &bp); - let usages = vec![( - "a.tsx::A".to_string(), - UtilityInput { - prop_name: "p".to_string(), - value: json!(8), - }, - )]; - let configs: FxHashMap<&str, &PropConfigMap> = - [("a.tsx::A", &tc.config)].into_iter().collect(); - let out = resolve_custom_prop_classes(&usages, &configs, &tc.ctx(), "animus", None, |_, _| {}).render(&bp, None, &[]); - assert!(out.class_map["a.tsx::A"]["p"].contains_key("8")); - assert!(out.css.contains("@layer anm-custom {")); - assert!(!out.css.contains("@layer anm-system {")); - } - - #[test] - fn class_map_structure() { - let bp = test_breakpoints(); - let tc = TestUtilCtx::new(utility_config(), utility_theme(), &bp); - let usages = vec![UtilityInput { - prop_name: "p".to_string(), - value: json!(8), - }]; - let out = resolve_utility_classes(&usages, &tc.ctx(), "animus", None).render(&bp, None, &[]); - assert!(out.class_map.contains_key("p")); - let p_map = &out.class_map["p"]; - assert!(p_map.contains_key("8")); - let class_name = &p_map["8"]; - assert!(class_name.starts_with("animus-u-")); - assert!(out.css.contains(class_name.as_str())); - } - - fn slot_meta(current_var: Option<&str>) -> HashMap { - let mut dynamic_props = HashMap::new(); - dynamic_props.insert( - "bg".to_string(), - DynamicPropMeta::Value(crate::dynamic_meta::ValuePropMeta { - var_name: "--animus-bg".to_string(), - slot_class: "animus-dyn-bg".to_string(), - property: "backgroundColor".to_string(), - properties: vec![], - negative: false, - strict: false, - keywords: vec![], - transform_name: None, - transform_id: None, - transform_fn_source: None, - scale_values: std::collections::BTreeMap::new(), - current_var: current_var.map(str::to_string), - production_conditions: None, - declared_numeric: false, - tables: Default::default(), - }), - ); - dynamic_props - } - - fn declarations_of(styles: &ResolvedStyles) -> Vec<(String, String)> { - styles - .declarations - .iter() - .chain(styles.breakpoint_groups().flat_map(|(_, declarations)| declarations)) - .map(|d| (d.property.clone(), d.value.clone())) - .collect() - } - - #[test] - fn a_current_var_slot_writes_it_and_has_a_slot_that_leaves_it_alone() { - let entries = build_variable_slot_entries(&slot_meta(Some("--current-bg")), &test_breakpoints(), &SlotConditions::default()); - let by_class: HashMap<&str, Vec<(String, String)>> = - entries.iter().map(|(class, styles, _)| (class.as_str(), declarations_of(styles))).collect(); - let decl = |p: &str, v: &str| (p.to_string(), v.to_string()); - - assert_eq!( - by_class["animus-dyn-bg"], - [decl("background-color", "var(--animus-bg)"), decl("--current-bg", "var(--animus-bg)")] - ); - assert_eq!(by_class["animus-dyn-bg--keep"], [decl("background-color", "var(--animus-bg)")]); - assert_eq!( - by_class["animus-dyn-bg-md"], - [decl("background-color", "var(--animus-bg-md)"), decl("--current-bg", "var(--animus-bg-md)")] - ); - assert_eq!(by_class["animus-dyn-bg--keep-md"], [decl("background-color", "var(--animus-bg-md)")]); - assert_eq!(entries.len(), 12); - } - - #[test] - fn a_slot_without_current_var_is_unchanged() { - let entries = build_variable_slot_entries(&slot_meta(None), &test_breakpoints(), &SlotConditions::default()); - assert_eq!(entries.len(), 6); - assert!(entries.iter().all(|(class, styles, _)| !class.contains("--keep") - && declarations_of(styles).iter().all(|(property, _)| property == "background-color"))); - } - - #[test] - fn variable_slot_single_property() { - let mut dynamic_props = HashMap::new(); - dynamic_props.insert( - "p".to_string(), - DynamicPropMeta::Value(crate::dynamic_meta::ValuePropMeta { - var_name: "--animus-p".to_string(), - slot_class: "animus-dyn-p".to_string(), - property: "padding".to_string(), - properties: vec![], - negative: false, - strict: false, - keywords: vec![], - transform_name: None, - transform_id: None, - transform_fn_source: None, - scale_values: std::collections::BTreeMap::new(), - current_var: None, - production_conditions: None, - declared_numeric: false, - tables: Default::default(), - }), - ); - let bp = test_breakpoints(); - let entries = build_variable_slot_entries(&dynamic_props, &bp, &SlotConditions::default()); - assert_eq!(entries.len(), 6); - assert_eq!(entries[0].0, "animus-dyn-p"); - assert_eq!(entries[0].1.declarations[0].property, "padding"); - assert_eq!(entries[0].1.declarations[0].value, "var(--animus-p)"); - assert!(entries[0].1.breakpoint_groups().next().is_none()); - assert_eq!(entries.len(), 6); - assert_eq!(entries[1].0, "animus-dyn-p-xs"); - assert!(entries[1].1.declarations.is_empty()); - let bps1: Vec<_> = entries[1].1.breakpoint_groups().collect(); - assert_eq!(bps1.len(), 1); - assert_eq!(bps1[0].0, "xs"); - assert_eq!(bps1[0].1[0].value, "var(--animus-p-xs)"); - assert_eq!(entries[2].0, "animus-dyn-p-sm"); - assert_eq!(entries[2].1.breakpoint_groups().next().unwrap().1[0].value, "var(--animus-p-sm)"); - assert_eq!(entries[5].0, "animus-dyn-p-xl"); - assert_eq!(entries[5].1.breakpoint_groups().next().unwrap().1[0].value, "var(--animus-p-xl)"); - } - - #[test] - fn variable_slot_multi_property() { - let mut dynamic_props = HashMap::new(); - dynamic_props.insert( - "px".to_string(), - DynamicPropMeta::Value(crate::dynamic_meta::ValuePropMeta { - var_name: "--animus-px".to_string(), - slot_class: "animus-dyn-px".to_string(), - property: "padding".to_string(), - properties: vec!["padding-left".to_string(), "padding-right".to_string()], - negative: false, - strict: false, - keywords: vec![], - transform_name: None, - transform_id: None, - transform_fn_source: None, - scale_values: std::collections::BTreeMap::new(), - current_var: None, - production_conditions: None, - declared_numeric: false, - tables: Default::default(), - }), - ); - let bp = test_breakpoints(); - let entries = build_variable_slot_entries(&dynamic_props, &bp, &SlotConditions::default()); - assert_eq!(entries.len(), 6); - assert_eq!(entries[0].1.declarations.len(), 2); - assert_eq!(entries[0].1.declarations[0].property, "padding-left"); - assert_eq!(entries[0].1.declarations[1].property, "padding-right"); - assert_eq!(entries[1].0, "animus-dyn-px-xs"); - let bps1: Vec<_> = entries[1].1.breakpoint_groups().collect(); - assert_eq!(bps1[0].1.len(), 2); - assert_eq!(bps1[0].1[0].value, "var(--animus-px-xs)"); - } - - #[test] - fn variable_slot_empty_dynamic_props() { - let dynamic_props: HashMap = HashMap::new(); - let bp = test_breakpoints(); - let entries = build_variable_slot_entries(&dynamic_props, &bp, &SlotConditions::default()); - assert!(entries.is_empty()); - } - - #[test] - fn slot_entries_merge_into_utility_stream() { - let mut dynamic_props = HashMap::new(); - dynamic_props.insert( - "p".to_string(), - DynamicPropMeta::Value(crate::dynamic_meta::ValuePropMeta { - var_name: "--animus-p".to_string(), - slot_class: "animus-dyn-p".to_string(), - property: "padding".to_string(), - properties: vec![], - negative: false, - strict: false, - keywords: vec![], - transform_name: None, - transform_id: None, - transform_fn_source: None, - scale_values: std::collections::BTreeMap::new(), - current_var: None, - production_conditions: None, - declared_numeric: false, - tables: Default::default(), - }), - ); - let bp = test_breakpoints(); - let tc = TestUtilCtx::new(utility_config(), utility_theme(), &bp); - let slots = build_variable_slot_entries(&dynamic_props, &bp, &SlotConditions::default()); - let usages = vec![UtilityInput { prop_name: "p".to_string(), value: json!(8) }]; - let out = resolve_utility_classes(&usages, &tc.ctx(), "animus", None).render(&bp, Some(slots), &[]); - assert!(out.css.contains("animus-dyn-p")); - assert!(out.css.contains("animus-u-")); - assert_eq!(out.css.matches("@layer anm-system {").count(), 1); - } - - #[test] - fn css_property_name_basic() { - assert_eq!(css_property_name("backgroundColor"), "background-color"); - assert_eq!(css_property_name("fontSize"), "font-size"); - assert_eq!(css_property_name("display"), "display"); - assert_eq!(css_property_name("--leadingVisual-size"), "--leadingVisual-size"); - } - - #[test] - fn css_property_name_vendor() { - assert_eq!(css_property_name("WebkitTextFillColor"), "-webkit-text-fill-color"); - } - - #[test] - fn variable_slot_hyphenated() { - assert_eq!(hyphenated("borderRadius"), "border-radius"); - assert_eq!(hyphenated("p"), "p"); - assert_eq!(hyphenated("mt"), "mt"); - assert_eq!(hyphenated("paddingLeft"), "padding-left"); - assert_eq!(hyphenated("backgroundColor"), "background-color"); - } - - #[test] - fn two_props_never_share_a_runtime_slot() { - // The runtime appends `--keep` and `-{breakpoint}` to a slot's names. - let slot = |prop: &str, suffix: &str| format!("{}{suffix}", slot_segment(prop)); - assert_ne!(slot("stack", "-sm"), slot("stackSm", "")); - assert_ne!(slot("aB", ""), slot("a-b", "")); - assert_ne!(slot("x", "--keep"), slot("x-Keep", "")); - } - - fn joined(rules_by_child: Vec<(&str, String)>) -> String { - rules_by_child.into_iter().map(|(_, rules)| rules).collect() - } - - fn make_component_css(class_name: &str, variant_prop: &str, options: &[(&str, &str, &str)]) -> ComponentCss { - ComponentCss { - variant_order: Vec::new(), - class_name: class_name.to_string(), - base: None, - variants: vec![VariantCss { - prop: variant_prop.to_string(), - default_option: None, - options: options - .iter() - .map(|(name, prop, val)| { - ( - name.to_string(), - ResolvedStyles { - declarations: vec![CssDeclaration { - property: prop.to_string(), - value: val.to_string(), - }], - ..Default::default() - }, - ) - }) - .collect(), - }], - compounds: vec![], - states: vec![], - } - } - - #[test] - fn composed_emits_two_rules_per_option() { - let components = vec![ - make_component_css("animus-Root-abc", "size", &[ - ("sm", "font-size", "0.875rem"), - ("lg", "font-size", "1.25rem"), - ]), - make_component_css("animus-Child-def", "size", &[ - ("sm", "font-size", "0.875rem"), - ("lg", "font-size", "1.25rem"), - ]), - ]; - - let shared = vec![String::from("size")]; - let families = vec![ComposeFamilyRef { - root_class: "animus-Root-abc", - child_slots: vec![("Child", "animus-Child-def")], - shared_keys: &shared, - }]; - - let bp = test_breakpoints(); - let css = joined(generate_composed_variant_css(&families, &components, &bp)); - - assert!(css.contains(".animus-Root-abc--size-sm .animus-Child-def")); - assert!(css.contains(".animus-Root-abc .animus-Child-def.animus-Child-def--size-sm")); - assert!(css.contains("--size-sm")); - assert!(css.contains("--size-lg")); - } - - #[test] - fn composed_specificity_three_classes_each() { - let components = vec![ - make_component_css("animus-Root-abc", "size", &[ - ("sm", "padding", "4px"), - ]), - make_component_css("animus-Child-def", "size", &[ - ("sm", "padding", "4px"), - ]), - ]; - - let shared = vec![String::from("size")]; - let families = vec![ComposeFamilyRef { - root_class: "animus-Root-abc", - child_slots: vec![("Child", "animus-Child-def")], - shared_keys: &shared, - }]; - - let bp = test_breakpoints(); - let css = joined(generate_composed_variant_css(&families, &components, &bp)); - - let inheritance_sel = ".animus-Root-abc--size-sm .animus-Child-def"; - let override_sel = ".animus-Root-abc .animus-Child-def.animus-Child-def--size-sm"; - assert!(css.contains(inheritance_sel), "Missing inheritance selector"); - assert!(css.contains(override_sel), "Missing override selector"); - assert_eq!(inheritance_sel.matches('.').count(), 2, "Inheritance should be (0,2,0)"); - assert_eq!(override_sel.matches('.').count(), 3, "Override should be (0,3,0)"); - } - - #[test] - fn composed_source_order_inheritance_before_override() { - let components = vec![ - make_component_css("animus-Root-abc", "size", &[ - ("sm", "padding", "4px"), - ]), - make_component_css("animus-Child-def", "size", &[ - ("sm", "padding", "4px"), - ]), - ]; - - let shared = vec![String::from("size")]; - let families = vec![ComposeFamilyRef { - root_class: "animus-Root-abc", - child_slots: vec![("Child", "animus-Child-def")], - shared_keys: &shared, - }]; - - let bp = test_breakpoints(); - let css = joined(generate_composed_variant_css(&families, &components, &bp)); - - let inheritance_pos = css.find(".animus-Root-abc--size-sm .animus-Child-def").unwrap(); - let override_pos = css.find(".animus-Root-abc .animus-Child-def.animus-Child-def--size-sm").unwrap(); - assert!(inheritance_pos < override_pos, "Inheritance rule must come before override rule"); - } - - #[test] - fn composed_root_default_option_propagates_to_child_slots() { - let mut root = make_component_css("animus-Root-abc", "size", &[ - ("sm", "font-size", "0.875rem"), - ("lg", "font-size", "1.25rem"), - ]); - root.variants[0].default_option = Some("sm".to_string()); - let child = make_component_css("animus-Child-def", "size", &[ - ("sm", "padding", "4px"), - ("lg", "padding", "8px"), - ]); - let components = vec![root, child]; - - let shared = vec![String::from("size")]; - let families = vec![ComposeFamilyRef { - root_class: "animus-Root-abc", - child_slots: vec![("Child", "animus-Child-def")], - shared_keys: &shared, - }]; - - let bp = test_breakpoints(); - let css = joined(generate_composed_variant_css(&families, &components, &bp)); - - assert!( - css.contains(".animus-Root-abc--size-default .animus-Child-def {\n padding: 4px;"), - "missing default inheritance rule:\n{css}" - ); - assert!( - !css.contains("animus-Child-def--size-default"), - "default must not emit a child-side override:\n{css}" - ); - assert_eq!( - css.matches("--size-default").count(), - 1, - "exactly one default-keyed rule expected:\n{css}" - ); - } - - #[test] - fn composed_root_default_absent_from_child_options_emits_nothing() { - let mut root = make_component_css("animus-Root-abc", "size", &[ - ("sm", "font-size", "0.875rem"), - ("xl", "font-size", "2rem"), - ]); - root.variants[0].default_option = Some("xl".to_string()); - let child = make_component_css("animus-Child-def", "size", &[ - ("sm", "padding", "4px"), - ]); - let components = vec![root, child]; - - let shared = vec![String::from("size")]; - let families = vec![ComposeFamilyRef { - root_class: "animus-Root-abc", - child_slots: vec![("Child", "animus-Child-def")], - shared_keys: &shared, - }]; - - let bp = test_breakpoints(); - let css = joined(generate_composed_variant_css(&families, &components, &bp)); - assert!(!css.contains("--size-default"), "{css}"); - } - - #[test] - fn composed_multiple_shared_variants_multiple_children() { - let root = make_component_css("animus-Root-abc", "size", &[ - ("sm", "font-size", "0.875rem"), - ]); - let mut child1 = make_component_css("animus-Control-def", "size", &[ - ("sm", "font-size", "0.875rem"), - ]); - child1.variants.push(VariantCss { - prop: "tone".to_string(), - default_option: None, - options: vec![("muted".to_string(), ResolvedStyles { - declarations: vec![CssDeclaration { property: "opacity".to_string(), value: "0.5".to_string() }], - ..Default::default() - })], - }); - let child2 = make_component_css("animus-Label-ghi", "size", &[ - ("sm", "font-size", "0.875rem"), - ]); - - let components = vec![root, child1, child2]; - - let shared_keys = vec![String::from("size"), String::from("tone")]; - let families = vec![ComposeFamilyRef { - root_class: "animus-Root-abc", - child_slots: vec![ - ("Control", "animus-Control-def"), - ("Label", "animus-Label-ghi"), - ], - shared_keys: &shared_keys, - }]; - - let bp = test_breakpoints(); - let css = joined(generate_composed_variant_css(&families, &components, &bp)); - - assert!(css.contains(".animus-Root-abc--size-sm .animus-Control-def")); - assert!(css.contains(".animus-Root-abc--tone-muted .animus-Control-def")); - assert!(css.contains(".animus-Root-abc--size-sm .animus-Label-ghi")); - assert!(!css.contains("--tone-muted .animus-Label-ghi")); - } - - #[test] - fn composed_includes_pseudo_selectors() { - let child = ComponentCss { - variant_order: Vec::new(), - class_name: "animus-Child-def".to_string(), - base: None, - variants: vec![VariantCss { - prop: "size".to_string(), - default_option: None, - options: vec![("sm".to_string(), ResolvedStyles { - declarations: vec![CssDeclaration { - property: "padding".to_string(), - value: "4px".to_string(), - }], - pseudo_selectors: vec![( - ":hover".to_string(), - vec![CssDeclaration { - property: "background-color".to_string(), - value: "blue".to_string(), - }], - Default::default(), - )], - ..Default::default() - })], - }], - compounds: vec![], - states: vec![], - }; - let root = make_component_css("animus-Root-abc", "size", &[("sm", "padding", "4px")]); - let components = vec![root, child]; - - let shared = vec![String::from("size")]; - let families = vec![ComposeFamilyRef { - root_class: "animus-Root-abc", - child_slots: vec![("Child", "animus-Child-def")], - shared_keys: &shared, - }]; - - let bp = test_breakpoints(); - let css = joined(generate_composed_variant_css(&families, &components, &bp)); - - assert!(css.contains(".animus-Root-abc--size-sm .animus-Child-def:hover")); - assert!(css.contains(".animus-Root-abc .animus-Child-def.animus-Child-def--size-sm:hover")); - assert!(css.contains("background-color: blue")); - } - - #[test] - fn composed_emits_selector_breakpoint_and_conditioned_groups() { - let child = ComponentCss { - variant_order: Vec::new(), - class_name: "animus-Child-def".to_string(), - base: None, - variants: vec![VariantCss { - prop: "size".to_string(), - default_option: None, - options: vec![( - "sm".to_string(), - ResolvedStyles { - declarations: vec![CssDeclaration { - property: "padding".to_string(), - value: "4px".to_string(), - }], - conditioned: vec![ - ConditionedGroup { - suppliers: Default::default(), - conditions: vec![Condition::Breakpoint("sm".to_string())], - selector: Some(":hover".to_string()), - declarations: vec![CssDeclaration { - property: "gap".to_string(), - value: "1rem".to_string(), - }], - emit_order: ConditionEmitOrder::Breakpoint, - }, - container_group( - "@container (min-width: 400px)", - "font-size", - "18px", - ), - ], - ..Default::default() - }, - )], - }], - compounds: vec![], - states: vec![], - }; - let root = make_component_css("animus-Root-abc", "size", &[("sm", "padding", "4px")]); - let components = vec![root, child]; - - let shared = vec![String::from("size")]; - let families = vec![ComposeFamilyRef { - root_class: "animus-Root-abc", - child_slots: vec![("Child", "animus-Child-def")], - shared_keys: &shared, - }]; - - let bp = test_breakpoints(); - let css = joined(generate_composed_variant_css(&families, &components, &bp)); - - assert_eq!( - css.matches("@media (min-width: 768px)").count(), - 1, - "exactly one sm breakpoint MQ:\n{css}" - ); - assert!( - css.contains(".animus-Root-abc--size-sm .animus-Child-def:hover"), - "inheritance selector + :hover:\n{css}" - ); - assert!( - css.contains(".animus-Root-abc .animus-Child-def.animus-Child-def--size-sm:hover"), - "override selector + :hover:\n{css}" - ); - assert_eq!( - css.matches("gap: 1rem").count(), - 2, - "responsive-selector decl wraps both composed selectors:\n{css}" - ); - - assert_eq!( - css.matches("@container (min-width: 400px)").count(), - 1, - "exactly one @container block:\n{css}" - ); - assert_eq!( - css.matches("font-size: 18px").count(), - 2, - "conditioned decl wraps both composed selectors:\n{css}" - ); - - let mq_pos = css.find("@media (min-width: 768px)").unwrap(); - let cond_pos = css.find("@container (min-width: 400px)").unwrap(); - assert!(mq_pos < cond_pos, "breakpoint MQ before condition (D4):\n{css}"); - } - - type CompoundConfigList = Vec; - - fn compound_config( - child_class: &str, - index: usize, - entries: &[(&str, Value)], - ) -> CompoundConfig { - ( - entries - .iter() - .map(|(axis, value)| ((*axis).to_string(), value.clone())) - .collect(), - format!("{}--compound-{}", child_class, index), - ) - } - - fn compound_styles(property: &str, value: &str) -> ResolvedStyles { - ResolvedStyles { - declarations: vec![CssDeclaration { - property: property.to_string(), - value: value.to_string(), - }], - ..Default::default() - } - } - - fn conditions_map<'a>( - entries: &'a [(&'a str, CompoundConfigList)], - ) -> CompoundConditionMap<'a> { - entries - .iter() - .map(|(class, configs)| (*class, configs.as_slice())) - .collect() - } - - fn one_child_family<'a>(shared: &'a [String]) -> Vec> { - vec![ComposeFamilyRef { - root_class: "animus-Root-abc", - child_slots: vec![("Child", "animus-Child-def")], - shared_keys: shared, - }] - } - - fn default_root() -> ComponentCss { - make_component_css("animus-Root-abc", "size", &[("sm", "padding", "4px")]) - } - - fn child_with_options(prop: &str, options: &[(&str, &str, &str)]) -> ComponentCss { - let mut child = make_component_css("animus-Child-def", prop, options); - child.compounds = vec![compound_styles("display", "flex")]; - child - } - - fn default_child() -> ComponentCss { - child_with_options("size", &[("sm", "padding", "4px")]) - } - - fn root_and_child() -> Vec { - vec![default_root(), default_child()] - } - - /// `axes` are the compound's stored conditions, `shared` the Root's axes. - fn expand(components: &[ComponentCss], axes: &[(&str, Value)], shared: &[&str]) -> String { - let configs = vec![( - "animus-Child-def", - vec![compound_config("animus-Child-def", 0, axes)], - )]; - let conditions = conditions_map(&configs); - let shared: Vec = shared.iter().map(|axis| (*axis).to_string()).collect(); - let families = one_child_family(&shared); - joined(generate_composed_compound_css(&families, components, &conditions, &test_breakpoints())) - } - - #[test] - fn shared_axis_compound_expands_to_an_ancestor_selector() { - let css = expand(&root_and_child(), &[("size", Value::from("sm"))], &["size"]); - - assert_eq!( - css, - " .animus-Root-abc--size-sm .animus-Child-def {\n display: flex;\n }\n", - "{css}" - ); - } - - #[test] - fn several_shared_axes_chain_on_the_root_in_conditions_order() { - let css = expand( - &root_and_child(), - &[("tone", Value::from("loud")), ("size", Value::from("sm"))], - &["size", "tone"], - ); - - assert_eq!( - css, - " .animus-Root-abc--size-sm.animus-Root-abc--tone-loud .animus-Child-def {\n display: flex;\n }\n", - "{css}" - ); - } - - #[test] - fn child_only_axes_stay_on_the_child_beside_the_shared_ancestor() { - let css = expand( - &root_and_child(), - &[("size", Value::from("sm")), ("weight", Value::from("bold"))], - &["size"], - ); - - assert_eq!( - css, - " .animus-Root-abc--size-sm .animus-Child-def.animus-Child-def--weight-bold {\n display: flex;\n }\n", - "{css}" - ); - } - - #[test] - fn an_accepted_value_list_groups_the_axis_into_one_is_selector() { - let css = expand( - &root_and_child(), - &[("size", Value::from(vec!["sm", "lg"]))], - &["size"], - ); - - assert_eq!( - css, - " :is(.animus-Root-abc--size-sm,.animus-Root-abc--size-lg) .animus-Child-def {\n display: flex;\n }\n", - "{css}" - ); - } - - #[test] - fn value_lists_group_each_axis_on_its_own_side() { - let css = expand( - &root_and_child(), - &[ - ("size", Value::from(vec!["sm", "lg"])), - ("weight", Value::from(vec!["bold", "black"])), - ], - &["size"], - ); - - assert_eq!( - css, - " :is(.animus-Root-abc--size-sm,.animus-Root-abc--size-lg) \ - .animus-Child-def:is(.animus-Child-def--weight-bold,.animus-Child-def--weight-black) \ - {\n display: flex;\n }\n", - "{css}" - ); - } - - #[test] - fn a_root_default_keeps_the_compound_alive_when_the_prop_is_omitted() { - let mut root = default_root(); - root.variants[0].default_option = Some("sm".to_string()); - - let css = expand( - &[root, default_child()], - &[("size", Value::from("sm"))], - &["size"], - ); - - assert_eq!( - css, - " :is(.animus-Root-abc--size-sm,.animus-Root-abc--size-default) .animus-Child-def \ - {\n display: flex;\n }\n", - "{css}" - ); - } - - #[test] - fn a_root_default_the_conditions_do_not_require_adds_no_alternative() { - let mut root = make_component_css( - "animus-Root-abc", - "size", - &[("sm", "padding", "4px"), ("lg", "padding", "8px")], - ); - root.variants[0].default_option = Some("lg".to_string()); - - let css = expand( - &[root, default_child()], - &[("size", Value::from("sm"))], - &["size"], - ); - - assert_eq!( - css, - " .animus-Root-abc--size-sm .animus-Child-def {\n display: flex;\n }\n", - "{css}" - ); - } - - fn child_with_defaulted_own_variant(default_option: &str) -> ComponentCss { - let mut child = default_child(); - child.variants.push(VariantCss { - prop: "weight".to_string(), - default_option: Some(default_option.to_string()), - options: vec![ - ( - "bold".to_string(), - ResolvedStyles { - declarations: vec![CssDeclaration { - property: "font-weight".to_string(), - value: "700".to_string(), - }], - ..Default::default() - }, - ), - ( - "light".to_string(), - ResolvedStyles { - declarations: vec![CssDeclaration { - property: "font-weight".to_string(), - value: "300".to_string(), - }], - ..Default::default() - }, - ), - ], - }); - child - } - - #[test] - fn a_child_default_keeps_the_mixed_form_alive_when_the_child_prop_is_omitted() { - let css = expand( - &[default_root(), child_with_defaulted_own_variant("bold")], - &[("size", Value::from("sm")), ("weight", Value::from("bold"))], - &["size"], - ); - - assert_eq!( - css, - " .animus-Root-abc--size-sm \ - .animus-Child-def:is(.animus-Child-def--weight-bold,.animus-Child-def--weight-default) \ - {\n display: flex;\n }\n", - "{css}" - ); - } - - #[test] - fn a_child_default_the_conditions_do_not_require_adds_no_alternative() { - let css = expand( - &[default_root(), child_with_defaulted_own_variant("light")], - &[("size", Value::from("sm")), ("weight", Value::from("bold"))], - &["size"], - ); - - assert_eq!( - css, - " .animus-Root-abc--size-sm .animus-Child-def.animus-Child-def--weight-bold \ - {\n display: flex;\n }\n", - "{css}" - ); - } - - #[test] - fn a_compound_on_child_only_axes_stays_flat() { - let css = expand( - &root_and_child(), - &[("weight", Value::from("bold"))], - &["size"], - ); - - assert_eq!(css, "", "{css}"); - } - - #[test] - fn an_expanded_compound_carries_its_pseudo_rules() { - let mut child = default_child(); - child.compounds = vec![ResolvedStyles { - declarations: vec![CssDeclaration { - property: "display".to_string(), - value: "flex".to_string(), - }], - pseudo_selectors: vec![( - ":hover".to_string(), - vec![CssDeclaration { - property: "background-color".to_string(), - value: "blue".to_string(), - }], - Default::default(), - )], - ..Default::default() - }]; - - let css = expand( - &[default_root(), child], - &[("size", Value::from(vec!["sm", "lg"]))], - &["size"], - ); - - assert!( - css.contains( - " :is(.animus-Root-abc--size-sm,.animus-Root-abc--size-lg) \ - .animus-Child-def:hover {\n" - ), - "the pseudo must land on the whole expanded selector:\n{css}" - ); - } - - #[test] - fn an_explicit_slot_option_on_a_shared_axis_suppresses_the_ancestor_form() { - let child = child_with_options("size", &[("sm", "padding", "4px"), ("lg", "padding", "8px")]); - - let css = expand( - &[default_root(), child], - &[("size", Value::from("sm"))], - &["size"], - ); - - assert_eq!( - css, - " .animus-Root-abc--size-sm .animus-Child-def:not(.animus-Child-def--size-lg) \ - {\n display: flex;\n }\n", - "{css}" - ); - } - - #[test] - fn an_accepted_value_list_excludes_only_the_options_it_leaves_out() { - let child = child_with_options( - "size", - &[ - ("sm", "padding", "4px"), - ("md", "padding", "6px"), - ("lg", "padding", "8px"), - ], - ); - - let css = expand( - &[default_root(), child], - &[("size", Value::from(vec!["sm", "md"]))], - &["size"], - ); - - assert_eq!( - css, - " :is(.animus-Root-abc--size-sm,.animus-Root-abc--size-md) \ - .animus-Child-def:not(.animus-Child-def--size-lg) {\n display: flex;\n }\n", - "{css}" - ); - } - - #[test] - fn numeric_accepted_values_keep_their_ancestor_branch() { - let child = child_with_options( - "size", - &[("sm", "padding", "4px"), ("2", "padding", "2px")], - ); - - let css = expand( - &[default_root(), child], - &[("size", serde_json::json!(["sm", 2]))], - &["size"], - ); - - assert_eq!( - css, - " :is(.animus-Root-abc--size-sm,.animus-Root-abc--size-2) \ - .animus-Child-def {\n display: flex;\n }\n", - "{css}" - ); - } - - #[test] - fn a_defaulted_slot_option_on_a_shared_axis_is_never_excluded() { - let mut child = - child_with_options("size", &[("sm", "padding", "4px"), ("lg", "padding", "8px")]); - child.variants[0].default_option = Some("lg".to_string()); - - let css = expand( - &[default_root(), child], - &[("size", Value::from("sm"))], - &["size"], - ); - - assert_eq!( - css, - " .animus-Root-abc--size-sm .animus-Child-def:not(.animus-Child-def--size-lg) \ - {\n display: flex;\n }\n", - "{css}" - ); - } - - #[test] - fn a_slot_without_its_own_copy_of_the_shared_axis_takes_the_form_unconditionally() { - let child = child_with_options("weight", &[("bold", "font-weight", "700")]); - - let css = expand( - &[default_root(), child], - &[("size", Value::from("sm"))], - &["size"], - ); - - assert_eq!( - css, - " .animus-Root-abc--size-sm .animus-Child-def {\n display: flex;\n }\n", - "{css}" - ); - } - - fn decls(pairs: &[(&str, &str)]) -> Vec { - pairs.iter().map(|(p, v)| CssDeclaration { property: p.to_string(), value: v.to_string() }).collect() - } - - #[test] - fn emits_stacked_condition_wrappers_outermost_first() { - let styles = ResolvedStyles { - declarations: vec![], - pseudo_selectors: vec![], - conditioned: vec![ConditionedGroup { - suppliers: Default::default(), - conditions: vec![ - Condition::Supports("@supports (display: grid)".into()), - Condition::Container("@container (min-width: 400px)".into()), - ], - selector: None, - declarations: decls(&[("display", "grid")]), - emit_order: ConditionEmitOrder::Raw(0), - }], - }; - let mut out = String::new(); - write_rule_block(&mut out, "animus-X-1", &styles, &test_breakpoints()); - let si = out.find("@supports (display: grid) {").expect("outer wrapper"); - let ci = out.find("@container (min-width: 400px) {").expect("inner wrapper"); - assert!(si < ci, "outermost-first:\n{}", out); - assert!(out.contains(".animus-X-1")); - assert!(out.contains("display: grid;")); - } - - #[test] - fn emits_condition_group_with_nested_selector() { - let styles = ResolvedStyles { - declarations: vec![], - pseudo_selectors: vec![], - conditioned: vec![ConditionedGroup { - suppliers: Default::default(), - conditions: vec![Condition::Container("@container (min-width: 400px)".into())], - selector: Some(":hover".into()), - declarations: decls(&[("gap", "0.5rem")]), - emit_order: ConditionEmitOrder::Raw(0), - }], - }; - let mut out = String::new(); - write_rule_block(&mut out, "animus-X-2", &styles, &test_breakpoints()); - assert!(out.contains("@container (min-width: 400px) {")); - assert!(out.contains(".animus-X-2:hover"), "selector composes inside at-rule:\n{}", out); - } - - #[test] - fn emits_breakpoint_member_inside_condition_stack() { - let styles = ResolvedStyles { - declarations: vec![], - pseudo_selectors: vec![], - conditioned: vec![ConditionedGroup { - suppliers: Default::default(), - conditions: vec![ - Condition::Container("@container (min-width: 400px)".into()), - Condition::Breakpoint("sm".into()), - ], - selector: None, - declarations: decls(&[("font-size", "16px")]), - emit_order: ConditionEmitOrder::Raw(0), - }], - }; - let mut out = String::new(); - write_rule_block(&mut out, "animus-X-3", &styles, &test_breakpoints()); - let ci = out.find("@container (min-width: 400px) {").expect("container wrapper"); - let mi = out.find("@media (min-width: 768px) {").expect("inner breakpoint wrapper"); - assert!(ci < mi, "breakpoint nests INSIDE the container block:\n{}", out); - } - - #[test] - fn rule_block_emits_responsive_selector_groups() { - let styles = ResolvedStyles { - declarations: decls(&[("display", "flex")]), - pseudo_selectors: vec![(":hover".to_string(), decls(&[("padding", "0.5rem")]), Default::default())], - conditioned: vec![ConditionedGroup { - suppliers: Default::default(), - conditions: vec![Condition::Breakpoint("sm".into())], - selector: Some(":hover".into()), - declarations: decls(&[("padding", "1rem")]), - emit_order: ConditionEmitOrder::Breakpoint, - }], - }; - let mut out = String::new(); - write_rule_block(&mut out, "animus-X-4", &styles, &test_breakpoints()); - let mq = out.find("@media (min-width: 768px) {").expect("mq wrapper"); - let sel = out.find(".animus-X-4:hover {").expect("plain pseudo rule"); - let cond_sel = out[mq..].find(".animus-X-4:hover").expect("selector inside mq"); - assert!(sel < mq, "plain pseudo before responsive-selector group:\n{}", out); - let _ = cond_sel; - assert!(out.contains("padding: 1rem;")); - } - - #[test] - fn hash_distinguishes_stack_members_and_selector() { - let base = ResolvedStyles { - declarations: decls(&[("display", "grid")]), - pseudo_selectors: vec![], - conditioned: vec![ConditionedGroup { - suppliers: Default::default(), - conditions: vec![Condition::Supports("@supports (display: grid)".into())], - selector: None, - declarations: decls(&[("gap", "1rem")]), - emit_order: ConditionEmitOrder::Raw(0), - }], - }; - let mut stacked = base.clone(); - stacked.conditioned[0].conditions.push(Condition::Container("@container (min-width: 400px)".into())); - let mut with_selector = base.clone(); - with_selector.conditioned[0].selector = Some(":hover".into()); - let mut with_bp_selector = base.clone(); - with_bp_selector.conditioned[0].conditions = vec![Condition::Breakpoint("sm".into())]; - with_bp_selector.conditioned[0].selector = Some(":hover".into()); - with_bp_selector.conditioned[0].emit_order = ConditionEmitOrder::Breakpoint; - - let h0 = canonical_css_for_hash(&base); - let h1 = canonical_css_for_hash(&stacked); - let h2 = canonical_css_for_hash(&with_selector); - let h3 = canonical_css_for_hash(&with_bp_selector); - assert_ne!(h0, h1, "inner stack member must change the hash"); - assert_ne!(h0, h2, "nested selector must change the hash"); - assert_ne!(h0, h3, "selector-bearing breakpoint group must be admitted"); - assert!(h3.contains("@cond:bp:sm|:hover{"), "hash admits bp+selector: {}", h3); - } - - #[test] - fn composed_selectors_emit_in_outer_cascade_order() { - let styles = ResolvedStyles { - declarations: vec![], - pseudo_selectors: vec![ - (":active::before".to_string(), decls(&[("opacity", "0.5")]), Default::default()), - (":hover::before".to_string(), decls(&[("opacity", "1")]), Default::default()), - ], - conditioned: vec![], - }; - let mut out = String::new(); - write_rule_block(&mut out, "animus-X-5", &styles, &test_breakpoints()); - let h = out.find(".animus-X-5:hover::before").expect("hover rule"); - let a = out.find(".animus-X-5:active::before").expect("active rule"); - assert!(h < a, "outer cascade order must beat authoring order:\n{}", out); - } - - #[test] - fn condition_base_group_emits_before_breakpoint_child() { - let styles = ResolvedStyles { - declarations: vec![], - pseudo_selectors: vec![], - conditioned: vec![ - ConditionedGroup { - suppliers: Default::default(), - conditions: vec![Condition::Container("@container (min-width: 400px)".into())], - selector: None, - declarations: decls(&[("font-size", "14px")]), - emit_order: ConditionEmitOrder::Raw(0), - }, - ConditionedGroup { - suppliers: Default::default(), - conditions: vec![ - Condition::Container("@container (min-width: 400px)".into()), - Condition::Breakpoint("sm".into()), - ], - selector: None, - declarations: decls(&[("font-size", "16px")]), - emit_order: ConditionEmitOrder::Raw(0), - }, - ], - }; - let mut out = String::new(); - write_rule_block(&mut out, "animus-X-6", &styles, &test_breakpoints()); - let base = out.find("font-size: 14px").expect("base decl"); - let bp = out.find("font-size: 16px").expect("bp override"); - assert!(base < bp, "base before breakpoint override:\n{}", out); - } - - #[test] - fn format_pseudo_selector_preserves_descendant_branches() { - assert_eq!( - format_pseudo_selector("C", " p + ul, ul + p"), - ".C p + ul, .C ul + p" - ); - assert_eq!(format_pseudo_selector("C", " strong, b"), ".C strong, .C b"); - assert_eq!( - format_pseudo_selector("C", " tr > *:last-child, tr > *:has(+ [data-part=\"trailing\"])"), - ".C tr > *:last-child, .C tr > *:has(+ [data-part=\"trailing\"])" - ); - } - - #[test] - fn format_pseudo_selector_groups_ampersand_adjacent_alternatives() { - assert_eq!( - format_pseudo_selector("c", ":hover,[data-x]"), - ".c:is(:hover, [data-x])" - ); - assert_eq!( - format_pseudo_selector("c", ":disabled,[disabled]"), - ".c:is(:disabled, [disabled])" - ); - assert_eq!(format_pseudo_selector("c", ":hover"), ".c:hover"); - assert_eq!( - format_pseudo_selector("c", ":disabled,[disabled],[aria-disabled=\"true\"],[data-disabled]"), - ".c:is(:disabled, [disabled], [aria-disabled=\"true\"], [data-disabled])" - ); - } - - #[test] - fn format_pseudo_selector_does_not_split_functional_or_quoted_commas() { - assert_eq!( - format_pseudo_selector("C", " [data-part=\"add-row\"] :is(:focus-visible, [data-focus-visible])"), - ".C [data-part=\"add-row\"] :is(:focus-visible, [data-focus-visible])" - ); - assert_eq!( - format_pseudo_selector("C", "[data-pinned]:is([data-active=\"true\"], [data-mode=\"edit\"])"), - ".C[data-pinned]:is([data-active=\"true\"], [data-mode=\"edit\"])" - ); - assert_eq!( - format_pseudo_selector("C", "[data-label=\"a,b\"]"), - ".C[data-label=\"a,b\"]" - ); - } - - #[test] - fn format_composed_pseudo_mirrors_combinator_and_functional_handling() { - assert_eq!( - format_composed_pseudo(".Root .Child", " p + ul, ul + p"), - ".Root .Child p + ul, .Root .Child ul + p" - ); - assert_eq!( - format_composed_pseudo(".Root", " [data-part=\"add-row\"] :is(:focus-visible, [data-focus-visible])"), - ".Root [data-part=\"add-row\"] :is(:focus-visible, [data-focus-visible])" - ); - assert_eq!( - format_composed_pseudo(".Root", ":hover,[data-x]"), - ".Root:is(:hover, [data-x])" - ); - } - - #[test] - fn resolved_comma_lists_emit_with_combinators_and_intact_functions() { - let bp = test_breakpoints(); - let tc = TestUtilCtx::new(utility_config(), utility_theme(), &bp); - let styles = resolve_styles( - &json!({ - "& p + ul, & ul + p": { "display": "flex" }, - "& [data-part=\"add-row\"] :is(:focus-visible, [data-focus-visible])": { "display": "grid" }, - "&:hover, &[data-x]": { "display": "block" }, - }), - &tc.ctx(), - true, - ); - let mut out = String::new(); - write_rule_block(&mut out, "C", &styles, &bp); - assert!(out.contains(".C p + ul, .C ul + p {"), "{}", out); - assert!( - out.contains(".C [data-part=\"add-row\"] :is(:focus-visible, [data-focus-visible]) {"), - "{}", - out - ); - assert!(out.contains(".C:is(:hover, [data-x]) {"), "{}", out); - } - - #[test] - fn composed_comma_selector_inside_condition_emits_every_branch() { - let bp = test_breakpoints(); - let mut tc = TestUtilCtx::new(utility_config(), utility_theme(), &bp); - tc.aliases.insert("_hover".into(), "&:hover".into()); - let styles = resolve_styles( - &json!({ - "@container (min-width: 400px)": { - "_hover": { - "& .a:is(x, y), & .b": { "display": "flex" } - } - } - }), - &tc.ctx(), - true, - ); - assert_eq!(styles.conditioned.len(), 1, "{:?}", styles.conditioned); - assert_eq!( - styles.conditioned[0].selector.as_deref(), - Some("&:hover .a:is(x, y),&:hover .b") - ); - - let mut out = String::new(); - write_rule_block(&mut out, "C", &styles, &bp); - assert!( - out.contains(".C:hover .a:is(x, y), .C:hover .b {"), - "{}", - out - ); - assert!(!out.contains(":hovery)"), "{}", out); - assert_eq!(out.matches(".C:hover").count(), 2, "{}", out); - } - - #[test] - fn pseudo_sort_order_reads_the_whole_first_branch() { - assert_eq!(pseudo_sort_order(":is(:hover, [data-disabled])"), 200); - assert_eq!(pseudo_sort_order(":is(:focus, [aria-selected])"), 150); - assert_eq!(pseudo_sort_order(":hover"), 30); - assert_eq!(pseudo_sort_order(":hover,:focus"), 30); - assert_eq!(pseudo_sort_order(":disabled,[disabled]"), 200); - } -} diff --git a/packages/extract/crates/extractor/src/declarations.rs b/packages/extract/crates/extractor/src/declarations.rs index cd364f6e5..c70283068 100644 --- a/packages/extract/crates/extractor/src/declarations.rs +++ b/packages/extract/crates/extractor/src/declarations.rs @@ -548,34 +548,3 @@ impl<'a> DeclarationNames<'a> { pub fn breakpoint_of(entry_key: &str) -> Option<&str> { (entry_key != "_").then_some(entry_key) } - -#[cfg(test)] -mod tests { - use serde_json::json; - - use super::*; - - fn bind(scale_members: &[&str], prop_members: &[&str]) -> Result { - let mut config: PropConfigMap = serde_json::from_value(json!({ - "look": { "kind": "declarations", "scale": "looks", "members": prop_members }, - })) - .unwrap(); - let record: Map = scale_members.iter().map(|member| (member.to_string(), json!("red"))).collect(); - let scales = json!({ - "looks": { "kind": "declarations", "members": scale_members, "values": { "loud": record } }, - }) - .to_string(); - bind_declaration_props(&mut config, Some(&scales), &FlatTheme::default()) - } - - /// The system package refuses custom-property members; the engine - /// refuses the same input when it arrives as hand-written options. - #[test] - fn a_custom_property_member_is_not_a_css_property_name() { - let error = bind(&["--bg", "color"], &["color"]).unwrap_err(); - assert!(error.contains("member \"--bg\" is not a CSS property name"), "{error}"); - let error = bind(&["color"], &["--bg", "color"]).unwrap_err(); - assert!(error.contains("member \"--bg\" is not a CSS property name"), "{error}"); - assert!(bind(&["backgroundColor", "color"], &["backgroundColor", "color"]).is_ok()); - } -} diff --git a/packages/extract/crates/extractor/src/dynamic_meta.rs b/packages/extract/crates/extractor/src/dynamic_meta.rs index d9b676391..5211a72d2 100644 --- a/packages/extract/crates/extractor/src/dynamic_meta.rs +++ b/packages/extract/crates/extractor/src/dynamic_meta.rs @@ -360,55 +360,3 @@ fn scale_values( _ => BTreeMap::new(), } } - -#[cfg(test)] -mod tests { - use serde_json::json; - - use super::*; - - fn runtime_meta(contextual_vars: &str) -> ValuePropMeta { - let config: PropConfig = serde_json::from_value(json!({ - "property": "--tone", - "properties": ["--tone", "outlineColor"], - "scale": "colors", - "currentVar": "--tone", - })) - .unwrap(); - let theme: FlatTheme = [("colors.red".to_string(), "#f00".to_string())].into_iter().collect(); - let contextual_vars: ContextualVarsMap = serde_json::from_str(contextual_vars).unwrap(); - let meta = DynamicPropMeta::new("--animus-tint".into(), "animus-dyn-tint".into(), &config, &theme, &contextual_vars, &Default::default(), &ScaleValues::default()); - meta.value().unwrap().clone() - } - - #[test] - fn runtime_writes_and_the_scale_map_use_final_names() { - let meta = runtime_meta( - r#"{"colors":[{"name":"tone","var":"acme-tone"},{"name":"acme-tone","var":"acme-acme-tone"}]}"#, - ); - assert_eq!(meta.property, "--acme-tone"); - assert_eq!(meta.properties, ["--acme-tone", "outlineColor"]); - assert_eq!(meta.current_var.as_deref(), Some("--acme-tone")); - assert_eq!( - serde_json::to_value(&meta.scale_values).unwrap(), - json!({ - "red": "#f00", - "tone": "var(--acme-tone)", - "acme-tone": "var(--acme-acme-tone)", - "acme-acme-tone": "var(--acme-acme-tone)", - }) - ); - } - - #[test] - fn the_legacy_string_form_keeps_its_runtime_map() { - let meta = runtime_meta(r#"{"colors":["tone"]}"#); - assert_eq!(meta.property, "--tone"); - assert_eq!(meta.properties, ["--tone", "outlineColor"]); - assert_eq!(meta.current_var.as_deref(), Some("--tone")); - assert_eq!( - serde_json::to_value(&meta.scale_values).unwrap(), - json!({ "red": "#f00", "tone": "var(--tone)" }) - ); - } -} diff --git a/packages/extract/crates/extractor/src/emit.rs b/packages/extract/crates/extractor/src/emit.rs index e9feee2ea..d2b110f7b 100644 --- a/packages/extract/crates/extractor/src/emit.rs +++ b/packages/extract/crates/extractor/src/emit.rs @@ -52,108 +52,3 @@ pub fn apply_plan(source: &str, plan: &EmissionPlan) -> Result EmissionOutput { - apply_plan(source, plan).expect("plan should apply") - } - - const SRC: &str = "import { ds } from './sys';\nexport const Box = ds.styles({ p: 4 }).asElement('div');\nexport const App = () => ;\n"; - - #[test] - fn replaces_chain_span() { - let start = SRC.find("ds.styles").unwrap() as u32; - let end = (SRC.find(".asElement('div')").unwrap() + ".asElement('div')".len()) as u32; - let out = try_apply( - SRC, - &EmissionPlan { - replacements: vec![(start, end, "createComponent('div', 'animus-Box-1234')".into())], - ..Default::default() - }, - ); - assert!(out.code.contains("export const Box = createComponent('div', 'animus-Box-1234');")); - assert!(out.code.contains("export const App = () => ;")); - } - - #[test] - fn prepends_imports_and_removes_consumed_ones() { - let import_span = (0u32, "import { ds } from './sys';\n".len() as u32); - let out = try_apply( - SRC, - &EmissionPlan { - prepend: "import { createComponent } from '@animus-ui/react';\nimport 'virtual:animus/styles.css';\n".into(), - removals: vec![import_span], - ..Default::default() - }, - ); - assert!(out.code.starts_with("import { createComponent } from '@animus-ui/react';\n")); - assert!(!out.code.contains("from './sys'")); - assert!(out.code.contains("export const Box = ds.styles")); - } - - #[test] - fn edits_compose_and_map_is_produced() { - let start = SRC.find("ds.styles").unwrap() as u32; - let end = (SRC.find(".asElement('div')").unwrap() + ".asElement('div')".len()) as u32; - let out = try_apply( - SRC, - &EmissionPlan { - replacements: vec![(start, end, "X()".into())], - prepend: "'use client';\n".into(), - removals: vec![(0, "import { ds } from './sys';\n".len() as u32)], - }, - ); - assert!(out.code.starts_with("'use client';\n")); - assert!(out.code.contains("export const Box = X();")); - assert!(out.map_json.contains("\"mappings\"")); - assert!(!out.map_json.contains("\"mappings\":\"\"")); - } - - #[test] - fn overlapping_edits_error_loudly() { - let start = SRC.find("ds.styles").unwrap() as u32; - let end = (SRC.find(".asElement('div')").unwrap() + ".asElement('div')".len()) as u32; - let result = apply_plan( - SRC, - &EmissionPlan { - replacements: vec![(start, end, "X()".into())], - removals: vec![(start + 2, end + 2)], - ..Default::default() - }, - ); - assert!(result.is_err(), "overlap must error, got: {result:?}"); - } - - #[test] - fn multibyte_source_before_edit_span() { - // oxc spans are UTF-8 byte offsets; string_wizard indexes bytes too. - let src = "const label = '日本語ラベル'; -const x = old(); -"; - let start = src.find("old()").unwrap() as u32; - let out = try_apply( - src, - &EmissionPlan { - replacements: vec![(start, start + "old()".len() as u32, "new_()".into())], - ..Default::default() - }, - ); - assert!(out.code.contains("const x = new_();")); - assert!(out.code.contains("日本語ラベル")); - } - - #[test] - fn untouched_bytes_are_preserved_exactly() { - let out = try_apply( - SRC, - &EmissionPlan { - removals: vec![(0, 5)], - ..Default::default() - }, - ); - assert_eq!(out.code, &SRC[5..]); - } -} diff --git a/packages/extract/crates/extractor/src/engine.rs b/packages/extract/crates/extractor/src/engine.rs index 1883394d0..d479a3f20 100644 --- a/packages/extract/crates/extractor/src/engine.rs +++ b/packages/extract/crates/extractor/src/engine.rs @@ -1411,10 +1411,6 @@ impl ExtractEngine { ); let changes = flow.close(); clock.mark("flow"); - #[cfg(test)] - OPENINGS.with(|openings| openings.borrow_mut().clear()); - #[cfg(test)] - note_openings("style statics", &changes); for ((file, local), (reason, uncertainty, openings)) in unstable_style_statics(&changes, &statics_by_file) { if statics_by_file.get_mut(&file).and_then(|statics| statics.remove(&local)).is_some() { // Only a value the binding had before const initializers read @@ -2069,23 +2065,6 @@ impl ExtractEngine { } } -#[cfg(test)] -thread_local! { - /// The last analysis's openings on this thread, by relation, kind and - /// site. - static OPENINGS: std::cell::RefCell> = - const { std::cell::RefCell::new(std::collections::BTreeSet::new()) }; -} - -/// Adds the openings of `relation`, closed, to the analysis's, for check 6. -#[cfg(test)] -pub(crate) fn note_openings(relation: &'static str, changes: &crate::flow::ValueEffects) { - OPENINGS.with(|openings| { - let mut openings = openings.borrow_mut(); - openings.extend(changes.closure().openings.iter().map(|opening| (relation, opening.reason, opening.site.clone()))); - }); -} - #[cfg(test)] mod tests { use super::*; @@ -2317,34 +2296,6 @@ mod tests { assert_eq!(replayed, plain); } - /// Contract: `prepare` names every base analysis probes, so a session - /// that gathers evidence for its bases leaves no probe unanswered: - /// imports, re-exports, `import()` and an alias's expansion alike. - #[test] - fn prepare_names_every_base_analysis_probes() { - let mut engine = ExtractEngine::new(Some(EngineOptions { - path_aliases_json: Some(r#"{"aliases":[{"pattern":"@ui/","replacement":"ui/","type":"prefix"}]}"#.to_string()), - ..Default::default() - })) - .unwrap(); - let files = serde_json::json!([ - { "path": "src/app.tsx", "source": "import { Box } from './box';\nexport { Row } from '../row';\nimport { Card } from '@ui/card';\nconst Lazy = () => import('./lazy');\nexport const App = () => ;" }, - { "path": "src/box.tsx", "source": "export const Box = ds.styles({ p: 4 }).asElement('div');" }, - { "path": "row.tsx", "source": "export const Row = ds.styles({ m: 2 }).asElement('div');" }, - { "path": "ui/card.tsx", "source": "export const Card = ds.styles({ p: 1 }).asElement('div');" }, - { "path": "src/lazy.tsx", "source": "export default 1;" }, - ]) - .to_string(); - let prepared: serde_json::Value = serde_json::from_str(&engine.prepare(files.clone()).unwrap()).unwrap(); - let bases: std::collections::BTreeSet = serde_json::from_value(prepared["bases"].clone()).unwrap(); - crate::analyze_css::PROBED.with(|probed| probed.borrow_mut().clear()); - engine.analyze(files, None).unwrap(); - let probed = crate::analyze_css::PROBED.with(|probed| probed.borrow().clone()); - assert!(!probed.is_empty()); - let unprepared: Vec<_> = probed.difference(&bases).collect(); - assert!(unprepared.is_empty(), "probed without a prepared base: {unprepared:?} (prepared {bases:?})"); - } - /// Contract: an object-use diagnostic names the 1-based line of the /// use, however far into the file it is. #[test] @@ -4247,7 +4198,6 @@ export const App = () => ; lost_properties: std::collections::BTreeSet<(String, String, String)>, pruned: std::collections::BTreeSet<(String, String, String)>, removed_imports: std::collections::BTreeSet<(String, String)>, - openings: std::collections::BTreeSet<(&'static str, crate::flow::ReasonId, String)>, } fn emission(files: &[(String, String)]) -> Emission { @@ -4328,7 +4278,6 @@ export const App = () => ; let removed = specifiers(source).into_iter().filter(|specifier| !kept.contains(specifier)); out.removed_imports.extend(removed.map(|specifier| (path.clone(), specifier))); } - out.openings = super::OPENINGS.with(|openings| openings.borrow().clone()); out } @@ -4382,7 +4331,6 @@ export const App = () => ; found.extend( head.removed_imports.difference(&base.removed_imports).map(|import| format!("import {import:?} newly removed")), ); - found.extend(base.openings.difference(&head.openings).map(|opening| format!("opening {opening:?} lost"))); found } @@ -4447,15 +4395,7 @@ export const App = () => ; base.pruned.len(), base.lost_properties.len(), ]; - // Each relation has an opening to keep, compared within that relation. - let opens = |relation| base.openings.iter().any(|(of, ..)| *of == relation); - assert!( - channels.iter().all(|count| *count > 0) - && !base.removed_imports.is_empty() - && opens("style statics") - && opens("member tables"), - "{base:?}" - ); + assert!(channels.iter().all(|count| *count > 0) && !base.removed_imports.is_empty(), "{base:?}"); for injected in injections { let mut files = project.clone(); files.push(file("opaque.ts", &injected)); @@ -5790,40 +5730,6 @@ export const App = () => ; assert!(code.contains("export const shared = ds.styles"), "{code}"); } - /// Every spelling of one path is one analysis identity; case, a query, a - /// parent above a relative start and each kind of root stay distinct, - /// and no `..` climbs past a root (Node's `path.win32.normalize` cases). - #[test] - fn spellings_of_one_path_share_an_analysis_id() { - for (path, id) in [ - ("a/b.tsx", "a/b.tsx"), - ("a\\b.tsx", "a/b.tsx"), - ("./a.tsx", "a.tsx"), - ("dir/../a.tsx", "a.tsx"), - ("a//b/./c.tsx", "a/b/c.tsx"), - ("../../packages/ui/x.tsx", "../../packages/ui/x.tsx"), - ("/root/../x.tsx", "/x.tsx"), - ("/../x.tsx", "/x.tsx"), - ("\\..\\x.tsx", "/x.tsx"), - ("A.tsx", "A.tsx"), - ("a.svelte?type=script&lang=../x", "a.svelte?type=script&lang=../x"), - ("./a.svelte?raw", "a.svelte?raw"), - ("C:/../a.tsx", "C:/a.tsx"), - ("C:\\..\\a.tsx", "C:/a.tsx"), - ("C:\\x\\..\\..\\y.tsx", "C:/y.tsx"), - ("C:..\\a.tsx", "C:../a.tsx"), - ("C:x\\..\\..\\y.tsx", "C:../y.tsx"), - ("C:", "C:"), - ("C:/", "C:/"), - ("//host/share/../../a.tsx", "//host/share/a.tsx"), - ("\\\\host\\share\\..\\..\\a.tsx", "//host/share/a.tsx"), - ("//host/share/a.tsx", "//host/share/a.tsx"), - ("/host/share/a.tsx", "/host/share/a.tsx"), - ] { - assert_eq!(canonical_analysis_id(path), id, "{path}"); - } - } - /// A path listed twice with the same source is analysed once; listed /// twice with different sources, or as two spellings of one file, it /// fails the analysis. A query names another input. diff --git a/packages/extract/crates/extractor/src/eval.rs b/packages/extract/crates/extractor/src/eval.rs index 8b6ab1ddc..807057ea5 100644 --- a/packages/extract/crates/extractor/src/eval.rs +++ b/packages/extract/crates/extractor/src/eval.rs @@ -1699,904 +1699,3 @@ pub fn collect_static_exports( exports } - - -#[cfg(test)] -mod tests { - - /// A statics map as JSON, for assertions. - fn plain_map(values: FxHashMap) -> FxHashMap { - values.iter().map(|(name, value)| (name.clone(), plain(value))).collect() - } - - /// JSON test data as a static value. - fn from_json(value: &Value) -> StaticValue { - match value { - Value::Null => StaticValue::Null, - Value::Bool(flag) => StaticValue::Bool(*flag), - Value::Number(number) => StaticValue::Number(StaticNumber(number.clone())), - Value::String(text) => StaticValue::String(text.clone()), - Value::Array(items) => StaticValue::Array(items.iter().map(from_json).collect()), - Value::Object(entries) => { - StaticValue::Object(entries.iter().map(|(key, value)| (key.clone(), from_json(value))).collect()) - } - } - } - - fn statics_of(values: &FxHashMap) -> FxHashMap { - values.iter().map(|(name, value)| (name.clone(), from_json(value))).collect() - } - use super::*; - use serde_json::Map; - use crate::owned_ast::{OwnedAst, ParseCounter}; - - fn parse_ts(full: String) -> OwnedAst { - let counter = ParseCounter::new(0); - OwnedAst::parse("test.ts".into(), full, &counter) - } - - fn parse_obj_all(source: &str) -> (Value, Vec, Vec) { - let ast = parse_ts(format!("const x = {};", source)); - let program = ast.program(); - - if let Some(oxc::ast::ast::Statement::VariableDeclaration(decl)) = program.body.first() { - if let Some(declarator) = decl.declarations.first() { - if let Some(Expression::ObjectExpression(obj)) = &declarator.init { - let (value, skips, captures) = eval_object_expr(obj).unwrap(); - return (plain(&value), skips, captures); - } - } - } - panic!("failed to parse object expression"); - } - - fn parse_obj_full(source: &str) -> (Value, Vec) { - let (val, skips, _captures) = parse_obj_all(source); - (val, skips) - } - - fn parse_obj(source: &str) -> Value { - parse_obj_full(source).0 - } - - fn parse_obj_err(source: &str) -> String { - let ast = parse_ts(format!("const x = {};", source)); - let program = ast.program(); - - if let Some(oxc::ast::ast::Statement::VariableDeclaration(decl)) = program.body.first() { - if let Some(declarator) = decl.declarations.first() { - if let Some(Expression::ObjectExpression(obj)) = &declarator.init { - return eval_object_expr(obj).unwrap_err().reason; - } - } - } - panic!("failed to parse"); - } - - fn parse_variant(source: &str) -> (VariantStageConfig, Vec) { - parse_variant_with_statics(source, None) - } - - fn parse_variant_with_statics( - source: &str, - sv: Option<&FxHashMap>, - ) -> (VariantStageConfig, Vec) { - let ast = parse_ts(format!("const x = {};", source)); - let program = ast.program(); - - if let Some(oxc::ast::ast::Statement::VariableDeclaration(decl)) = program.body.first() { - if let Some(declarator) = decl.declarations.first() { - if let Some(Expression::ObjectExpression(obj)) = &declarator.init { - let typed = sv.map(statics_of); - return parse_variant_arg(obj, typed.as_ref().map(|typed| Statics::of(typed, "test.ts"))).unwrap(); - } - } - } - panic!("failed to parse variant config object"); - } - - /// Contract: a skip carries the kind of what evaluation could not - /// settle, from its own site (spec §6.2, `Unevaluated(kind)`). - #[test] - fn a_skip_carries_the_kind_of_what_evaluation_could_not_settle() { - let object_kind = |source: &str| { - let (_, skips, _) = parse_obj_all(source); - skips.iter().map(|skip| skip.kind).collect::>() - }; - let variant_kind = |source: &str| { - let (_, skips) = parse_variant(source); - skips.iter().map(|skip| skip.kind).collect::>() - }; - assert_eq!(object_kind("{ a: unknown + 1 }"), [UnevaluatedKind::Operator]); - assert_eq!(object_kind("{ a: [() => 1] }"), [UnevaluatedKind::Function]); - assert_eq!(object_kind("{ a: [`x${unknown}`] }"), [UnevaluatedKind::Template]); - assert_eq!(object_kind("{ a: [!unknown] }"), [UnevaluatedKind::Operator]); - assert_eq!(object_kind("{ a: [unknown.x] }"), [UnevaluatedKind::Reference]); - assert_eq!(variant_kind("{ prop: 'size', variants: { sm: {}, ...rest } }"), [UnevaluatedKind::Spread]); - assert_eq!(variant_kind("{ prop: 'size', variants: selectSizes }"), [UnevaluatedKind::Reference]); - assert_eq!(variant_kind("{ prop: name, variants: {} }"), [UnevaluatedKind::Reference]); - } - - /// Contract (spec §6.2 F1a): `static_value` is `Exact` only where - /// evaluation settled every node on the path and nothing may change the - /// binding. An unevaluated node is `Unevaluated(kind)` at its path in the - /// binding's object; an unsettled binding is Flow's exposure of it, - /// joined with an unevaluated node of its held value. - #[test] - fn a_static_read_is_known_as_evaluation_and_flow_leave_it() { - use crate::flow::{ChangeKind, Known, ObjectId, ReasonId, Region, RegionAtom, Uncertainty}; - let ast = parse_ts("const preset = { size: 4, tone: pick() };".to_string()); - let values = collect_static_values(ast.program(), "m.ts"); - let path = |segments: &[&str]| segments.iter().map(|segment| segment.to_string()).collect::>(); - let unevaluated = Uncertainty::new( - ReasonId::Unevaluated(UnevaluatedKind::Call), - Region::of(RegionAtom::Path(ObjectId::new("m.ts", "preset"), path(&["tone"]))), - ); - let statics = Statics::of(&values, "m.ts"); - - assert_eq!( - static_value(statics, "preset", &["size"]), - Some(Known::Exact(&StaticValue::Number(StaticNumber(4.into())))), - ); - assert_eq!(static_value(statics, "preset", &["tone"]), Some(Known::Uncertain(unevaluated.clone()))); - - let written = Uncertainty::new( - ReasonId::Changed(ChangeKind::Write), - Region::of(RegionAtom::Path(ObjectId::new("m.ts", "preset"), path(&["size"]))), - ); - let unsettled = FxHashMap::from_iter([( - "preset".to_string(), - Unsettled { - reason: "preset.size is written".to_string(), - uncertainty: written.clone(), - held: values.get("preset").cloned(), - openings: Vec::new(), - }, - )]); - let none = FxHashMap::default(); - let held = Statics::new(&none, &unsettled, "m.ts"); - - assert_eq!(static_value(held, "preset", &["size"]), Some(Known::Uncertain(written.clone()))); - assert_eq!(static_value(held, "preset", &["tone"]), Some(Known::Uncertain(written.join(unevaluated)))); - assert_eq!(uncertain_clause(held, "preset", &["tone"]), Some("preset.size is written")); - } - - #[test] - fn variant_identifier_map_records_skip_instead_of_silent_empty() { - let (cfg, skips) = - parse_variant("{ prop: 'size', defaultVariant: 'lg', variants: selectSizes }"); - assert!(plain(&cfg.variants).as_object().is_some_and(Map::is_empty), "{:?}", cfg.variants); - assert_eq!(cfg.default_variant.as_deref(), Some("lg")); - assert_eq!(cfg.prop, "size"); - assert_eq!(skips.len(), 1, "{:?}", skips); - assert_eq!(skips[0].key, "variants"); - assert!( - skips[0].reason.contains("variant map (non-static)"), - "{}", - skips[0].reason - ); - } - - #[test] - fn variant_spread_map_records_skip_instead_of_silent_empty() { - let (cfg, skips) = - parse_variant("{ prop: 'size', defaultVariant: 'lg', variants: { ...sizes } }"); - assert!(plain(&cfg.variants).as_object().is_some_and(Map::is_empty), "{:?}", cfg.variants); - assert_eq!(cfg.default_variant.as_deref(), Some("lg")); - assert_eq!(skips.len(), 1, "{:?}", skips); - assert_eq!(skips[0].key, "variants"); - assert!( - skips[0].reason.contains("variant map spread (non-static)"), - "{}", - skips[0].reason - ); - } - - // Contract: a boolean `defaultVariant` names its key, as the runtime and - // the variant's `'true'`/`'false'` keys do. - #[test] - fn boolean_default_variant_names_its_key() { - let (cfg, skips) = parse_variant("{ prop: 'fit', defaultVariant: true, variants: { true: {}, false: {} } }"); - assert_eq!(cfg.default_variant.as_deref(), Some("true")); - assert!(skips.is_empty(), "{skips:?}"); - let (cfg, _) = parse_variant("{ prop: 'fit', defaultVariant: false, variants: { true: {}, false: {} } }"); - assert_eq!(cfg.default_variant.as_deref(), Some("false")); - } - - #[test] - fn variant_config_spread_records_skip_instead_of_silent_absence() { - let (cfg, skips) = parse_variant("{ ...cfg }"); - assert!(plain(&cfg.variants).as_object().is_some_and(Map::is_empty), "{:?}", cfg.variants); - assert_eq!(cfg.default_variant, None); - assert_eq!(skips.len(), 1, "{:?}", skips); - assert_eq!(skips[0].key, "variant config"); - assert!( - skips[0].reason.contains("variant config spread (non-static)"), - "{}", - skips[0].reason - ); - } - - #[test] - fn variant_spread_alongside_literal_options_still_records_the_spread() { - let (cfg, skips) = - parse_variant("{ prop: 'size', variants: { sm: { p: 8 }, ...rest } }"); - assert_eq!(plain(&cfg.variants).as_object().map_or(0, Map::len), 1); - assert_eq!(skips.len(), 1, "{:?}", skips); - assert!( - skips[0].reason.contains("variant map spread (non-static)"), - "{}", - skips[0].reason - ); - } - - #[test] - fn variant_literal_map_records_no_extra_skip() { - let (cfg, skips) = parse_variant( - "{ prop: 'size', defaultVariant: 'lg', base: { p: 4 }, variants: { sm: { p: 8 }, lg: { p: 16 } } }", - ); - assert_eq!(plain(&cfg.variants).as_object().map_or(0, Map::len), 2); - assert!(cfg.base.is_some()); - assert!(skips.is_empty(), "{:?}", skips); - } - - #[test] - fn variant_non_literal_prop_default_and_base_record_skips() { - let (cfg, skips) = parse_variant( - "{ prop: propName, defaultVariant: fallback, base: sharedBase, variants: {} }", - ); - assert_eq!(cfg.prop, "variant"); - assert!(cfg.default_variant.is_none()); - assert!(cfg.base.is_none()); - let keys: Vec<&str> = skips.iter().map(|s| s.key.as_str()).collect(); - assert_eq!(skips.len(), 3, "{:?}", skips); - assert!(keys.contains(&"prop"), "{:?}", skips); - assert!(keys.contains(&"defaultVariant"), "{:?}", skips); - assert!(keys.contains(&"base"), "{:?}", skips); - assert!( - skips.iter().all(|s| s.reason.contains("non-static")), - "{:?}", - skips - ); - } - - #[test] - fn eval_simple_object() { - let val = parse_obj(r#"{ p: 0, display: 'inline-flex', borderRadius: 4 }"#); - assert_eq!(val["p"], 0); - assert_eq!(val["display"], "inline-flex"); - assert_eq!(val["borderRadius"], 4); - } - - #[test] - fn eval_nested_pseudo() { - let val = parse_obj(r#"{ '&:hover': { color: 'primary' } }"#); - assert_eq!(val["&:hover"]["color"], "primary"); - } - - #[test] - fn eval_responsive_object() { - let val = parse_obj(r#"{ fontSize: { _: 16, xs: 18 } }"#); - assert_eq!(val["fontSize"]["_"], 16); - assert_eq!(val["fontSize"]["xs"], 18); - } - - #[test] - fn eval_string_keys() { - let val = parse_obj(r#"{ '&:nth-child(even)': { bg: 'muted' } }"#); - assert_eq!(val["&:nth-child(even)"]["bg"], "muted"); - } - - #[test] - fn eval_negative_number() { - let val = parse_obj(r#"{ top: -1 }"#); - assert_eq!(val["top"], -1); - } - - #[test] - fn eval_boolean_value() { - let val = parse_obj(r#"{ hidden: true }"#); - assert_eq!(val["hidden"], true); - } - - #[test] - fn eval_array_value() { - let val = parse_obj(r#"{ p: [8, 12, 16] }"#); - let arr = val["p"].as_array().unwrap(); - assert_eq!(arr.len(), 3); - assert_eq!(arr[0], 8); - } - - #[test] - fn eval_static_template_literal() { - let val = parse_obj(r#"{ content: '""' }"#); - assert_eq!(val["content"], "\"\""); - } - - #[test] - fn skip_variable_reference_keep_others() { - let (val, skips) = parse_obj_full(r#"{ color: someVariable, display: 'flex' }"#); - assert_eq!(val["display"], "flex"); - assert!(val.get("color").is_none()); - assert_eq!(skips.len(), 1); - assert_eq!(skips[0].key, "color"); - assert!(skips[0].reason.contains("non-static")); - } - - #[test] - fn skip_function_call_keep_others() { - let (val, skips) = parse_obj_full(r#"{ background: arr.join(''), p: 16 }"#); - assert_eq!(val["p"], 16); - assert!(val.get("background").is_none()); - assert_eq!(skips.len(), 1); - assert_eq!(skips[0].key, "background"); - } - - #[test] - fn skip_template_with_expression_keep_others() { - let (val, skips) = parse_obj_full("{ animation: `${flow} 5s`, opacity: 1 }"); - assert_eq!(val["opacity"], 1); - assert!(val.get("animation").is_none()); - assert_eq!(skips.len(), 1); - assert_eq!(skips[0].key, "animation"); - } - - /// Contract: a template with no substitution, or whose every substitution - /// is a static string or number, evaluates as JavaScript does, to its - /// cooked text with each number as `String(n)` writes it; a number this - /// cannot prove it prints that way (beyond ±2^53, or with an exponent) - /// keeps the skip. - #[test] - fn template_with_static_substitutions_evaluates() { - let (val, skips) = parse_obj_full( - "{ width: `${8}px`, inset: `${0.5}rem`, content: `\"${'絵'}\"`, top: `${1e-7}px`, \ - color: `\\u0072${'ed'}`, quotes: `\"${1000000000000000100}\"`, safe: `${9007199254740992}`, \ - fill: `\\u0072ed` }", - ); - assert_eq!(val["width"], "8px"); - assert_eq!(val["inset"], "0.5rem"); - assert_eq!(val["content"], "\"絵\""); - assert_eq!(val["color"], "red"); - assert_eq!(val["fill"], "red"); - assert_eq!(val["safe"], "9007199254740992"); - assert!(val.get("quotes").is_none()); - assert!(val.get("top").is_none()); - assert_eq!(skips.iter().map(|skip| skip.key.as_str()).collect::>(), ["top", "quotes"]); - } - - #[test] - fn skip_member_expression_keep_others() { - let (val, skips) = parse_obj_full(r#"{ color: theme.colors.primary, padding: '8px' }"#); - assert_eq!(val["padding"], "8px"); - assert!(val.get("color").is_none()); - assert_eq!(skips.len(), 1); - assert_eq!(skips[0].key, "color"); - } - - #[test] - fn skip_all_non_static_returns_empty() { - let (val, skips) = parse_obj_full(r#"{ bg: dynamicA, color: dynamicB }"#); - assert_eq!(val.as_object().unwrap().len(), 0); - assert_eq!(skips.len(), 2); - } - - #[test] - fn skip_inside_pseudo_selector() { - let (val, skips) = parse_obj_full(r#"{ '&:hover': { color: dynamicVar, bg: 'red' } }"#); - assert_eq!(val["&:hover"]["bg"], "red"); - assert!(val["&:hover"].get("color").is_none()); - assert_eq!(skips.len(), 1); - assert_eq!(skips[0].key, "color"); - } - - #[test] - fn skip_non_static_pseudo_value() { - let (val, skips) = parse_obj_full(r#"{ '&:hover': someFunction(), color: 'red' }"#); - assert_eq!(val["color"], "red"); - assert!(val.get("&:hover").is_none()); - assert_eq!(skips.len(), 1); - assert_eq!(skips[0].key, "&:hover"); - } - - #[test] - fn spread_inside_nested_skips_parent() { - let (val, skips) = parse_obj_full(r#"{ '&:hover': { ...hoverOverrides, bg: 'red' }, color: 'blue' }"#); - assert_eq!(val["color"], "blue"); - assert!(val.get("&:hover").is_none()); - assert_eq!(skips.len(), 1); - assert_eq!(skips[0].key, "&:hover"); - assert!(skips[0].reason.contains("spread")); - } - - #[test] - fn bail_on_spread() { - let reason = parse_obj_err(r#"{ ...baseStyles }"#); - assert!(reason.contains("spread")); - } - - #[test] - fn bail_on_spread_even_with_static_props() { - let reason = parse_obj_err(r#"{ ...baseStyles, color: 'red' }"#); - assert!(reason.contains("spread")); - } - - #[test] - fn capture_arrow_on_transform_field() { - let (val, skips, captured) = parse_obj_all( - r#"{ property: 'flexBasis', transform: (v) => v + 'px' }"#, - ); - assert_eq!(val["property"], "flexBasis"); - assert!(val.get("transform").is_none()); - assert_eq!(skips.len(), 0); - assert_eq!(captured.len(), 1); - assert_eq!(captured[0].key, "transform"); - } - - #[test] - fn capture_function_expr_on_transform_field() { - let (val, _skips, captured) = parse_obj_all( - r#"{ property: 'gap', transform: function(v) { return v + 'px'; } }"#, - ); - assert_eq!(val["property"], "gap"); - assert!(val.get("transform").is_none()); - assert_eq!(captured.len(), 1); - assert_eq!(captured[0].key, "transform"); - } - - #[test] - fn identifier_on_transform_field_still_skips() { - let (val, skips, captured) = parse_obj_all( - r#"{ property: 'flexBasis', transform: myTransform }"#, - ); - assert_eq!(val["property"], "flexBasis"); - assert_eq!(skips.len(), 1); - assert_eq!(skips[0].key, "transform"); - assert!(skips[0].reason.contains("non-static")); - assert_eq!(captured.len(), 0); - } - - #[test] - fn string_literal_on_transform_field_still_evaluates() { - let (val, skips, captured) = parse_obj_all( - r#"{ property: 'flexBasis', transform: 'size' }"#, - ); - assert_eq!(val["property"], "flexBasis"); - assert_eq!(val["transform"], "size"); - assert_eq!(skips.len(), 0); - assert_eq!(captured.len(), 0); - } - - #[test] - fn arrow_on_non_transform_field_still_bails() { - let (val, skips, captured) = parse_obj_all( - r#"{ property: 'flexBasis', scale: (v) => v * 2 }"#, - ); - assert_eq!(val["property"], "flexBasis"); - assert_eq!(skips.len(), 1); - assert_eq!(skips[0].key, "scale"); - assert!(skips[0].reason.contains("arrow function")); - assert_eq!(captured.len(), 0); - } - - #[test] - fn nested_object_with_transform_capture_prefixes_key() { - let (val, skips, captured) = parse_obj_all( - r#"{ sizing: { property: 'flexBasis', transform: (v) => v + 'px' } }"#, - ); - assert_eq!(val["sizing"]["property"], "flexBasis"); - assert!(val["sizing"].get("transform").is_none()); - assert_eq!(skips.len(), 0); - assert_eq!(captured.len(), 1); - assert_eq!(captured[0].key, "sizing.transform"); - } - - #[test] - fn multiple_nested_transforms_captured() { - let (val, _skips, captured) = parse_obj_all( - r#"{ sizing: { property: 'flexBasis', transform: (v) => v + 'px' }, ratio: { property: 'width', transform: (v) => v * 100 + '%' } }"#, - ); - assert_eq!(val["sizing"]["property"], "flexBasis"); - assert_eq!(val["ratio"]["property"], "width"); - assert_eq!(captured.len(), 2); - let keys: Vec<&str> = captured.iter().map(|c| c.key.as_str()).collect(); - assert!(keys.contains(&"sizing.transform")); - assert!(keys.contains(&"ratio.transform")); - } - - #[test] - fn intra_file_numeric_const_resolution() { - let source = r#"const GAP = 16; -const Component = { gap: GAP };"#; - let ast = parse_ts(source.to_string()); - let result_program = ast.program(); - let values = plain_map(collect_static_values(result_program, "test.ts")); - assert_eq!(values.get("GAP"), Some(&Value::Number(16.into()))); - } - - #[test] - fn intra_file_string_const_resolution() { - let source = r#"const COLOR = 'red';"#; - let ast = parse_ts(source.to_string()); - let result_program = ast.program(); - let values = plain_map(collect_static_values(result_program, "test.ts")); - assert_eq!(values.get("COLOR"), Some(&Value::String("red".to_string()))); - } - - #[test] - fn non_static_const_not_collected() { - let source = r#"const val = getSpacing();"#; - let ast = parse_ts(source.to_string()); - let result_program = ast.program(); - let values = plain_map(collect_static_values(result_program, "test.ts")); - assert!(!values.contains_key("val")); - } - - #[test] - fn let_declaration_not_collected() { - let source = r#"let gap = 16;"#; - let ast = parse_ts(source.to_string()); - let result_program = ast.program(); - let values = plain_map(collect_static_values(result_program, "test.ts")); - assert!(!values.contains_key("gap")); - } - - #[test] - fn const_object_collected() { - let source = r#"const config = { gap: 16, display: 'flex' };"#; - let ast = parse_ts(source.to_string()); - let result_program = ast.program(); - let values = plain_map(collect_static_values(result_program, "test.ts")); - let config = &values["config"]; - assert_eq!(config["gap"], 16); - assert_eq!(config["display"], "flex"); - } - - #[test] - fn identifier_resolved_via_static_values() { - let mut sv = FxHashMap::default(); - sv.insert("GAP".to_string(), Value::Number(16.into())); - - let (val, skips, _) = parse_obj_with_statics("{ gap: GAP }", Some(&sv)); - assert_eq!(val["gap"], 16); - assert!(skips.is_empty()); - } - - #[test] - fn identifier_not_in_static_values_skips() { - let sv = FxHashMap::default(); - - let (_, skips, _) = parse_obj_with_statics("{ gap: UNKNOWN }", Some(&sv)); - assert_eq!(skips.len(), 1); - assert_eq!(skips[0].key, "gap"); - } - - #[test] - fn exported_const_collected() { - let source = r#"export const SPACING = 8;"#; - let ast = parse_ts(source.to_string()); - let result_program = ast.program(); - let values = plain_map(collect_static_values(result_program, "test.ts")); - assert_eq!(values.get("SPACING"), Some(&Value::Number(8.into()))); - } - - #[test] - fn member_expression_resolved_via_static_values_object() { - let mut sv = FxHashMap::default(); - let mut motion = Map::new(); - motion.insert("ember".to_string(), Value::String("animus-kf-abc".to_string())); - motion.insert("flow".to_string(), Value::String("animus-kf-xyz".to_string())); - sv.insert("motion".to_string(), Value::Object(motion)); - - let (val, skips, _) = - parse_obj_with_statics("{ animationName: motion.ember }", Some(&sv)); - assert_eq!(val["animationName"], "animus-kf-abc"); - assert!(skips.is_empty()); - } - - #[test] - fn member_expression_unknown_key_skips() { - let mut sv = FxHashMap::default(); - let mut motion = Map::new(); - motion.insert("ember".to_string(), Value::String("animus-kf-abc".to_string())); - sv.insert("motion".to_string(), Value::Object(motion)); - - let (val, skips, _) = - parse_obj_with_statics("{ animationName: motion.unknown }", Some(&sv)); - assert!(val.get("animationName").is_none()); - assert_eq!(skips.len(), 1); - assert_eq!(skips[0].key, "animationName"); - } - - #[test] - fn member_expression_base_not_in_statics_skips() { - let sv = FxHashMap::default(); - let (val, skips, _) = - parse_obj_with_statics("{ animationName: motion.ember }", Some(&sv)); - assert!(val.get("animationName").is_none()); - assert_eq!(skips.len(), 1); - assert_eq!(skips[0].key, "animationName"); - } - - #[test] - fn member_expression_falls_back_when_base_is_not_object() { - let mut sv = FxHashMap::default(); - sv.insert("GAP".to_string(), Value::Number(16.into())); - let (val, skips, _) = - parse_obj_with_statics("{ animationName: GAP.nested }", Some(&sv)); - assert!(val.get("animationName").is_none()); - assert_eq!(skips.len(), 1); - } - - #[test] - fn member_expression_keeps_other_static_props() { - let mut sv = FxHashMap::default(); - let mut motion = Map::new(); - motion.insert("ember".to_string(), Value::String("animus-kf-abc".to_string())); - sv.insert("motion".to_string(), Value::Object(motion)); - - let (val, skips, _) = parse_obj_with_statics( - "{ animationName: motion.ember, animationDuration: '5s' }", - Some(&sv), - ); - assert_eq!(val["animationName"], "animus-kf-abc"); - assert_eq!(val["animationDuration"], "5s"); - assert!(skips.is_empty()); - } - - #[test] - fn member_expression_skip_codes_an_unregistered_collection_and_names_the_repair() { - let sv = FxHashMap::default(); - let (_, skips, _) = parse_obj_with_statics("{ animationName: motion.pulse }", Some(&sv)); - assert_eq!(skips.len(), 1, "{:?}", skips); - let reason = &skips[0].reason; - assert!( - reason.contains("member expression 'motion.pulse'"), - "{reason}" - ); - assert!(reason.contains("non-static"), "{reason}"); - assert!( - reason.contains("is neither a registered keyframe collection"), - "{reason}" - ); - assert!( - reason.contains("register it on the system between build() and seal()"), - "{reason}" - ); - assert!( - reason.contains("the registration key must equal the export name"), - "{reason}" - ); - assert!( - reason.ends_with(&format!("({KEYFRAMES_UNREGISTERED_REFERENCE})")), - "{reason}" - ); - assert_eq!( - crate::analyze_css::diagnostic_code_from_message(reason).as_deref(), - Some(KEYFRAMES_UNREGISTERED_REFERENCE), - "{reason}" - ); - } - - #[test] - fn keyframes_code_is_scoped_to_animation_name_properties() { - let sv = FxHashMap::default(); - let (_, skips, _) = parse_obj_with_statics("{ color: palette.brand }", Some(&sv)); - assert_eq!(skips.len(), 1, "{:?}", skips); - let reason = &skips[0].reason; - assert!( - reason.contains("member expression 'palette.brand'"), - "{reason}" - ); - assert!( - reason.contains("'palette' is not an extraction-time static binding"), - "{reason}" - ); - assert!( - !reason.contains("keyframe") && !reason.contains("build() and seal()"), - "keyframes advice must not leak onto unrelated properties: {reason}" - ); - assert_eq!( - crate::analyze_css::diagnostic_code_from_message(reason), - None, - "{reason}" - ); - } - - #[test] - fn keyframes_code_fires_through_the_responsive_form() { - let sv = FxHashMap::default(); - let (_, skips, _) = - parse_obj_with_statics("{ animationName: { _: motion.pulse } }", Some(&sv)); - assert_eq!(skips.len(), 1, "{:?}", skips); - let reason = &skips[0].reason; - assert_eq!( - crate::analyze_css::diagnostic_code_from_message(reason).as_deref(), - Some(KEYFRAMES_UNREGISTERED_REFERENCE), - "{reason}" - ); - } - - #[test] - fn responsive_form_of_an_unrelated_property_stays_uncoded() { - let sv = FxHashMap::default(); - let (_, skips, _) = - parse_obj_with_statics("{ color: { _: palette.brand } }", Some(&sv)); - assert_eq!(skips.len(), 1, "{:?}", skips); - let reason = &skips[0].reason; - assert!( - reason.contains("'palette' is not an extraction-time static binding"), - "{reason}" - ); - assert_eq!( - crate::analyze_css::diagnostic_code_from_message(reason), - None, - "{reason}" - ); - } - - #[test] - fn member_expression_skip_names_a_missing_member_of_a_registered_collection() { - let mut sv = FxHashMap::default(); - let mut motion = Map::new(); - motion.insert("ember".to_string(), Value::String("animus-kf-abc".to_string())); - sv.insert("motion".to_string(), Value::Object(motion)); - - let (_, skips, _) = parse_obj_with_statics("{ animationName: motion.pulse }", Some(&sv)); - assert_eq!(skips.len(), 1, "{:?}", skips); - let reason = &skips[0].reason; - assert!( - reason.contains("member expression 'motion.pulse'"), - "{reason}" - ); - assert!( - reason.contains("registered collection with no 'pulse' member"), - "{reason}" - ); - assert_eq!( - crate::analyze_css::diagnostic_code_from_message(reason), - None, - "{reason}" - ); - } - - #[test] - fn member_expression_skip_without_statics_reports_missing_context() { - let (_, skips) = parse_obj_full("{ animationName: motion.pulse }"); - assert_eq!(skips.len(), 1, "{:?}", skips); - let reason = &skips[0].reason; - assert!( - reason.contains("member expression 'motion.pulse'"), - "{reason}" - ); - assert!( - reason.contains("evaluated without extraction-time statics"), - "{reason}" - ); - assert_eq!( - crate::analyze_css::diagnostic_code_from_message(reason), - None, - "{reason}" - ); - } - - #[test] - fn computed_member_expression_keeps_the_bare_reason() { - let (_, skips) = parse_obj_full("{ animationName: motion[key] }"); - assert_eq!(skips.len(), 1, "{:?}", skips); - assert_eq!(skips[0].reason, "member expression (non-static)"); - } - - fn parse_obj_with_statics( - source: &str, - sv: Option<&FxHashMap>, - ) -> (Value, Vec, Vec) { - let ast = parse_ts(format!("const x = {};", source)); - let program = ast.program(); - - if let Some(Statement::VariableDeclaration(decl)) = program.body.first() { - if let Some(declarator) = decl.declarations.first() { - if let Some(Expression::ObjectExpression(obj)) = &declarator.init { - let typed = sv.map(statics_of); - let (value, skips, captures) = - eval_object_expr_with_statics(obj, typed.as_ref().map(|typed| Statics::of(typed, "test.ts"))).unwrap(); - return (plain(&value), skips, captures); - } - } - } - panic!("failed to parse test object"); - } - - #[test] - fn variant_map_resolves_from_statics() { - let mut sv = FxHashMap::default(); - sv.insert( - "sizes".to_string(), - serde_json::json!({ "sm": { "height": 32 }, "md": { "height": 40 } }), - ); - sv.insert("emphasis".to_string(), serde_json::json!({ "fontWeight": 700 })); - let (cfg, skips) = parse_variant_with_statics( - "{ prop: 'size', defaultVariant: 'md', base: emphasis, variants: sizes }", - Some(&sv), - ); - assert!(skips.is_empty(), "{:?}", skips); - assert_eq!(cfg.prop, "size"); - assert_eq!(cfg.default_variant.as_deref(), Some("md")); - assert_eq!(cfg.base.as_ref().map(plain), Some(serde_json::json!({ "fontWeight": 700 }))); - assert_eq!(plain(&cfg.variants).as_object().map_or(0, Map::len), 2); - assert_eq!(plain(&cfg.variants)["sm"], serde_json::json!({ "height": 32 })); - - let (cfg2, skips2) = parse_variant( - "{ prop: 'size', defaultVariant: 'md', variants: sizes }", - ); - assert!(plain(&cfg2.variants).as_object().is_some_and(Map::is_empty)); - assert_eq!(skips2.len(), 1); - assert!(skips2[0].reason.contains("variant map (non-static)")); - } - - #[test] - fn as_const_declarations_collect_into_statics() { - let ast = parse_ts( - "const sizes = { sm: { height: 32 } } as const;\nconst gap = 16 as const;\nconst theme = { gap: 8 } satisfies Record;\n".to_string(), - ); - let statics = plain_map(collect_static_values(ast.program(), "test.ts")); - assert_eq!( - statics.get("sizes"), - Some(&serde_json::json!({ "sm": { "height": 32 } })) - ); - assert_eq!(statics.get("gap"), Some(&serde_json::json!(16))); - assert_eq!(statics.get("theme"), Some(&serde_json::json!({ "gap": 8 }))); - } - - #[test] - fn wrapped_values_evaluate_like_their_operands() { - let (val, skips) = parse_obj_full( - "{ gap: (8), color: 'red' as const, width: 4 as number }", - ); - assert!(skips.is_empty(), "{:?}", skips); - assert_eq!(val["gap"], 8); - assert_eq!(val["color"], "red"); - assert_eq!(val["width"], 4); - } - - #[test] - fn unsupported_selector_key_predicate() { - assert!(unsupported_selector_key(r#"[data-x="a&b"]"#)); - assert!(unsupported_selector_key("[data-x='&']")); - assert!(!unsupported_selector_key(r#"[aria-sort="ascending"] &"#)); - assert!(!unsupported_selector_key(".group:hover &")); - assert!(!unsupported_selector_key("&:hover")); - assert!(!unsupported_selector_key("& + &")); - assert!(!unsupported_selector_key("color")); - assert!(!unsupported_selector_key("_hover")); - assert!(!unsupported_selector_key(r#"@scope ([data-x="&"])"#)); - } - - #[test] - fn quoted_only_subject_key_records_coded_skip_and_omits_property() { - let (val, skips) = parse_obj_full( - r#"{ '[data-x="a&b"]': { color: 'red' }, color: 'blue' }"#, - ); - assert_eq!(skips.len(), 1, "{:?}", skips); - assert!( - skips[0].reason.contains(SELECTOR_UNSUPPORTED_SUBJECT), - "{}", - skips[0].reason - ); - let obj = val.as_object().unwrap(); - assert!(!obj.contains_key(r#"[data-x="a&b"]"#)); - assert_eq!(obj.get("color"), Some(&Value::String("blue".into()))); - } - - #[test] - fn ancestor_and_repeated_subject_keys_flow_through() { - let (val, skips) = parse_obj_full( - r#"{ '[aria-sort="ascending"] &': { color: 'red' }, '&:hover': { color: 'blue' }, '& + &': { gap: 4 }, '&:hover': { '.parent &': { color: 'green' } } }"#, - ); - assert!(skips.is_empty(), "{:?}", skips); - let obj = val.as_object().unwrap(); - assert!(obj.contains_key(r#"[aria-sort="ascending"] &"#)); - assert!(obj.contains_key("& + &")); - let hover = obj.get("&:hover").unwrap().as_object().unwrap(); - assert!(hover.contains_key(".parent &")); - } -} diff --git a/packages/extract/crates/extractor/src/evaluator.rs b/packages/extract/crates/extractor/src/evaluator.rs index 89afa6a2c..dfca75b52 100644 --- a/packages/extract/crates/extractor/src/evaluator.rs +++ b/packages/extract/crates/extractor/src/evaluator.rs @@ -527,226 +527,6 @@ fn value_to_js_literal(value: &Value) -> Result { mod tests { use super::*; - #[test] - fn register_and_eval_simple() { - let eval = TransformEvaluator::new(); - eval.register("double", "(v) => String(v * 2)").unwrap(); - let result = eval.evaluate("double", "double", &Value::Number(5.into())).unwrap(); - assert_eq!(result, "10"); - } - - /// String arguments reach the callback with every character intact, a - /// carriage return included. - #[test] - fn string_arguments_keep_line_terminators_quotes_and_backslashes() { - let eval = TransformEvaluator::new(); - eval.register("b64", "(v) => btoa(v)").unwrap(); - for (value, expected) in [("a\rb", "YQ1i"), ("a\r\nb", "YQ0KYg=="), ("q\"\\\n\u{e9}", "cSJcCuk=")] { - assert_eq!(eval.evaluate("b64", "b64", &Value::String(value.into())).unwrap(), expected, "{value:?}"); - } - } - - /// A host function's exception keeps its name and message: each - /// evaluation has a runtime of its own. - #[test] - fn host_function_exceptions_keep_their_message() { - let eval = TransformEvaluator::new(); - eval.register("b64", "(v) => btoa(v)").unwrap(); - eval.register("caught", "(v) => { try { return btoa(v); } catch (e) { return e.name; } }").unwrap(); - let euro = Value::String("\u{20ac}".into()); - assert_eq!( - eval.evaluate("b64", "b64", &euro), - Err(EvalError::Throw { message: "transform 'b64' eval failed: InvalidCharacterError: String contains an invalid character".into() }) - ); - assert_eq!(eval.evaluate("caught", "caught", &euro).unwrap(), "InvalidCharacterError"); - } - - #[test] - fn register_fails_on_invalid_js() { - let eval = TransformEvaluator::new(); - let result = eval.register("bad", "not valid javascript {{{}}}"); - assert!(result.is_err()); - } - - #[test] - fn eval_with_string_value() { - let eval = TransformEvaluator::new(); - eval.register("wrap", r#"(v) => v + "px""#).unwrap(); - let result = eval.evaluate("wrap", "wrap", &Value::String("10".into())).unwrap(); - assert_eq!(result, "10px"); - } - - #[test] - fn eval_size_transform() { - let eval = TransformEvaluator::new(); - let source = r#"(value) => { - const toSize = (n) => { - if (n === 0) return n; - if (n <= 1 && n >= -1) return `${n * 100}%`; - return `${n}px`; - }; - if (typeof value === 'number') { return toSize(value); } - const strValue = value; - if (strValue.includes('calc')) { return strValue; } - const [match, number, unit] = /(-?\d*\.?\d+)(%|\w*)/.exec(strValue) || []; - if (match === undefined) { return strValue; } - const numericValue = parseFloat(number); - return !unit ? toSize(numericValue) : `${numericValue}${unit}`; - }"#; - eval.register("size", source).unwrap(); - assert_eq!(eval.evaluate("size", "size", &Value::Number(28.into())).unwrap(), "28px"); - assert_eq!(eval.evaluate("size", "size", &Value::Number(0.into())).unwrap(), "0"); - assert_eq!(eval.evaluate("size", "size", &Value::String("max-content".into())).unwrap(), "max-content"); - } - - fn assert_invalid_shape(source: &str, expected: &str) { - let eval = TransformEvaluator::new(); - eval.register("t", source).unwrap(); - let err = eval.evaluate("t", "t", &Value::Number(1.into())).unwrap_err(); - assert_eq!(err, EvalError::InvalidResultShape { shape: expected.to_string() }); - } - - #[test] - fn invalid_shape_object() { - assert_invalid_shape("(v) => ({ a: 1 })", "object"); - } - - #[test] - fn invalid_shape_array() { - assert_invalid_shape("(v) => [1, 2]", "array"); - } - - #[test] - fn invalid_shape_null() { - assert_invalid_shape("(v) => null", "null"); - } - - #[test] - fn invalid_shape_boolean() { - assert_invalid_shape("(v) => true", "boolean"); - } - - #[test] - fn invalid_shape_undefined() { - assert_invalid_shape("(v) => undefined", "undefined"); - } - - #[test] - fn invalid_shape_function() { - assert_invalid_shape("(v) => (() => 1)", "function"); - } - - #[test] - fn invalid_shape_nan() { - assert_invalid_shape("(v) => NaN", "non-finite-number"); - } - - #[test] - fn invalid_shape_positive_infinity() { - assert_invalid_shape("(v) => Infinity", "non-finite-number"); - } - - #[test] - fn invalid_shape_negative_infinity() { - assert_invalid_shape("(v) => -Infinity", "non-finite-number"); - } - - #[test] - fn throwing_transform_reports_throw() { - let eval = TransformEvaluator::new(); - eval.register("boom", "(v) => { throw new Error('boom-message') }").unwrap(); - let err = eval.evaluate("boom", "boom", &Value::Number(1.into())).unwrap_err(); - match err { - EvalError::Throw { message } => assert!(message.contains("boom-message")), - other => panic!("expected Throw, got {:?}", other), - } - } - - #[test] - fn invalid_shape_symbol() { - assert_invalid_shape("(v) => Symbol('x')", "symbol"); - } - - #[test] - fn invalid_shape_bigint() { - assert_invalid_shape("(v) => 10n", "bigint"); - } - - #[test] - fn forged_prefix_with_junk_tail_classifies_as_throw() { - let eval = TransformEvaluator::new(); - eval.register( - "forge", - "(v) => { throw new Error('animus-invalid-transform-result:object trailing junk') }", - ) - .unwrap(); - let err = eval.evaluate("forge", "forge", &Value::Number(1.into())).unwrap_err(); - assert!(matches!(err, EvalError::Throw { .. }), "got {:?}", err); - } - - #[test] - fn non_error_throw_recovers_coerced_message() { - let eval = TransformEvaluator::new(); - eval.register("strthrow", "(v) => { throw 'plain-string-throw' }").unwrap(); - let err = eval.evaluate("strthrow", "strthrow", &Value::Number(1.into())).unwrap_err(); - match err { - EvalError::Throw { message } => assert!( - message.contains("plain-string-throw"), - "message lost the thrown value: {}", - message - ), - other => panic!("expected Throw, got {:?}", other), - } - - eval.register("numthrow", "(v) => { throw 42 }").unwrap(); - let err = eval.evaluate("numthrow", "numthrow", &Value::Number(1.into())).unwrap_err(); - match err { - EvalError::Throw { message } => assert!(message.contains("42")), - other => panic!("expected Throw, got {:?}", other), - } - } - - #[test] - fn unsupported_argument_names_the_transform() { - let eval = TransformEvaluator::new(); - eval.register("t", "(v) => v").unwrap(); - let err = eval.evaluate("t", "t", &Value::Null).unwrap_err(); - match err { - EvalError::Throw { message } => assert!(message.contains("transform 't'")), - other => panic!("expected Throw, got {:?}", other), - } - } - - #[test] - fn harness_locals_do_not_shadow_same_named_transforms() { - for name in ["r", "d"] { - let eval = TransformEvaluator::new(); - eval.register(name, r#"(v) => v + "px""#).unwrap(); - let result = eval - .evaluate(name, name, &Value::Number(4.into())) - .unwrap_or_else(|e| panic!("transform '{}' failed: {:?}", name, e)); - assert_eq!(result, "4px", "transform named '{}' was shadowed", name); - } - } - - #[test] - fn intrinsic_named_keys_do_not_break_the_accept_path() { - let eval = TransformEvaluator::new(); - eval.register("Number", "(v) => v * 2").unwrap(); - eval.register("String", "(v) => v").unwrap(); - eval.register("Array", "(v) => v").unwrap(); - eval.register("keep", "(v) => v * 3").unwrap(); - - assert_eq!( - eval.evaluate("keep", "keep", &Value::Number(5.into())).unwrap(), - "15" - ); - assert_eq!( - eval.evaluate("Number", "Number", &Value::Number(6.into())).unwrap(), - "12" - ); - } - /// Registration keys are registry entries, never global properties: a /// definition keyed like a standard global leaves that global intact for /// every other callback. @@ -766,94 +546,6 @@ mod tests { ); } - #[test] - fn definitions_sharing_a_readable_name_stay_separate() { - let eval = TransformEvaluator::new(); - eval.register("unit@system.inset", r#"(v) => v + "px""#).unwrap(); - eval.register("unit@system.lift", r#"(v) => v + "rem""#).unwrap(); - let value = Value::Number(3.into()); - assert_eq!(eval.evaluate("unit@system.inset", "unit", &value).unwrap(), "3px"); - assert_eq!(eval.evaluate("unit@system.lift", "unit", &value).unwrap(), "3rem"); - } - - #[test] - fn a_result_kept_across_analyses_names_its_own_transform() { - // Contract: a result kept from an earlier analysis is the one a fresh - // evaluation gives, so its error still names the transform it reports. - let source = "(v) => { throw new Error('kept-across-analyses') }"; - let value = Value::Number(7.into()); - let message = |key: &str, name: &str| { - let eval = TransformEvaluator::new(); - eval.register(key, source).unwrap(); - match eval.evaluate(key, name, &value) { - Err(EvalError::Throw { message }) => message, - other => panic!("expected Throw, got {:?}", other), - } - }; - let first = message("a", "first"); - assert!(first.starts_with("transform 'first' eval failed"), "{first}"); - let second = message("b", "second"); - assert!(second.starts_with("transform 'second' eval failed"), "{second}"); - assert_eq!(message("c", "first"), first); - } - - #[test] - fn a_process_cache_holds_to_its_byte_budget() { - // Contract: a process-wide transform cache never holds more than its - // byte budget, keeps no entry larger than a quarter of it, and - // stores each source once however many entries share it. - let mut cache: super::Budgeted> = super::Budgeted::new(4096); - for edit in 0..64u32 { - let source = format!("{edit:0>500}"); - cache.keep(&source, 100, |entries| entries.push(edit)); - assert!(cache.bytes <= cache.budget, "{} > {}", cache.bytes, cache.budget); - } - assert!(cache.entries.len() < 64); - cache.keep("oversized", 1025, |entries| entries.push(0)); - assert!(!cache.entries.contains_key("oversized")); - let before = cache.bytes; - let source = cache.entries.keys().next().unwrap().clone(); - cache.keep(&source, 10, |entries| entries.push(1)); - assert_eq!(cache.bytes, before + 10); - } - - #[test] - fn an_unregistered_key_reports_the_readable_name() { - let eval = TransformEvaluator::new(); - eval.register("unit@system.inset", r#"(v) => v + "px""#).unwrap(); - let err = eval.evaluate("unit", "unit", &Value::Number(3.into())).unwrap_err(); - match err { - EvalError::Throw { message } => assert!( - message.contains("transform 'unit' is not bound to one admitted definition"), - "{message}" - ), - other => panic!("expected Throw, got {:?}", other), - } - } - - #[test] - fn register_rejects_a_source_that_is_not_a_function() { - let eval = TransformEvaluator::new(); - assert!(eval.register("n", "42").is_err()); - } - - /// Transform names come from user source and are never validated as - /// identifiers, so neither registration nor evaluation may interpolate one. - #[test] - fn non_identifier_transform_names_are_safe() { - let eval = TransformEvaluator::new(); - for name in ["kebab-name", "with space", "with\"quote"] { - eval.register(name, r#"(v) => v + "!""#) - .unwrap_or_else(|e| panic!("register '{}' failed: {}", name, e)); - assert_eq!( - eval.evaluate(name, name, &Value::String("x".into())).unwrap(), - "x!", - "name {:?} did not round-trip", - name - ); - } - } - /// The harness closes over intrinsics captured before any callback ran, /// so a callback that clobbers them cannot change shape classification. #[test] diff --git a/packages/extract/crates/extractor/src/facts.rs b/packages/extract/crates/extractor/src/facts.rs index e5b6afe77..923d8d557 100644 --- a/packages/extract/crates/extractor/src/facts.rs +++ b/packages/extract/crates/extractor/src/facts.rs @@ -2482,581 +2482,3 @@ pub(crate) fn extract_file_facts_from_static_maps( ..structural } } - -#[cfg(test)] -mod tests { - use super::*; - use crate::owned_ast::{OwnedAst, ParseCounter}; - - fn facts_for(source: &str) -> FileFacts { - let counter = ParseCounter::new(0); - let ast = OwnedAst::parse("test.tsx".into(), source.into(), &counter); - let facts = extract_file_facts(&ast); - assert_eq!(counter.load(std::sync::atomic::Ordering::SeqCst), 1); - facts - } - - /// Contract: the module facts list an extension of a namespace import's - /// member (`Parts.Base.extend()`) among a module's chains, as the full - /// facts do, whether or not the module is read in full for a resolver. - #[test] - fn module_facts_list_a_namespace_member_extension_as_a_chain() { - for source in [ - "import * as Parts from './parts';\nexport const badge = Parts.Base.extend().styles({}).asClass();", - "import * as Parts from './parts';\nexport const Card = Parts.Base.extend().styles({}).asElement('div');", - ] { - let counter = ParseCounter::new(0); - let ast = OwnedAst::parse("test.tsx".into(), source.into(), &counter); - let full: Vec<_> = extract_file_facts(&ast).chains.into_iter().map(|c| c.descriptor.binding).collect(); - let module: Vec<_> = extract_module_facts(&ast).chains.into_iter().map(|c| c.descriptor.binding).collect(); - assert_eq!(full.len(), 1, "{source}"); - assert_eq!(module, full, "{source}"); - } - } - - #[test] - fn records_every_builder_reference_in_mdx_and_none_in_strings() { - let references = |source: &str| { - let counter = ParseCounter::new(0); - let ast = OwnedAst::parse("doc.mdx.tsx".into(), source.into(), &counter); - extract_file_facts(&ast).builder_references.into_iter().map(|r| r.name).collect::>() - }; - // Wherever and however a builder method or style-declaring import - // is named, it is recorded. - for (source, expected) in [ - ("export const Hidden = () => { const Box = ns.ds.styles({}).asElement('div'); return ; };", vec!["styles", "asElement"]), - ("const el = ds.styles({})} />;", vec!["styles"]), - ("const s = ds.styles; s({});", vec!["styles"]), - ("ds['styles']({});", vec!["styles"]), - ("ds.styles?.({});", vec!["styles"]), - ("ds.styles`x`;", vec!["styles"]), - ("const el =
{ds.variant({})}
;", vec!["variant"]), - ("import { createSystem as makeSystem } from '@animus-ui/react';", vec!["import from @animus-ui/react"]), - ("import * as animus from '@animus-ui/react';\nanimus.createGlobalStyles({});", vec!["import from @animus-ui/react"]), - ("import animus from '@animus-ui/core/groups';", vec!["import from @animus-ui/core/groups"]), - ("const { styles: s } = ds;\ns({});", vec!["styles"]), - ("const { styles } = ds;", vec!["styles"]), - ("let s;\n({ styles: s } = ds);", vec!["styles"]), - ("ds\n .styles({})\n .asClass();", vec!["styles", "asClass"]), - ] { - assert_eq!(references(source), expected, "{source}"); - } - // Text that only spells one is no reference. - for source in [ - "export const example = \"ds.styles({})\";", - "const el = ;", - "const el = <>{\"ds.styles({})\"};", - "const el = <>{`ds.styles({})`};", - ] { - assert!(references(source).is_empty(), "{source}"); - } - // Outside MDX's view nothing is recorded. - let counter = ParseCounter::new(0); - let ast = OwnedAst::parse("a.tsx".into(), "ds.styles({});".into(), &counter); - assert!(extract_file_facts(&ast).builder_references.is_empty()); - } - - #[test] - fn records_only_create_system_calls_no_binding_resolves() { - let calls = |source: &str| facts_for(source).unbound_create_system_calls; - // A bare call, at its callee. - assert_eq!(calls("export const ds = createSystem().build();"), vec![(1, 19)]); - // An escaped spelling names the same identifier. - assert_eq!(calls(r"export const ds = create\u0053ystem().build();"), vec![(1, 19)]); - // A comment or string spelling it is no call, and an alias is bound. - assert!(calls( - "import { createSystem as makeSystem } from '@animus-ui/react';\n\ - // createSystem()\nconst s = 'createSystem()';\n\ - export const ds = makeSystem().build();" - ) - .is_empty()); - // A parameter, a declaration and an import each bind the name. - assert!(calls("function build(createSystem) { return createSystem().build(); }").is_empty()); - assert!(calls("function createSystem() {}\nexport const ds = createSystem();").is_empty()); - assert!(calls( - "import { createSystem } from '@animus-ui/react';\nexport const ds = createSystem();" - ) - .is_empty()); - } - - #[test] - fn directive_remap_rejects_out_of_bounds_removal_metadata() { - let source = "'use client';\nconst x = 1;\n"; - let mut prologue = facts_for(source).directive_prologue.unwrap(); - assert!(!prologue.remap_after_strip(source.len(), &[(source.len(), source.len() + 1)],)); - } - - #[test] - fn evaluates_stage_objects_eagerly() { - let facts = facts_for( - r#" - import { ds } from './sys'; - export const Box = ds - .styles({ display: 'flex', p: 16 }) - .variant({ prop: 'size', variants: { sm: { fontSize: 14 } } }) - .asElement('div'); - "#, - ); - assert_eq!(facts.chains.len(), 1); - let stages = &facts.chains[0].stages; - assert_eq!(stages.len(), 2); - assert_eq!(stages[0].method, "styles"); - let v = stages[0].value.as_ref().unwrap(); - assert_eq!(v["display"], "flex"); - assert_eq!(v["p"], 16); - assert_eq!(stages[1].method, "variant"); - assert_eq!( - stages[1].value.as_ref().unwrap()["variants"]["sm"]["fontSize"], - 14 - ); - } - - #[test] - fn statics_resolve_and_skips_surface() { - let facts = facts_for( - r#" - const GAP = 16; - export const Box = ds.styles({ gap: GAP, color: dynamic() }).asElement('div'); - "#, - ); - let stage = &facts.chains[0].stages[0]; - assert_eq!(stage.value.as_ref().unwrap()["gap"], 16); - assert_eq!(stage.skipped.len(), 1); - assert_eq!(stage.skipped[0].0, "color"); - assert_eq!(eval::plain(&facts.statics["GAP"]), Value::from(16)); - } - - /// Contract (spec §6.2 F1): no key inside a static value stands in for - /// what evaluation could not read, so an authored key that spells one - /// (`$animus.lost`, `$animus.capture`, `$animus.asset`) is plain data: - /// it reads, spreads and serializes as written. - #[test] - fn an_authored_marker_spelling_is_plain_data() { - let rows: [(&str, &str); 5] = [ - ( - "const preset = { '$animus.lost': 'authored', padding: 4 };\n\ - export const A = ds.styles(preset).asElement('div');", - r#"{"value": {"$animus.lost": "authored", "padding": 4}, "skipped": [], "statics": {"preset": {"$animus.lost": "authored", "padding": 4}}}"#, - ), - ( - "const preset = { '$animus.lost': 'authored', padding: 4 };\n\ - export const A = ds.styles({ p: preset.padding }).asElement('div');", - r#"{"value": {"p": 4}, "skipped": [], "statics": {"preset": {"$animus.lost": "authored", "padding": 4}}}"#, - ), - ( - "const nested = { ':hover': { '$animus.lost': 'authored', '$animus.capture': false, padding: 4 }, color: 'red' };\n\ - export const A = ds.styles({ ...nested }).asElement('div');", - r#"{"value": {":hover": {"$animus.lost": "authored", "$animus.capture": false, "padding": 4}, "color": "red"}, "skipped": [], "statics": {"nested": {":hover": {"$animus.lost": "authored", "$animus.capture": false, "padding": 4}, "color": "red"}}}"#, - ), - ( - "const odd = { '$animus.asset': 'other' };\n\ - export const A = ds.styles({ ...odd, color: 'red' }).asElement('div');", - r#"{"value": {"$animus.asset": "other", "color": "red"}, "skipped": [], "statics": {"odd": {"$animus.asset": "other"}}}"#, - ), - ( - "const cfg = { tone: { transform: { '$animus.lost': 'authored' }, property: 'color', scale: 'colors' } };\n\ - export const A = ds.props(cfg).asElement('div');", - r#"{"value": {"tone": {"transform": {"$animus.lost": "authored"}, "property": "color", "scale": "colors"}}, "skipped": [], "statics": {"cfg": {"tone": {"transform": {"$animus.lost": "authored"}, "property": "color", "scale": "colors"}}}}"#, - ), - ]; - for (source, expected) in rows { - let facts = facts_for(source); - let stage = &facts.chains[0].stages[0]; - let seen = serde_json::json!({ - "value": stage.value, - "skipped": stage.skipped, - "statics": serde_json::to_value(&facts).unwrap()["statics"], - }); - // Compared as text, so key order counts. - assert_eq!(seen.to_string(), serde_json::from_str::(expected).unwrap().to_string(), "{source}"); - } - } - - /// Contract: serialized statics carry data only, so the `asset` function - /// a module imports is no serialized static. - #[test] - fn serialized_statics_carry_no_asset_function() { - let facts = facts_for( - r#" - import { asset } from '@animus-ui/react'; - const GAP = 16; - export const Box = ds.styles({ gap: GAP }).asElement('div'); - "#, - ); - let serialized = serde_json::to_value(&facts).unwrap(); - assert_eq!(serialized["statics"], serde_json::json!({ "GAP": 16 })); - } - - #[test] - fn local_const_ident_aliases_are_captured() { - let facts = facts_for( - r#" - export const CardRoot = ds.styles({ display: 'flex' }).asElement('div'); - const Alias = CardRoot; - export const Exported = Alias; - const Peeled = (CardRoot as any); - let Mutable = CardRoot; - const NotAlias = pick(CardRoot); - const Num = 3; - "#, - ); - assert_eq!( - facts.aliases.get("Alias").map(String::as_str), - Some("CardRoot") - ); - assert_eq!( - facts.aliases.get("Exported").map(String::as_str), - Some("Alias") - ); - assert_eq!( - facts.aliases.get("Peeled").map(String::as_str), - Some("CardRoot") - ); - assert!(!facts.aliases.contains_key("Mutable")); - assert!(!facts.aliases.contains_key("NotAlias")); - assert!(!facts.aliases.contains_key("Num")); - } - - #[test] - fn raw_usage_keeps_identifiers_dynamic_and_conditionals_unenumerated() { - let facts = facts_for( - r#" - const GAP = 24; - export const App = ({ open }) => ( - - ); - "#, - ); - let UsageFact::Element { attrs, .. } = &facts.usage[0] else { - panic!("expected JSX element usage fact"); - }; - let identifier = attrs.iter().find(|attr| attr.name == "p").unwrap(); - assert!(identifier.static_value.is_none()); - assert!(identifier.enumerable_values.is_empty()); - assert!(identifier.dynamic); - assert_eq!( - identifier.dynamic_kind, - Some(crate::jsx_scan::DynamicExpressionKind::Identifier) - ); - - let conditional = attrs.iter().find(|attr| attr.name == "display").unwrap(); - assert!(conditional.static_value.is_none()); - assert!(conditional.enumerable_values.is_empty()); - assert!(conditional.dynamic); - assert_eq!( - conditional.dynamic_kind, - Some(crate::jsx_scan::DynamicExpressionKind::Conditional) - ); - } - - #[test] - fn compound_second_arg_evaluates() { - let facts = facts_for( - r#" - export const Btn = ds - .styles({ display: 'flex' }) - .compound({ size: 'sm', tone: 'loud' }, { fontSize: 12 }) - .asElement('button'); - "#, - ); - let compound = &facts.chains[0].stages[1]; - assert_eq!(compound.method, "compound"); - assert_eq!(compound.value.as_ref().unwrap()["size"], "sm"); - assert_eq!(compound.second_value.as_ref().unwrap()["fontSize"], 12); - } - - #[test] - fn identifier_stage_arg_resolves_from_statics() { - let facts = facts_for( - r#" - const BASE = { p: 4 }; - export const Box = ds.styles(BASE).asElement('div'); - "#, - ); - let stage = &facts.chains[0].stages[0]; - assert_eq!(stage.value.as_ref().unwrap()["p"], 4); - assert!(stage.eval_error.is_none()); - assert!(facts.chains[0].fatal_error.is_none()); - } - - fn skipped_of(source: &str, method: &str) -> Vec { - let facts = facts_for(source); - let stage = facts.chains[0] - .stages - .iter() - .find(|stage| stage.method == method) - .unwrap(); - stage.skipped.iter().map(|(key, _)| key.clone()).collect() - } - - #[test] - fn every_stage_reports_what_a_const_could_not_carry() { - let styles = facts_for( - r#" - const CONFIG = { gap: 16, color: someVar, _hover: { opacity: level } }; - export const Box = ds.styles(CONFIG).asElement('div'); - "#, - ); - let stage = &styles.chains[0].stages[0]; - let value = stage.value.as_ref().unwrap(); - assert_eq!(value["gap"], 16); - assert!(value.get("color").is_none(), "{value}"); - assert!(value["_hover"].get("opacity").is_none(), "{value}"); - let mut skipped: Vec<&str> = stage.skipped.iter().map(|(key, _)| key.as_str()).collect(); - skipped.sort_unstable(); - assert_eq!(skipped, ["_hover.opacity", "color"]); - assert!( - stage - .skipped - .iter() - .all(|(_, reason)| reason.contains("in const 'CONFIG'")), - "{:?}", - stage.skipped - ); - - let variant = r#" - const SMALL = { padding: 4, color: someVar }; - export const Box = ds - .styles({}) - .variant({ prop: 'size', variants: { sm: SMALL } }) - .asElement('div'); - "#; - assert_eq!(skipped_of(variant, "variant"), ["variants.sm.color"]); - - let compound = r#" - const HOVER = { opacity: level }; - export const Box = ds - .styles({}) - .variant({ prop: 'size', variants: { sm: {} } }) - .compound({ size: 'sm' }, { _hover: HOVER }) - .asElement('div'); - "#; - assert_eq!(skipped_of(compound, "compound"), ["_hover.opacity"]); - - let props = r#" - const SCALE = { sm: 4, lg: someVar }; - export const Box = ds - .styles({}) - .props({ w: { property: 'width', scale: SCALE } }) - .asElement('div'); - "#; - assert_eq!(skipped_of(props, "props"), ["w.scale.lg"]); - - let captured = r#" - const C = { transform: (v) => v }; - export const Box = ds.styles(C).asElement('div'); - "#; - assert!(skipped_of(captured, "styles").is_empty()); - } - - #[test] - fn unresolvable_identifier_is_chain_fatal_with_v1_message() { - let facts = facts_for( - r#" - export const Box = ds.styles(MYSTERY).asElement('div'); - "#, - ); - let err = facts.chains[0].fatal_error.as_ref().unwrap(); - assert_eq!( - err, - "styles eval failed: identifier 'MYSTERY' not resolvable to static object" - ); - } - - #[test] - fn compound_second_arg_failure_is_chain_fatal() { - let facts = facts_for( - r#" - export const Btn = ds - .styles({ display: 'flex' }) - .compound({ size: 'sm' }, { ...spread }) - .asElement('button'); - "#, - ); - let err = facts.chains[0].fatal_error.as_ref().unwrap(); - assert!( - err.starts_with("compound styles eval failed:"), - "got: {err}" - ); - // Evaluation stopped at the failing stage. - assert_eq!(facts.chains[0].stages.len(), 2); - } - - #[test] - fn variant_stage_uses_variant_parser_without_capture() { - let facts = facts_for( - r#" - export const Box = ds - .variant({ prop: 'size', variants: { sm: { transform: (v) => v } } }) - .asElement('div'); - "#, - ); - let stage = &facts.chains[0].stages[0]; - assert_eq!(stage.method, "variant"); - assert!(stage.captured.is_empty()); - assert_eq!(stage.value.as_ref().unwrap()["prop"], "size"); - } - - /// Contract: an empty variant prop name is `variant`, as the runtime - /// reads `prop || 'variant'`, written inline or through a const. - #[test] - fn an_empty_variant_prop_name_is_variant() { - let facts = facts_for( - r#" - const sized = { prop: '', variants: { lg: { padding: 8 } } }; - export const Box = ds.variant({ prop: '', variants: { sm: { padding: 4 } } }).variant(sized).asElement('div'); - "#, - ); - let props: Vec<&serde_json::Value> = - facts.chains[0].stages.iter().filter_map(|stage| stage.value.as_ref()).map(|value| &value["prop"]).collect(); - assert_eq!(props, ["variant", "variant"]); - } - - #[test] - fn captured_transform_carries_owned_source() { - let facts = facts_for( - r#" - export const Box = ds - .props({ w: { property: 'width', transform: (v) => v * 4 } }) - .asElement('div'); - "#, - ); - let stage = &facts.chains[0].stages[0]; - assert_eq!(stage.captured.len(), 1); - assert_eq!(stage.captured[0].key, "w.transform"); - assert!(stage.captured[0].source.contains("v * 4")); - } - - /// An inline callback reading a `btoa` its module declares is never - /// isolated; the same callback reading the host function is. - #[test] - fn inline_callback_reading_a_module_bound_host_function_is_not_isolated() { - for (preamble, isolated) in [("function btoa(s) { return s; }", false), ("", true)] { - let facts = facts_for(&format!( - "{preamble}\nexport const Box = ds.props({{ w: {{ property: 'width', transform: (v) => btoa(String(v)) }} }}).asElement('div');" - )); - let callback = facts.chains[0].stages[0].captured[0].callback.as_ref().unwrap(); - assert_eq!(callback.definition.isolated_source().is_some(), isolated, "{preamble:?}"); - } - } - - fn captured_pairs(stage: &StageFacts) -> Vec<(&str, &str)> { - stage - .captured - .iter() - .map(|c| (c.key.as_str(), c.source.as_str())) - .collect() - } - - #[test] - fn local_transform_references_keep_their_authored_reference() { - let facts = facts_for( - r#" - import { createTransform as ct } from '@animus-ui/react'; - const double = (v) => v * 2; - function half(v) { return v / 2; } - const twice = double; - const again = twice; - const named = ct('double', (v) => `${v}px`); - const viaExpression = (function (v) { return v; }) satisfies object; - export const Box = ds - .props({ - a: { property: 'width', transform: double }, - b: { property: 'height', transform: again as never }, - c: { property: 'minWidth', transform: half }, - d: { property: 'maxWidth', transform: named }, - e: { property: 'top', transform: viaExpression }, - f: { property: 'left', transform: (v) => v }, - }) - .asElement('div'); - export const Other = ds.props({ g: { property: 'width', transform: double } }).asElement('p'); - "#, - ); - let stage = &facts.chains[0].stages[0]; - let mut captured = captured_pairs(stage); - captured.sort(); - assert_eq!( - captured, - [ - ("a.transform", "double"), - ("b.transform", "again"), - ("c.transform", "half"), - ("d.transform", "named"), - ("e.transform", "viaExpression"), - ("f.transform", "(v) => v"), - ] - ); - assert!(stage.skipped.is_empty(), "{:?}", stage.skipped); - assert!(stage.dropped_transforms.is_empty(), "{:?}", stage.dropped_transforms); - assert_eq!( - captured_pairs(&facts.chains[1].stages[0]), - [("g.transform", "double")] - ); - } - - #[test] - fn unsupported_transform_references_replace_their_generic_skip() { - let facts = facts_for( - r#" - let shift = (v) => v; - export const Box = ds - .props({ - mut: { property: 'height', transform: shift }, - und: { property: 'inset', transform: nowhere }, - }) - .asElement('div'); - "#, - ); - let stage = &facts.chains[0].stages[0]; - assert!(stage.captured.is_empty(), "{:?}", stage.captured); - assert_eq!( - stage.dropped_transforms, - [ - ("mut".to_string(), "transform reference 'shift' is a mutable `let` binding".to_string()), - ("und".to_string(), "transform reference 'nowhere' is not declared in this module".to_string()), - ] - ); - // The classified diagnostic replaces exactly the generic skip line. - for (_, reason) in &stage.dropped_transforms { - assert!(stage.skipped.contains(&("transform".to_string(), reason.clone()))); - } - } - - #[test] - fn css_transform_identifiers_outside_props_stay_skipped() { - let facts = facts_for( - r#" - const rotate = (v) => v; - export const Box = ds - .styles({ transform: rotate }) - .props({ w: { property: 'width', transform: rotate, scale: rotate } }) - .asElement('div'); - "#, - ); - let styles = &facts.chains[0].stages[0]; - assert!(styles.captured.is_empty()); - assert_eq!(styles.skipped.len(), 1); - assert_eq!(styles.skipped[0].0, "transform"); - let props = &facts.chains[0].stages[1]; - assert_eq!(captured_pairs(props), [("w.transform", "rotate")]); - assert_eq!(props.skipped.len(), 1, "{:?}", props.skipped); - assert_eq!(props.skipped[0].0, "scale"); - } - - #[test] - fn serialized_facts_tell_an_aborted_parse_from_a_recovered_one() { - let chain = "export const Box = ds.styles({ display: 'block' }).asElement('div');\n"; - - let aborted = facts_for(&chain.replace("= ds.", "= ds(.")); - assert!(aborted.chains.is_empty()); - assert!(!aborted.parse_diagnostics.is_empty()); - let wire = serde_json::to_value(&aborted).unwrap(); - assert_eq!(wire["parsePanicked"], true); - - let recovered = facts_for(&format!("{chain}return 1;\n")); - assert_eq!(recovered.chains.len(), 1); - assert!(!recovered.parse_diagnostics.is_empty()); - let wire = serde_json::to_value(&recovered).unwrap(); - assert!(wire.get("parsePanicked").is_none(), "{wire}"); - } -} diff --git a/packages/extract/crates/extractor/src/family_members.rs b/packages/extract/crates/extractor/src/family_members.rs index 37673e859..3ce2a9eae 100644 --- a/packages/extract/crates/extractor/src/family_members.rs +++ b/packages/extract/crates/extractor/src/family_members.rs @@ -1097,10 +1097,7 @@ impl<'f> ObjectMembers<'f> { self.namespace_reach(target).record(flow, self.families, Vec::new(), reason) }); } - let changed = flow.close(); - #[cfg(test)] - crate::engine::note_openings("member tables", &changed); - changed + flow.close() } /// What `module`'s namespace may hold: each object it exports and, diff --git a/packages/extract/crates/extractor/src/flow.rs b/packages/extract/crates/extractor/src/flow.rs index 2d570191b..198b0e9b5 100644 --- a/packages/extract/crates/extractor/src/flow.rs +++ b/packages/extract/crates/extractor/src/flow.rs @@ -582,153 +582,3 @@ fn reaches( RegionAtom::AllExports => exports.is_some(), }) } - -#[cfg(test)] -mod tests { - use super::*; - - /// Uncertainties around the region bound: regions of 1, 2, 63, 64 and - /// 65 atoms, over shared and distinct atoms, with two reasons, and - /// everything. - fn bounded_inputs() -> Vec { - let mut inputs = Vec::new(); - for reason in [ReasonId::OpaqueStar, ReasonId::DirectEval] { - for size in [1, 2, 63, 64, 65] { - for family in ["shared", "own"] { - let atoms = (0..size).map(|i| RegionAtom::ExportedAs(format!("{family}{i}"))); - inputs.push(Uncertainty::new(reason, Region::atoms(atoms).expect("non-empty"))); - } - } - inputs.push(Uncertainty::new(reason, Region::top())); - } - inputs - } - - /// Contract (spec §6.2 F1a): what an exposure makes uncertain. A seen - /// change is `Changed(kind)` at its object's path; an opening keeps its - /// own reason and region. - #[test] - fn an_exposure_is_uncertain_as_its_change_or_opening() { - let o = ObjectId::new("m.ts", "preset"); - let mut flow = FlowBuilder::new(); - flow.export(o.clone(), "m.ts", "preset"); - flow.change(o.clone(), vec!["a".to_string()], ChangeKind::Write, "preset.a is written".to_string()); - flow.open(ReasonId::DynamicCode, Region::of(RegionAtom::AllExports), "m.ts runs code".to_string()); - let effects = flow.close(); - let Coverage::Exposed(exposures) = effects.covers(&AbsenceQuery::Stable(o.clone(), Vec::new())) else { - panic!("a written object is exposed"); - }; - let uncertainties: Vec = exposures.iter().map(Exposure::uncertainty).collect(); - - assert_eq!( - uncertainties, - [ - Uncertainty::new( - ReasonId::Changed(ChangeKind::Write), - Region::of(RegionAtom::Path(o, vec!["a".to_string()])), - ), - Uncertainty::new(ReasonId::DynamicCode, Region::of(RegionAtom::AllExports)), - ] - ); - } - - /// A slot is exposed only by what can rebind it: a write of it or of a - /// container above it, a write under an unknown key or an escape of a - /// container above it, a reassignment of the binding, or an opening - /// that reaches the object at or above it. Anything strictly below the - /// slot leaves it, while `Stable` counts that too. Every slot of the - /// object together (`SlotsNotWritten`) is exposed by what exposes any - /// one-member slot, a member the table does not list included. - #[test] - fn a_slot_counts_only_what_can_rebind_it() { - let o = ObjectId::new("m.ts", "o"); - let path = |members: &[&str]| members.iter().map(|member| member.to_string()).collect::>(); - let slot = AbsenceQuery::SlotNotWritten(o.clone(), path(&["Root"])); - let slots = AbsenceQuery::SlotsNotWritten(o.clone()); - let stable = AbsenceQuery::Stable(o.clone(), path(&["Root"])); - let changes: [(ChangeKind, &[&str], bool, bool, bool); 12] = [ - // (kind, at, slot exposed, every slot exposed, stable exposed) - (ChangeKind::Write, &["Root"], true, true, true), - (ChangeKind::Write, &[], true, true, true), - (ChangeKind::Write, &["Root", "x"], false, false, true), - (ChangeKind::Write, &["Other"], false, true, false), - (ChangeKind::UnknownKeyWrite, &[], true, true, true), - (ChangeKind::UnknownKeyWrite, &["Root"], false, false, true), - (ChangeKind::Escape, &[], true, true, true), - (ChangeKind::Escape, &["Root"], false, false, true), - (ChangeKind::Escape, &["Other"], false, false, false), - (ChangeKind::Escape, &["Root", "x"], false, false, true), - (ChangeKind::Rebind, &[], true, true, true), - (ChangeKind::Rebind, &["Root"], true, true, true), - ]; - let exposed = |effects: &ValueEffects, query: &AbsenceQuery| matches!(effects.covers(query), Coverage::Exposed(_)); - for (kind, at, slot_exposed, slots_exposed, stable_exposed) in changes { - let mut builder = FlowBuilder::new(); - builder.change(o.clone(), path(at), kind, "changed".to_string()); - let effects = builder.close(); - assert_eq!(exposed(&effects, &slot), slot_exposed, "{kind:?} at {at:?}"); - assert_eq!(exposed(&effects, &slots), slots_exposed, "{kind:?} at {at:?}, every slot"); - assert_eq!(exposed(&effects, &stable), stable_exposed, "{kind:?} at {at:?}"); - } - let openings: [(RegionAtom, bool, bool); 7] = [ - // (region, slot exposed, every slot exposed) - (RegionAtom::Object(o.clone()), true, true), - (RegionAtom::Path(o.clone(), path(&[])), true, true), - (RegionAtom::Path(o.clone(), path(&["Root"])), true, true), - (RegionAtom::Path(o.clone(), path(&["Other"])), false, true), - (RegionAtom::Path(o.clone(), path(&["Root", "x"])), false, false), - (RegionAtom::ExportsOf("m.ts".to_string()), true, true), - (RegionAtom::ExportedAs("elsewhere".to_string()), false, false), - ]; - for (atom, slot_exposed, slots_exposed) in openings { - let mut builder = FlowBuilder::new(); - builder.export(o.clone(), "m.ts", "o"); - builder.open(ReasonId::OpaqueEffect, Region::of(atom.clone()), "opened".to_string()); - let effects = builder.close(); - assert_eq!(exposed(&effects, &slot), slot_exposed, "{atom:?}"); - assert_eq!(exposed(&effects, &slots), slots_exposed, "{atom:?}, every slot"); - } - } - - /// Adding an opening never takes coverage away: a narrow opening on an - /// object a flow reaches leaves the flow's whole-object change in place. - #[test] - fn a_narrow_opening_keeps_what_a_flow_carries() { - let (x, y) = (ObjectId::new("m.ts", "x"), ObjectId::new("m.ts", "y")); - let build = |narrow: bool| { - let mut builder = FlowBuilder::new(); - builder.change(y.clone(), Vec::new(), ChangeKind::Escape, "y changes".to_string()); - if narrow { - let region = Region::of(RegionAtom::Path(x.clone(), vec!["a".to_string()])); - builder.open(ReasonId::OpaqueEffect, region, "x.a may change".to_string()); - } - builder.flow(vec![(x.clone(), Vec::new())], vec![(y.clone(), Vec::new())], "x reads y, and ".to_string()); - builder.close() - }; - let member_b = AbsenceQuery::Stable(x.clone(), vec!["b".to_string()]); - for narrow in [false, true] { - assert!(matches!(build(narrow).covers(&member_b), Coverage::Exposed(_)), "narrow opening: {narrow}"); - } - } - - #[test] - fn uncertainty_join_is_associative() { - let inputs = bounded_inputs(); - for a in &inputs { - for b in &inputs { - for c in &inputs { - let left = a.clone().join(b.clone()).join(c.clone()); - let right = a.clone().join(b.clone().join(c.clone())); - assert_eq!(left, right, "({a:?} ⊔ {b:?}) ⊔ {c:?}"); - } - } - } - } - - #[test] - fn uncertainty_join_is_idempotent() { - for u in bounded_inputs() { - assert_eq!(u.clone().join(u.clone()), u); - } - } -} diff --git a/packages/extract/crates/extractor/src/forced_usage.rs b/packages/extract/crates/extractor/src/forced_usage.rs index aa0bdaf96..e59ef272d 100644 --- a/packages/extract/crates/extractor/src/forced_usage.rs +++ b/packages/extract/crates/extractor/src/forced_usage.rs @@ -416,228 +416,3 @@ fn push_forced_state( }); } } - -#[cfg(test)] -mod tests { - use super::*; - - fn usage_config( - variants: &[(&str, &[&str], Option<&str>)], - states: &[&str], - ) -> ComponentUsageConfig { - let mut cfg = ComponentUsageConfig { - variants: FxHashMap::default(), - states: FxHashSet::default(), - }; - for (prop, options, default) in variants { - cfg.variants.insert( - prop.to_string(), - ( - options.iter().map(|o| o.to_string()).collect(), - default.map(|d| d.to_string()), - ), - ); - } - for s in states { - cfg.states.insert(s.to_string()); - } - cfg - } - - type Harness = ( - FxHashSet, - FxHashMap, - FxHashMap>, - ); - - fn harness() -> Harness { - let known: FxHashSet = ["Button".to_string(), "Card".to_string()] - .into_iter() - .collect(); - let mut configs = FxHashMap::default(); - configs.insert( - "Button".to_string(), - usage_config( - &[("variant", &["fill", "stroke", "ghost"], Some("fill"))], - &["disabled", "loading"], - ), - ); - // Declared variant without a default option: never participates in - // reconciliation, but must still be forceable by name. - configs.insert( - "Card".to_string(), - usage_config(&[("tone", &["light", "dark"], None)], &[]), - ); - let mut custom = FxHashMap::default(); - let mut button_props = FxHashSet::default(); - button_props.insert("size".to_string()); - custom.insert("Button".to_string(), button_props); - (known, configs, custom) - } - - fn build(config_json: &str) -> ForcedInjection { - let (known, configs, custom) = harness(); - let config = StaticCssConfig::parse(config_json).unwrap(); - build_forced_injection( - &config, - &known, - &configs, - &custom, - &|p| p == "p" || p == "mt", - &UsageLedger::default(), - ) - } - - #[test] - fn empty_config_is_a_no_op() { - let injection = build("{}"); - assert!(injection.scan.variant_usages.is_empty()); - assert!(injection.scan.rendered_components.is_empty()); - assert!(injection.utility_values.is_empty()); - assert!(injection.warnings.is_empty()); - assert_eq!(injection.report.components_forced, 0); - } - - #[test] - fn explicit_variant_list_injects_literals_and_labels() { - let injection = build( - r#"{"components":{"Button":{"variants":{"variant":["ghost"]}}}}"#, - ); - assert_eq!(injection.scan.variant_usages.len(), 1); - assert_eq!(injection.scan.variant_usages[0].value, VariantValue::Literal("ghost".to_string())); - assert!(injection.scan.rendered_components.contains("Button")); - assert_eq!(injection.report.variants_forced, 1); - assert_eq!(injection.report.components_forced, 1); - assert!(injection - .report - .details - .iter() - .any(|d| d.kind == "forced" && d.name.as_deref() == Some("ghost"))); - } - - #[test] - fn wildcard_variants_use_dynamic_expansion_and_count_all_options() { - let injection = build(r#"{"components":{"Button":{"variants":"*"}}}"#); - assert_eq!(injection.scan.variant_usages.len(), 1); - assert_eq!(injection.scan.variant_usages[0].value, VariantValue::Dynamic); - assert_eq!(injection.report.variants_forced, 3); - } - - #[test] - fn no_default_variant_is_forced_without_synthetic_usage() { - let injection = - build(r#"{"components":{"Card":{"variants":{"tone":["light"]}}}}"#); - // Declared-but-defaultless is NOT unknown. - assert!(injection.warnings.is_empty()); - assert_eq!(injection.report.variants_forced, 1); - assert!(injection.scan.rendered_components.contains("Card")); - // No ledger entry may be created: synthetic usage would flip the - // no-default variant from kept-in-full to pruned-to-forced. - assert!(injection.scan.variant_usages.is_empty()); - } - - #[test] - fn wildcard_covers_no_default_variants_without_synthetic_usage() { - let injection = build(r#"{"components":{"Card":{"variants":"*"}}}"#); - assert!(injection.warnings.is_empty()); - assert_eq!(injection.report.variants_forced, 2); - assert!(injection.scan.variant_usages.is_empty()); - } - - #[test] - fn wildcard_states_enumerate_declared_set() { - let injection = build(r#"{"components":{"Button":{"states":"*"}}}"#); - let mut names: Vec<&str> = injection - .scan - .state_usages - .iter() - .map(|s| s.state_name.as_str()) - .collect(); - names.sort(); - assert_eq!(names, vec!["disabled", "loading"]); - assert_eq!(injection.report.states_forced, 2); - } - - #[test] - fn system_prop_values_feed_the_utility_stream_verbatim() { - let injection = - build(r#"{"systemProps":{"p":[4,{"_":8,"sm":16}]}}"#); - assert_eq!(injection.utility_values.len(), 2); - assert_eq!(injection.utility_values[0].0, "p"); - assert!(injection.utility_values[1].1.is_object()); - } - - #[test] - fn custom_dynamic_props_inject_dynamic_usage() { - let injection = - build(r#"{"components":{"Button":{"dynamicProps":["size"]}}}"#); - assert_eq!(injection.custom_dynamic.len(), 1); - assert_eq!(injection.custom_dynamic[0].prop_name, "size"); - assert_eq!(injection.custom_dynamic[0].binding, "Button"); - } - - #[test] - fn unmatched_names_warn_and_never_fail() { - let injection = build( - r#"{"components":{"Buton":{"variants":"*"},"Button":{"variants":{"nope":["x"],"variant":["nope"]},"states":["missing"],"dynamicProps":["ghost"]}},"systemProps":{"zzz":[1]}}"#, - ); - let messages: Vec<&str> = injection - .warnings - .iter() - .map(|w| w.message.as_str()) - .collect(); - assert_eq!(injection.warnings.len(), 6); - assert!(messages.iter().any(|m| m.contains("unknown component 'Buton'"))); - assert!(messages.iter().any(|m| m.contains("unknown variant prop 'nope'"))); - assert!(messages.iter().any(|m| m.contains("unknown option 'nope'"))); - assert!(messages.iter().any(|m| m.contains("unknown state 'missing'"))); - assert!(messages.iter().any(|m| m.contains("unknown custom prop 'ghost'"))); - assert!(messages.iter().any(|m| m.contains("unknown system prop 'zzz'"))); - // Warnings do not abort the valid parts of the declaration. - assert!(injection.scan.rendered_components.contains("Button")); - } - - #[test] - fn observed_usage_suppresses_forced_labels() { - let (known, configs, custom) = harness(); - let mut observed = UsageLedger::default(); - observed.rendered_components.insert("Button".to_string()); - observed - .variant_usage - .entry("Button".to_string()) - .or_default() - .entry("variant".to_string()) - .or_default() - .insert("ghost".to_string()); - - let config = StaticCssConfig::parse( - r#"{"components":{"Button":{"variants":{"variant":["ghost"]}}}}"#, - ) - .unwrap(); - let injection = build_forced_injection( - &config, - &known, - &configs, - &custom, - &|_| false, - &observed, - ); - // Usage still injected (harmless union) but nothing labeled forced. - assert_eq!(injection.scan.variant_usages.len(), 1); - assert_eq!(injection.report.variants_forced, 0); - assert_eq!(injection.report.components_forced, 0); - assert!(injection.report.details.is_empty()); - } - - #[test] - fn synthesis_is_deterministic() { - let json = r#"{"components":{"Button":{"variants":"*","states":"*"},"Card":{}},"systemProps":{"p":[1,2],"mt":[3]}}"#; - let a = build(json); - let b = build(json); - assert_eq!( - serde_json::to_string(&a.scan).unwrap(), - serde_json::to_string(&b.scan).unwrap() - ); - assert_eq!(a.utility_values, b.utility_values); - } -} diff --git a/packages/extract/crates/extractor/src/identity.rs b/packages/extract/crates/extractor/src/identity.rs index ccf01e699..ca6b67b6b 100644 --- a/packages/extract/crates/extractor/src/identity.rs +++ b/packages/extract/crates/extractor/src/identity.rs @@ -400,79 +400,3 @@ pub(crate) fn runtime_value(scoping: &Scoping, symbol: SymbolId) -> bool { let runtime = |flags: oxc::semantic::SymbolFlags| flags.is_value() && !flags.is_ambient(); runtime(scoping.symbol_flags(symbol)) || scoping.symbol_redeclarations(symbol).iter().any(|declaration| runtime(declaration.flags)) } - -#[cfg(test)] -mod tests { - use super::*; - use crate::owned_ast::{OwnedAst, ParseCounter}; - - fn table_of(path: &str, source: &str) -> Arc { - let ast = OwnedAst::parse(path.into(), source.into(), &ParseCounter::new(0)); - crate::facts::extract_file_facts(&ast).bindings - } - - /// The identity of each reference spelled `name`, in source order. - fn references(table: &BindingTable, source: &str, name: &str) -> Vec { - source - .match_indices(name) - .filter_map(|(start, _)| table.reference((start as u32, (start + name.len()) as u32)).cloned()) - .collect() - } - - fn module(table: &BindingTable, name: &str) -> Identity { - let local = table.module_binding(name).expect("a module-scope binding"); - Identity::Module(BindingId { module: table.module.clone(), local }) - } - - #[test] - fn a_reference_is_exactly_one_of_module_nested_or_global_and_no_nested_binding_reads_as_a_module_name() { - let source = "import React from 'react'; -import { a as b } from './m'; -const x = 0; -function one() { const x = 1; return x; } -function two(x) { return x; } -function three(Object, React) { return [Object, React]; } -export const uses = [x, b, Object, React]; -"; - let table = table_of("a.tsx", source); - - let [Identity::Nested { scope: first_scope, local: first }, Identity::Nested { scope: second_scope, local: second }, top]: [Identity; 3] = - references(&table, source, "x").try_into().expect("three references to x") - else { - panic!("the two inner references to x are nested"); - }; - assert_ne!((first_scope, first), (second_scope, second)); - assert_eq!(top, module(&table, "x")); - assert!(![first, second].contains(&table.module_binding("x").unwrap())); - - let [shadowed, global]: [Identity; 2] = references(&table, source, "Object").try_into().expect("two references to Object"); - assert!(matches!(shadowed, Identity::Nested { .. })); - assert_eq!(global, Identity::Global { realm: Realm::Shared, name: "Object".into() }); - - let [shadowed, imported]: [Identity; 2] = references(&table, source, "React").try_into().expect("two references to React"); - assert!(matches!(shadowed, Identity::Nested { .. })); - assert_eq!(imported, module(&table, "React")); - assert_eq!(table.module_import("React"), Some(&ImportBinding::Default { specifier: "react".into() })); - - assert_eq!(references(&table, source, "b"), [module(&table, "b")]); - assert_eq!( - table.module_import("b"), - Some(&ImportBinding::Named { specifier: "./m".into(), imported: "a".into() }) - ); - - // Two modules each number their first binding 0, and stay apart. - let snapshot = table_of("b.ts", "let y = 1; export default y;"); - let alias = table_of("c.ts", "let y = 1; export { y as default };"); - assert_eq!((snapshot.module_binding("y"), alias.module_binding("y")), (Some(LocalId(0)), Some(LocalId(0)))); - assert_ne!(module(&snapshot, "y"), module(&alias, "y")); - - // `export default y` holds y's value then; `export { y as default }` is y. - let Some(DefaultExport::Snapshot { cell, of }) = snapshot.default_export else { - panic!("a default expression is a snapshot: {:?}", snapshot.default_export); - }; - assert_ne!(cell, LocalId(0)); - assert_eq!(of, Some(LocalId(0))); - assert_eq!(snapshot.binding(cell).kind, BindingKind::DefaultCell); - assert_eq!(alias.default_export, Some(DefaultExport::Alias(LocalId(0)))); - } -} diff --git a/packages/extract/crates/extractor/src/ids.rs b/packages/extract/crates/extractor/src/ids.rs index 761fec6fd..7376f030b 100644 --- a/packages/extract/crates/extractor/src/ids.rs +++ b/packages/extract/crates/extractor/src/ids.rs @@ -204,72 +204,3 @@ pub fn is_installed_file(path: &str, linked_dirs: &[String]) -> bool { }; !linked_dirs.iter().any(within) && path.split(['/', '\\']).any(|segment| segment == "node_modules") } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn only_definitions_whose_short_names_collide_take_full_suffixes() { - // Two identities whose 8-hex suffixes collide. - let mut by_suffix: rustc_hash::FxHashMap = Default::default(); - let (first, second) = (0u32..) - .map(|n| format!("system:{n:016x}")) - .find_map(|identity| { - let suffix = content_hash(&identity); - match by_suffix.get(&suffix) { - Some(earlier) => Some((earlier.clone(), identity)), - None => { - by_suffix.insert(suffix, identity); - None - } - } - }) - .expect("a 32-bit suffix collides within 2^32 identities"); - assert_eq!(make_class_name("Button", &first, "animus"), make_class_name("Button", &second, "animus")); - let across = class_names(&[("Button", &first), ("Card", &second)], "animus"); - assert_eq!( - across, - [make_class_name("Button", &first, "animus"), make_class_name("Card", &second, "animus")], - "suffixes that collide under different bindings keep 8 hex" - ); - assert_ne!(name_scope("Button", &across[0]), name_scope("Card", &across[1]), "their props' names differ by binding"); - let names = class_names(&[("Button", &first), ("Card", "system:other"), ("Button", &second), ("Button", &first)], "animus"); - assert_ne!(names[0], names[2], "different definitions never share a class"); - assert_eq!(names[0], names[3], "copies of one definition share theirs"); - assert!(class_suffix(&names[0]).len() == 16 && class_suffix(&names[2]).len() == 16); - assert_eq!(names[1], make_class_name("Card", "system:other", "animus")); - } - - /// Contract: a short class id depends on its own definition and binding, - /// so adding a component renames no other unless their 32-bit ids - /// collide, when both take 64-bit ids; copies share one, and two - /// definitions never do. - #[test] - fn short_class_ids_widen_only_on_collision_and_are_never_shared_by_two_definitions() { - let names = short_class_names(&[("Button", "s:a"), ("Card", "s:b"), ("Button", "s:a")], "x"); - assert_eq!(names[0], names[2]); - assert!(names.iter().all(|name| name.starts_with("x-") && name.len() <= 9), "{names:?}"); - let grown = short_class_names(&[("Button", "s:a"), ("Badge", "s:c"), ("Card", "s:b")], "x"); - assert_eq!((&grown[0], &grown[2]), (&names[0], &names[1])); - assert_ne!(short_class_names(&[("Btn", "s:a")], "x")[0], names[0], "bindings keep apart, as readable names do"); - // Two definitions whose 32-bit ids collide. - let mut by_id: rustc_hash::FxHashMap = Default::default(); - let (first, second) = (0u32..) - .map(|n| format!("s:{n:x}")) - .find_map(|identity| { - let id = short_class_names(&[("B", &identity)], "x").remove(0); - match by_id.get(&id) { - Some(earlier) => Some((earlier.clone(), identity)), - None => { - by_id.insert(id, identity); - None - } - } - }) - .expect("a 32-bit id collides within 2^32 identities"); - let widened = short_class_names(&[("B", &first), ("B", &second)], "x"); - assert_ne!(widened[0], widened[1]); - assert!(widened.iter().all(|name| name.len() > 9), "{widened:?}"); - } -} diff --git a/packages/extract/crates/extractor/src/jsx_scan.rs b/packages/extract/crates/extractor/src/jsx_scan.rs index dfa5672dd..6fd434dad 100644 --- a/packages/extract/crates/extractor/src/jsx_scan.rs +++ b/packages/extract/crates/extractor/src/jsx_scan.rs @@ -107,1014 +107,3 @@ pub struct CustomPropScanResult { pub static_usages: Vec, pub dynamic_usages: Vec, } - -#[cfg(test)] -mod tests { - use super::*; - use rustc_hash::{FxHashMap, FxHashSet}; - use crate::owned_ast::{OwnedAst, ParseCounter}; - - fn parse_tsx(source: &str) -> OwnedAst { - let counter = ParseCounter::new(0); - OwnedAst::parse("test.tsx".into(), source.to_string(), &counter) - } - - macro_rules! map { - ($( $key:expr => $val:expr ),* $(,)?) => {{ - let mut m = FxHashMap::default(); - $( m.insert($key.to_string(), $val); )* - m - }}; - } - - macro_rules! set { - ($( $val:expr ),* $(,)?) => {{ - let mut s = FxHashSet::default(); - $( s.insert($val.to_string()); )* - s - }}; - } - - fn parse_and_scan( - source: &str, - component_props: FxHashMap>, - ) -> Vec { - let ast = parse_tsx(source); - let result_program = ast.program(); - let empty = FxHashMap::default(); - scan_jsx(result_program, &component_props, &empty).static_usages - } - - fn parse_and_scan_full( - source: &str, - component_props: FxHashMap>, - ) -> CustomPropScanResult { - let ast = parse_tsx(source); - let result_program = ast.program(); - let empty = FxHashMap::default(); - scan_jsx(result_program, &component_props, &empty) - } - - fn box_with_props(props: &[&str]) -> FxHashMap> { - map! { "Box" => props.iter().map(|s| s.to_string()).collect() } - } - - #[test] - fn collects_numeric_prop() { - let usages = parse_and_scan( - r#" - function App() { - return ; - } - "#, - box_with_props(&["p"]), - ); - assert_eq!(usages.len(), 1); - assert_eq!(usages[0].prop_name, "p"); - assert_eq!(usages[0].value, 8); - assert_eq!(usages[0].binding, "Box"); - } - - #[test] - fn collects_string_prop() { - let usages = parse_and_scan( - r#" - function App() { - return ; - } - "#, - box_with_props(&["display"]), - ); - assert_eq!(usages.len(), 1); - assert_eq!(usages[0].prop_name, "display"); - assert_eq!(usages[0].value, "flex"); - } - - #[test] - fn collects_responsive_object() { - let usages = parse_and_scan( - r#" - function App() { - return ; - } - "#, - box_with_props(&["mt"]), - ); - assert_eq!(usages.len(), 1); - assert_eq!(usages[0].prop_name, "mt"); - assert_eq!(usages[0].value["_"], 8); - assert_eq!(usages[0].value["sm"], 16); - } - - #[test] - fn skips_non_group_prop() { - let usages = parse_and_scan( - r#" - function App() { - return ; - } - "#, - box_with_props(&["p"]), - ); - assert_eq!(usages.len(), 1); - assert_eq!(usages[0].prop_name, "p"); - assert_eq!(usages[0].value, 8); - } - - #[test] - fn skips_unknown_component() { - let usages = parse_and_scan( - r#" - function App() { - return ; - } - "#, - box_with_props(&["p"]), - ); - assert!(usages.is_empty()); - } - - #[test] - fn skips_dynamic_value() { - let usages = parse_and_scan( - r#" - function App() { - return ; - } - "#, - box_with_props(&["p"]), - ); - assert!(usages.is_empty()); - } - - #[test] - fn deduplicates_same_value() { - let usages = parse_and_scan( - r#" - function App() { - return ( -
- - -
- ); - } - "#, - box_with_props(&["p"]), - ); - assert_eq!(usages.len(), 1); - assert_eq!(usages[0].prop_name, "p"); - assert_eq!(usages[0].value, 8); - } - - #[test] - fn different_values_kept() { - let usages = parse_and_scan( - r#" - function App() { - return ( -
- - -
- ); - } - "#, - box_with_props(&["p"]), - ); - assert_eq!(usages.len(), 2); - let values: FxHashSet = usages.iter().map(|u| u.value.as_i64().unwrap()).collect(); - assert!(values.contains(&8)); - assert!(values.contains(&16)); - } - - #[test] - fn nested_jsx_found() { - let usages = parse_and_scan( - r#" - function Card() { - return ( - - - - ); - } - "#, - box_with_props(&["display", "p"]), - ); - assert_eq!(usages.len(), 2); - let names: FxHashSet<&str> = usages.iter().map(|u| u.prop_name.as_str()).collect(); - assert!(names.contains("display")); - assert!(names.contains("p")); - } - - #[test] - fn collects_negative_number() { - let usages = parse_and_scan( - r#" - function App() { - return ; - } - "#, - box_with_props(&["mt"]), - ); - assert_eq!(usages.len(), 1); - assert_eq!(usages[0].value, -4); - } - - #[test] - fn multiple_components_same_prop_name() { - let component_props = map! { - "Box" => set!["p"], - "Text" => set!["p"], - }; - - let usages = parse_and_scan( - r#" - function App() { - return ( -
- - -
- ); - } - "#, - component_props, - ); - assert_eq!( - usages - .iter() - .map(|usage| usage.binding.as_str()) - .collect::>(), - vec!["Box", "Text"], - "same (prop, value) kept per component, deduped within one" - ); - } - - #[test] - fn skips_call_expression_value() { - let usages = parse_and_scan( - r#" - function App() { - return ; - } - "#, - box_with_props(&["p"]), - ); - assert!(usages.is_empty()); - } - - #[test] - fn skips_conditional_expression_value() { - let usages = parse_and_scan( - r#" - function App() { - return ; - } - "#, - box_with_props(&["display"]), - ); - assert!(usages.is_empty()); - } - - #[test] - fn skips_spread_attributes() { - let usages = parse_and_scan( - r#" - function App() { - return ; - } - "#, - box_with_props(&["p"]), - ); - assert_eq!(usages.len(), 1); - assert_eq!(usages[0].prop_name, "p"); - } - - #[test] - fn jsx_in_variable_initializer() { - let usages = parse_and_scan( - r#" - const el = ; - "#, - box_with_props(&["p"]), - ); - assert_eq!(usages.len(), 1); - assert_eq!(usages[0].value, 24); - } - - fn parse_and_scan_usage( - source: &str, - component_props: FxHashMap>, - component_configs: FxHashMap, - ) -> UsageScanResult { - let ast = parse_tsx(source); - let result_program = ast.program(); - let empty = FxHashMap::default(); - scan_jsx_usage(result_program, &component_props, &component_configs, &empty) - } - - fn button_config_variant() -> FxHashMap { - map! { - "Button" => ComponentUsageConfig { - variants: map! { "variant" => (set!["fill", "stroke"], Some("fill".to_string())) }, - states: FxHashSet::default(), - } - } - } - - fn layout_config_state() -> FxHashMap { - map! { - "Layout" => ComponentUsageConfig { - variants: FxHashMap::default(), - states: set!["sidebar"], - } - } - } - - #[test] - fn scan_usage_collects_variant_value() { - let result = parse_and_scan_usage( - r#" - function App() { - return