Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .changepacks/changepack_log_stylex_include_override.json
Original file line number Diff line number Diff line change
@@ -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"
}
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
4 changes: 3 additions & 1 deletion libs/extractor/src/extractor/extract_style_from_stylex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)),
Expand Down Expand Up @@ -354,6 +354,7 @@ fn push_decomposed(styles: &mut Vec<ExtractStyleProp<'_>>, decomposed: Vec<Decom
/// `include()` call
fn include(
spread: &SpreadElement<'_>,
position: usize,
resolver: StylexResolver<'_>,
) -> Option<Result<StylexIncludeRef, (u32, String)>> {
let Expression::CallExpression(call) = &spread.argument else {
Expand All @@ -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((
Expand Down
56 changes: 55 additions & 1 deletion libs/extractor/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16188,7 +16188,10 @@ export const a = (m) => <Box {prop} />"
#[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]
Expand All @@ -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() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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",
}
36 changes: 36 additions & 0 deletions libs/extractor/src/stylex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<Vec<_>>()
.join(" ")
}

/// Whether `callee` is a member of the `types` the package gives, as
Expand Down
93 changes: 63 additions & 30 deletions libs/extractor/src/visit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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<String, SymbolId>,
include: &StylexIncludeRef,
) -> Option<Vec<(String, String)>> {
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<Vec<(String, String)>> {
Expand Down Expand Up @@ -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));

Expand All @@ -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)
Expand All @@ -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(),
Expand All @@ -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 {
Expand Down
Loading