From 388ae9bd3e31a4434079533ec102f062a61ec96f Mon Sep 17 00:00:00 2001 From: owjs3901 Date: Sun, 15 Nov 2026 23:41:00 +0900 Subject: [PATCH] fix(extractor): let later StyleX keys override an include() `{ ...stylex.include(s0.a), color: 'blue' }` prepended the included classes to the namespace's own, so both the red and the blue class were applied and red could win by stylesheet order. An include() written after a key was prepended too, so its position was ignored. Each include() now records how many keys come before it. When the namespace and every namespace it includes are static, their keys are merged in written order, a later key replacing the same key from before, and the namespace gets the merged classes. Its keys are also recorded, so stylex.props() resolves it per key instead of joining classes. A dynamic namespace has no keys, so including one keeps prepending. The StyleX migration page says the override now holds. Co-Authored-By: Claude Opus 5.5 --- ...hangepack_log_stylex_include_override.json | 8 ++ .../(detail)/docs/migration/stylex/page.mdx | 2 +- .../extractor/extract_style_from_stylex.rs | 4 +- libs/extractor/src/lib.rs | 56 ++++++++++- ...xtractor__tests__stylex_include_basic.snap | 2 +- libs/extractor/src/stylex.rs | 36 +++++++ libs/extractor/src/visit.rs | 93 +++++++++++++------ 7 files changed, 167 insertions(+), 34 deletions(-) create mode 100644 .changepacks/changepack_log_stylex_include_override.json diff --git a/.changepacks/changepack_log_stylex_include_override.json b/.changepacks/changepack_log_stylex_include_override.json new file mode 100644 index 000000000..a445ccc5a --- /dev/null +++ b/.changepacks/changepack_log_stylex_include_override.json @@ -0,0 +1,8 @@ +{ + "changes": { + "bindings/devup-ui-wasm/package.json": "Patch", + "bindings/devup-ui-binding/package.json": "Patch" + }, + "note": "A key written after `...stylex.include(base.root)` in `stylex.create()` now overrides the included one, as StyleX merges them: `{ ...stylex.include(s0.a), color: 'blue' }` kept both the included red and the blue class, and red could win by stylesheet order. The included namespace's keys are merged where the spread is written, so a later key or a later `include()` replaces what came before, and `stylex.props()` resolves such a namespace per key like any other. A dynamic (arrow function) namespace has no keys and is still only prepended. No new build errors", + "date": "2026-11-15T00:00:00.000Z" +} diff --git a/apps/landing/src/app/(detail)/docs/migration/stylex/page.mdx b/apps/landing/src/app/(detail)/docs/migration/stylex/page.mdx index dda8454c7..ece1a7ac5 100644 --- a/apps/landing/src/app/(detail)/docs/migration/stylex/page.mdx +++ b/apps/landing/src/app/(detail)/docs/migration/stylex/page.mdx @@ -154,7 +154,7 @@ const transition = stylex.viewTransitionClass({ animationDuration: '300ms' }) ## Value helpers -`firstThatWorks()` emits its fallbacks in CSS order, `types.*()` unwraps to the inner value, and `include()` merges another namespace's classes. Values may be plain literals, condition objects (`{ default, ':hover', '@media ...' }`), or arrow functions, which become CSS variables bound at the call site. +`firstThatWorks()` emits its fallbacks in CSS order, `types.*()` unwraps to the inner value, and `include()` merges another namespace's keys where the spread is written. A key written after the `include()` overrides the included one: `{ ...stylex.include(base.root), color: 'blue' }` keeps only the blue class for `color`, and a later `include()` likewise overrides the keys before it. This is resolved at build time, including when the namespace is passed to `props()`. A dynamic (arrow function) namespace has no keys to merge, so its classes are only added before the namespace's own. Values may be plain literals, condition objects (`{ default, ':hover', '@media ...' }`), or arrow functions, which become CSS variables bound at the call site. ## Unsupported APIs diff --git a/libs/extractor/src/extractor/extract_style_from_stylex.rs b/libs/extractor/src/extractor/extract_style_from_stylex.rs index 42bdc0f32..bb594de3c 100644 --- a/libs/extractor/src/extractor/extract_style_from_stylex.rs +++ b/libs/extractor/src/extractor/extract_style_from_stylex.rs @@ -248,7 +248,7 @@ fn extract_stylex_namespace<'a>( let style_prop = match style_prop { ObjectPropertyKind::ObjectProperty(style_prop) => style_prop, ObjectPropertyKind::SpreadProperty(spread) => { - match include(spread, resolver) { + match include(spread, groups.len(), resolver) { Some(Ok(include_ref)) => include_refs.push(include_ref), Some(Err(error)) => errors.push(error), None => errors.push(spread_error("stylex.create", spread)), @@ -354,6 +354,7 @@ fn push_decomposed(styles: &mut Vec>, decomposed: Vec, + position: usize, resolver: StylexResolver<'_>, ) -> Option> { let Expression::CallExpression(call) = &spread.argument else { @@ -370,6 +371,7 @@ fn include( var_name: ident.name.to_string(), member_name: member.property.name.to_string(), offset: spread.span.start, + position, })); } Some(Err(( diff --git a/libs/extractor/src/lib.rs b/libs/extractor/src/lib.rs index 71b38efe2..6505a6985 100644 --- a/libs/extractor/src/lib.rs +++ b/libs/extractor/src/lib.rs @@ -16188,7 +16188,10 @@ export const a = (m) => " #[case("stylex.props(s.red, (cond).x)", "[cond.x]")] #[case("stylex.props(s.red, ...rest)", "rest")] #[case("stylex.props(s.red, s.fn(1))", "--")] - #[case("stylex.props(s.red, s.inc)", "color-0-red--255")] + #[case( + "stylex.props(s.red, s.inc)", + "result = { className: \"margin-0-1px--255 color-0-green--255\" }" + )] #[case("stylex.props(on && s.reset)", "{ className: \"\" }")] #[case("stylex.props([s.red, rest])", "[rest].flat(Infinity)")] #[serial] @@ -16210,6 +16213,57 @@ export const result = {call}" assert!(code.contains(expected), "{expected}\n{code}"); } + #[rstest] + #[case::later_declaration_wins( + "{ ...stylex.include(s0.a), color: 'blue' }", + "\"x\": \"margin-0-1px--255 color-0-blue--255\"" + )] + #[case::later_include_wins( + "{ color: 'blue', ...stylex.include(s0.a) }", + "\"x\": \"color-0-red--255 margin-0-1px--255\"" + )] + #[case::later_include_over_earlier( + "{ ...stylex.include(s0.a), ...stylex.include(s0.b) }", + "\"x\": \"margin-0-1px--255 color-0-green--255\"" + )] + #[case::nested_include( + "{ ...stylex.include(s1.c), margin: '2px' }", + "\"x\": \"color-0-red--255 opacity-0-_d_5--255 margin-0-2px--255\"" + )] + #[case::condition_key_replaced( + "{ ...stylex.include(s0.h), ':hover': { opacity: 1 } }", + "\"x\": \"opacity-0-1-_a__c_hover-255\"" + )] + #[case::props_resolves_keys( + "{ ...stylex.include(s0.a), color: 'blue' }", + "p = { className: \"margin-0-1px--255 color-0-green--255\" }" + )] + #[case::dynamic_include_keeps_classes( + "{ ...stylex.include(s0.f), color: 'blue' }", + "\"x\": \"height-0---255 color-0-blue--255\"" + )] + #[serial] + fn test_stylex_include_later_declarations_override( + #[case] namespace: &str, + #[case] expected: &str, + ) { + let code = readable_code(&format!( + "import stylex from '@stylexjs/stylex' +const s0 = stylex.create({{ + a: {{ color: 'red', margin: '1px' }}, + b: {{ color: 'green' }}, + h: {{ ':hover': {{ color: 'red' }} }}, + f: (h) => ({{ height: h }}), +}}) +const s1 = stylex.create({{ c: {{ ...stylex.include(s0.a), opacity: 0.5 }} }}) +const s = stylex.create({{ + x: {namespace}, +}}) +export const p = stylex.props(s.x, s0.b)" + )); + assert!(code.contains(expected), "{expected}\n{code}"); + } + #[test] #[serial] fn test_css_composing_reports_runtime_values() { diff --git a/libs/extractor/src/snapshots/extractor__tests__stylex_include_basic.snap b/libs/extractor/src/snapshots/extractor__tests__stylex_include_basic.snap index 691133529..2c67e1f67 100644 --- a/libs/extractor/src/snapshots/extractor__tests__stylex_include_basic.snap +++ b/libs/extractor/src/snapshots/extractor__tests__stylex_include_basic.snap @@ -35,5 +35,5 @@ ToBTreeSet { }, ), }, - code: "import \"@devup-ui/react/devup-ui.css\";\nimport stylex from \"@stylexjs/stylex\";\nconst base = { \"root\": \"a b\" };\nconst composed = { \"fancy\": \"a b c\" };\n", + code: "import \"@devup-ui/react/devup-ui.css\";\nimport stylex from \"@stylexjs/stylex\";\nconst base = { \"root\": \"a b\" };\nconst composed = { \"fancy\": \"b a c\" };\n", } diff --git a/libs/extractor/src/stylex.rs b/libs/extractor/src/stylex.rs index 2bd428112..22821dd05 100644 --- a/libs/extractor/src/stylex.rs +++ b/libs/extractor/src/stylex.rs @@ -243,6 +243,42 @@ pub struct StylexIncludeRef { pub var_name: String, pub member_name: String, pub offset: u32, + /// How many keys of the namespace are written before the `include()` + pub position: usize, +} + +/// The keys of a namespace with its `include()`s merged in where they are +/// written: a key written later replaces the same key from before, as `StyleX` +/// merges them. +pub fn merge_included_keys( + own: Vec<(String, String)>, + included: Vec<(usize, Vec<(String, String)>)>, +) -> Vec<(String, String)> { + let mut merged: Vec<(String, String)> = Vec::new(); + let mut included = included.into_iter().peekable(); + for (index, own) in own.into_iter().map(Some).chain([None]).enumerate() { + while let Some((_, keys)) = included.next_if(|(position, _)| *position <= index) { + keys.into_iter().for_each(|key| put_key(&mut merged, key)); + } + if let Some(own) = own { + put_key(&mut merged, own); + } + } + merged +} + +fn put_key(merged: &mut Vec<(String, String)>, key: (String, String)) { + merged.retain(|(existing, _)| *existing != key.0); + merged.push(key); +} + +/// The class names `keys` give, in order +pub fn joined_key_classes(keys: &[(String, String)]) -> String { + keys.iter() + .map(|(_, class)| class.as_str()) + .filter(|class| !class.is_empty()) + .collect::>() + .join(" ") } /// Whether `callee` is a member of the `types` the package gives, as diff --git a/libs/extractor/src/visit.rs b/libs/extractor/src/visit.rs index 4adfbc731..cffdcc706 100644 --- a/libs/extractor/src/visit.rs +++ b/libs/extractor/src/visit.rs @@ -58,9 +58,9 @@ use crate::prop_modify_utils::{ use crate::scope::{Bindings, NAMESPACE_STYLED}; use crate::style_collector::StyleCollector; use crate::stylex::{ - StylexDynamicInfo, StylexFunction, StylexNamespaceValue, create_theme_class, - css_variable_block, css_variable_rules, define_vars_variable, unsupported_stylex_error, - variable_values, + StylexDynamicInfo, StylexFunction, StylexIncludeRef, StylexNamespaceValue, create_theme_class, + css_variable_block, css_variable_rules, define_vars_variable, joined_key_classes, + merge_included_keys, unsupported_stylex_error, variable_values, }; use crate::util_type::UtilType; use crate::{ExtractStyleProp, ExtractStyleValue}; @@ -2772,6 +2772,47 @@ impl<'a> DevupVisitor<'a> { Some(()) } + /// Each top-level key of a static namespace and the classes its styles get + fn stylex_key_classes( + &self, + styles: &mut [ExtractStyleProp<'a>], + groups: Vec<(String, usize)>, + ) -> Vec<(String, String)> { + let mut offset = 0; + let mut keys = Vec::with_capacity(groups.len()); + for (key, count) in groups { + let class = gen_class_names( + &self.ast, + &mut styles[offset..offset + count], + None, + self.split_filename.as_deref(), + ); + offset += count; + let class = match class { + Some(Expression::StringLiteral(class)) => class + .value + .as_str() + .map_or_else(String::new, str::to_string), + _ => String::new(), + }; + keys.push((key, class)); + } + keys + } + + /// The keys of the namespace an `include()` reads; none when they are not + /// known, as for a dynamic namespace + fn stylex_included_keys( + &self, + visible: &FxHashMap, + include: &StylexIncludeRef, + ) -> Option> { + self.stylex_keys + .get(visible.get(&include.var_name)?)? + .get(&include.member_name) + .cloned() + } + /// The classes each key of the namespace `expr` reads gives; none for a /// value `StyleX` skips fn stylex_keyed(&self, expr: &Expression<'a>) -> Option> { @@ -3726,32 +3767,9 @@ impl<'a> VisitMut<'a> for DevupVisitor<'a> { for (ns_name, mut styles, css_vars, include_refs, groups) in namespaces { let class_name = gen_class_names(&self.ast, &mut styles, None, self.split_filename.as_deref()); - if include_refs.is_empty() && css_vars.is_none() { - let mut offset = 0; - let mut keys = Vec::with_capacity(groups.len()); - for (key, count) in groups { - let class = gen_class_names( - &self.ast, - &mut styles[offset..offset + count], - None, - self.split_filename.as_deref(), - ); - offset += count; - let class = match class { - Some(Expression::StringLiteral(class)) - if class.value.as_str().is_some() => - { - class - .value - .as_str() - .map_or_else(String::new, str::to_string) - } - _ => String::new(), - }; - keys.push((key, class)); - } - key_map.insert(ns_name.clone(), keys); - } + let own_keys = css_vars + .is_none() + .then(|| self.stylex_key_classes(&mut styles, groups)); self.styles .extend(styles.into_iter().flat_map(ExtractStyleProp::into_extract)); @@ -3763,7 +3781,9 @@ impl<'a> VisitMut<'a> for DevupVisitor<'a> { _ => String::new(), }; - // Resolve include() references — prepend included classNames + // Resolve include() references: merge their keys where they are written, + // else prepend the included classNames + let mut included_keys = Some(Vec::with_capacity(include_refs.len())); for inc_ref in &include_refs { let Some(ns_value) = visible .get(&inc_ref.var_name) @@ -3780,6 +3800,12 @@ impl<'a> VisitMut<'a> for DevupVisitor<'a> { )); continue; }; + included_keys = included_keys + .zip(self.stylex_included_keys(&visible, inc_ref)) + .map(|(mut included, keys)| { + included.push((inc_ref.position, keys)); + included + }); let included_class = match ns_value { StylexNamespaceValue::Static(s) => s.clone(), StylexNamespaceValue::Dynamic(info) => info.class_name.clone(), @@ -3792,6 +3818,13 @@ impl<'a> VisitMut<'a> for DevupVisitor<'a> { } } } + if let Some((own, included)) = own_keys.zip(included_keys) { + let keys = merge_included_keys(own, included); + if !include_refs.is_empty() { + class_name_str = joined_key_classes(&keys); + } + key_map.insert(ns_name.clone(), keys); + } let ns_value = if let Some(vars) = css_vars { StylexNamespaceValue::Dynamic(StylexDynamicInfo {