diff --git a/.changepacks/changepack_log_later_shorthand_wins.json b/.changepacks/changepack_log_later_shorthand_wins.json
new file mode 100644
index 000000000..c21e9b3c6
--- /dev/null
+++ b/.changepacks/changepack_log_later_shorthand_wins.json
@@ -0,0 +1,8 @@
+{
+ "changes": {
+ "bindings/devup-ui-wasm/package.json": "Patch",
+ "bindings/devup-ui-binding/package.json": "Patch"
+ },
+ "note": "A shorthand set across a boundary after a longhand it covers now wins, as the later style: `css({ borderTopWidth: 2 }, { borderWidth: 1 })` keeps only `border-width`. The boundaries are css() arguments, a spread among Box props or style object keys (a prop after a spread, a later spread), and css()/styled composition. Within one level, the keys of one object literal (css(), styled objects, each nested selector or breakpoint object) or the Box props between two spreads, key order is no \"later wins\" signal: both are kept and the sheet, which writes a longhand after its shorthands, lets the longhand win, so `css({ borderTopWidth: 2, borderWidth: 1 })` keeps border-top-width and `` keeps its gradient text. The earlier longhand's atom is dropped only when both are static and unconditional at the same selector, breakpoint, layer and style order; a conditional or dynamic value keeps both and the sheet order decides. globalCss keeps every declaration in the order written. No new build errors",
+ "date": "2026-11-16T00:00:00.000Z"
+}
diff --git a/libs/css/src/property_order.rs b/libs/css/src/property_order.rs
index 1fdce3c33..0a66cb2f0 100644
--- a/libs/css/src/property_order.rs
+++ b/libs/css/src/property_order.rs
@@ -472,22 +472,37 @@ static SHORTHANDS: &[(&str, &[&str])] = &[
),
];
-/// The sort key of every property set through a shorthand:
-/// (greatest name among it and its shorthands, how deeply it is covered).
-static COVERED: LazyLock> = LazyLock::new(|| {
+/// The shorthands setting each property directly.
+static PARENTS: LazyLock>> = LazyLock::new(|| {
let mut parents: HashMap<&'static str, Vec<&'static str>> = HashMap::new();
for (shorthand, longhands) in SHORTHANDS {
for longhand in *longhands {
parents.entry(longhand).or_default().push(shorthand);
}
}
+ parents
+});
+
+/// The sort key of every property set through a shorthand:
+/// (greatest name among it and its shorthands, how deeply it is covered).
+static COVERED: LazyLock> = LazyLock::new(|| {
let mut keys = HashMap::new();
- for property in parents.keys() {
- covered_key(property, &parents, &mut keys);
+ for property in PARENTS.keys() {
+ covered_key(property, &PARENTS, &mut keys);
}
keys
});
+/// Whether the kebab-case `shorthand` sets `property`, directly or through
+/// another shorthand it sets, so declaring it replaces `property`.
+pub fn covers(shorthand: &str, property: &str) -> bool {
+ PARENTS.get(property).is_some_and(|parents| {
+ parents
+ .iter()
+ .any(|parent| *parent == shorthand || covers(shorthand, parent))
+ })
+}
+
fn covered_key(
property: &'static str,
parents: &HashMap<&'static str, Vec<&'static str>>,
@@ -569,4 +584,21 @@ mod tests {
fn orders_properties(#[case] a: &str, #[case] b: &str, #[case] expected: Ordering) {
assert_eq!(cmp_properties(a, b), expected);
}
+
+ #[rstest]
+ #[case("border-width", "border-top-width", true)]
+ #[case("border", "border-top-width", true)]
+ #[case("place-items", "align-items", true)]
+ #[case("white-space", "text-wrap-mode", true)]
+ #[case("border-top-width", "border-width", false)]
+ #[case("border-width", "border-width", false)]
+ #[case("margin", "padding-top", false)]
+ #[case("color", "display", false)]
+ fn covers_what_a_shorthand_sets(
+ #[case] shorthand: &str,
+ #[case] property: &str,
+ #[case] expected: bool,
+ ) {
+ assert_eq!(covers(shorthand, property), expected);
+ }
}
diff --git a/libs/extractor/src/composition.rs b/libs/extractor/src/composition.rs
index e6ab8bd59..e56e7d67d 100644
--- a/libs/extractor/src/composition.rs
+++ b/libs/extractor/src/composition.rs
@@ -8,13 +8,17 @@ use oxc_allocator::{CloneIn, GetAllocator};
use oxc_ast::ast::Expression;
use oxc_ast::builder::AstBuilder;
+use crate::extract_style::extract_static_style::ExtractStaticStyle;
use crate::{ExtractStyleProp, ExtractStyleValue};
#[path = "composition_keys.rs"]
mod key_query;
#[path = "composition_residual.rs"]
mod residual;
+#[path = "composition_shorthands.rs"]
+pub(crate) mod shorthands;
pub(crate) use residual::{CascadeKey, Coverage, coverage};
+use shorthands::replaces;
#[cfg(test)]
#[path = "layer_registration_tests.rs"]
@@ -143,6 +147,9 @@ impl<'a> Composition<'a> {
}
fn overlay(&mut self, ast_builder: &AstBuilder<'a>, key: CascadeKey, overlay: Overlay<'a>) {
+ if let Overlay::Atom(ExtractStyleValue::Static(shorthand)) = &overlay {
+ self.drop_covered(shorthand);
+ }
let previous = self
.entries
.iter()
@@ -152,6 +159,14 @@ impl<'a> Composition<'a> {
self.entries.push((key, choice));
}
+ /// A shorthand a later part sets replaces the longhands it covers that
+ /// earlier parts set, under the rule of `shorthands`
+ fn drop_covered(&mut self, shorthand: &ExtractStaticStyle) {
+ self.entries.retain(|(_, choice)| {
+ !matches!(choice, Choice::Atom(ExtractStyleValue::Static(longhand)) if replaces(shorthand, longhand))
+ });
+ }
+
/// A class applying after the composed parts, whose styles `values` the
/// build knows: what it sets replaces what they set
pub fn cover(&mut self, values: &[ExtractStyleValue]) {
diff --git a/libs/extractor/src/composition_shorthand_tests.rs b/libs/extractor/src/composition_shorthand_tests.rs
new file mode 100644
index 000000000..b1d2411ef
--- /dev/null
+++ b/libs/extractor/src/composition_shorthand_tests.rs
@@ -0,0 +1,251 @@
+//! A shorthand set across a boundary after a longhand it covers wins (#688),
+//! whatever order the stylesheet gives the two (#690 writes a longhand after
+//! its shorthands): the earlier longhand's atom is dropped when both are
+//! static and unconditional at the same selector, breakpoint, layer and style
+//! order. The boundaries are `css(a, b)` arguments, spreads among JSX
+//! attributes or object properties, and styled composition. Declarations of
+//! one level, the keys of one object literal or the JSX attributes between two
+//! spreads, keep both and the stylesheet's order lets the longhand win
+use crate::{ExtractOption, extract};
+use css::{class_map::reset_class_map, file_map::reset_file_map};
+use rstest::rstest;
+use serial_test::serial;
+
+/// The debug class names `code` gives, sorted
+fn atoms(filename: &str, code: &str) -> Vec {
+ reset_class_map();
+ reset_file_map();
+ css::debug::set_debug(true);
+ let output = extract(filename, code, ExtractOption::default());
+ css::debug::set_debug(false);
+ let output = output.unwrap_or_else(|error| panic!("{error}"));
+ let mut atoms: Vec = output
+ .code
+ .split(|c: char| c.is_whitespace() || matches!(c, '"' | '`' | '{' | '}' | '$'))
+ .filter_map(|token| token.strip_suffix("-a"))
+ .map(ToString::to_string)
+ .collect();
+ atoms.sort_unstable();
+ atoms.dedup();
+ atoms
+}
+
+const CSS: &str = "import { css } from '@devup-ui/react';";
+const BOX: &str = "import { Box } from '@devup-ui/react';";
+const STYLED: &str = "import { styled } from '@devup-ui/react';";
+
+/// Across a boundary, the later shorthand drops the earlier longhand
+#[rstest]
+#[case::css_arguments(
+ format!("{CSS} export const a = css({{ borderTopWidth: 2 }}, {{ borderWidth: 1 }});"),
+ &["border-width-0-4px--255"]
+)]
+#[case::css_arguments_transitive(
+ format!("{CSS} export const a = css({{ borderTopWidth: 2 }}, {{ border: 'solid' }});"),
+ &["border-0-solid--255"]
+)]
+#[case::css_arguments_place(
+ format!("{CSS} export const a = css({{ alignItems: 'start' }}, {{ placeItems: 'center' }});"),
+ &["place-items-0-center--255"]
+)]
+#[case::css_arguments_nested(
+ format!("{CSS} export const a = css({{ _hover: {{ borderTopWidth: 2 }} }}, {{ _hover: {{ borderWidth: 1 }} }});"),
+ &["border-width-0-4px-_a__c_hover-255"]
+)]
+#[case::css_composed(
+ format!("{CSS} const b = css({{ borderTopWidth: 2 }}); export const a = css(b, {{ borderWidth: 1 }});"),
+ &["border-top-width-0-8px--255", "border-width-0-4px--255"]
+)]
+#[case::css_property_after_spread(
+ format!("{CSS} const b = {{ borderTopWidth: 2 }}; export const a = css({{ ...b, borderWidth: 1 }});"),
+ &["border-width-0-4px--255"]
+)]
+#[case::css_nested_property_after_spread(
+ format!("{CSS} const b = {{ borderTopWidth: 2 }}; export const a = css({{ _hover: {{ ...b, borderWidth: 1 }} }});"),
+ &["border-width-0-4px-_a__c_hover-255"]
+)]
+#[case::css_property_after_literal_spread(
+ format!("{CSS} export const a = css({{ ...{{ borderTopWidth: 2 }}, borderWidth: 1 }});"),
+ &["border-width-0-4px--255"]
+)]
+#[case::css_property_after_nested_literal_spreads(
+ format!("{CSS} export const a = css({{ ...{{ ...{{ borderTopWidth: 2 }}, color: 'red' }}, ...{{}}, borderWidth: 1 }});"),
+ &["border-width-0-4px--255", "color-0-red--255"]
+)]
+#[case::css_literal_spread_after_property(
+ format!("{CSS} export const a = css({{ borderTopWidth: 2, ...{{ borderWidth: 1 }} }});"),
+ &["border-width-0-4px--255"]
+)]
+#[case::box_spread(
+ format!("{BOX} export const a = ;"),
+ &["border-width-0-4px--255"]
+)]
+#[case::box_attribute_before_spread(
+ format!("{BOX} export const a = ;"),
+ &["border-width-0-4px--255"]
+)]
+#[case::box_attribute_runs(
+ format!("{BOX} export const a = (p) => ;"),
+ &["border-width-0-4px--255"]
+)]
+#[serial]
+fn later_shorthand_across_a_boundary_drops_the_longhand(
+ #[case] code: String,
+ #[case] expected: &[&str],
+) {
+ assert_eq!(atoms("a.tsx", &code), expected);
+}
+
+/// Within one level, the keys of one object literal or the JSX attributes
+/// between two spreads, key order is no "later wins" signal: both stay and the
+/// longhand, written after its shorthands in the sheet, wins
+#[rstest]
+#[case::css_object(
+ format!("{CSS} export const a = css({{ borderTopWidth: 2, borderWidth: 1 }});"),
+ &["border-top-width-0-8px--255", "border-width-0-4px--255"]
+)]
+#[case::css_transitive(
+ format!("{CSS} export const a = css({{ borderTopWidth: 2, border: 'solid' }});"),
+ &["border-0-solid--255", "border-top-width-0-8px--255"]
+)]
+#[case::css_place(
+ format!("{CSS} export const a = css({{ alignItems: 'start', placeItems: 'center' }});"),
+ &["align-items-0-start--255", "place-items-0-center--255"]
+)]
+#[case::css_style_order(
+ format!("{CSS} export const a = css({{ borderTopWidth: 2, borderWidth: 1, styleOrder: 3 }});"),
+ &["border-top-width-0-8px--3", "border-width-0-4px--3"]
+)]
+#[case::css_nested(
+ format!("{CSS} export const a = css({{ _hover: {{ borderTopWidth: 2, borderWidth: 1 }} }});"),
+ &["border-top-width-0-8px-_a__c_hover-255", "border-width-0-4px-_a__c_hover-255"]
+)]
+#[case::box_selector(
+ format!("{BOX} export const a = ;"),
+ &["border-top-width-0-8px-_a__c_hover-255", "border-width-0-4px-_a__c_hover-255"]
+)]
+#[case::box_css_prop(
+ format!("{BOX} export const a = ;"),
+ &["border-top-width-0-8px--255", "border-width-0-4px--255"]
+)]
+#[case::styled_member(
+ format!("{STYLED} export const A = styled.div({{ borderTopWidth: 2, borderWidth: 1 }});"),
+ &["border-top-width-0-8px--255", "border-width-0-4px--255"]
+)]
+#[case::styled_call(
+ format!("{STYLED} export const A = styled('div')({{ borderTopWidth: 2, borderWidth: 1 }});"),
+ &["border-top-width-0-8px--255", "border-width-0-4px--255"]
+)]
+#[case::longhand_later(
+ format!("{CSS} export const a = css({{ borderWidth: 1, borderTopWidth: 2 }});"),
+ &["border-top-width-0-8px--255", "border-width-0-4px--255"]
+)]
+#[case::box_props(
+ format!("{BOX} export const a = ;"),
+ &["border-top-width-0-8px--255", "border-width-0-4px--255"]
+)]
+#[case::box_gradient_text(
+ format!("{BOX} export const a = ;"),
+ &["background-0-red--255", "background-clip-0-text--255"]
+)]
+#[case::box_spread_attribute_runs(
+ format!("{BOX} export const a = (p) => ;"),
+ &["border-top-width-0-8px--255", "border-width-0-4px--255"]
+)]
+#[case::css_spread_property_runs(
+ format!("{CSS} const b = {{ color: 'red' }}; export const a = css({{ ...b, borderTopWidth: 2, borderWidth: 1 }});"),
+ &["border-top-width-0-8px--255", "border-width-0-4px--255", "color-0-red--255"]
+)]
+#[case::css_literal_spread_keeps_its_own_level(
+ format!("{CSS} export const a = css({{ ...{{ borderTopWidth: 2, borderWidth: 1 }}, color: 'red' }});"),
+ &["border-top-width-0-8px--255", "border-width-0-4px--255", "color-0-red--255"]
+)]
+#[case::css_argument_keeps_its_own_level(
+ format!("{CSS} export const a = css({{ color: 'red' }}, {{ borderTopWidth: 2, borderWidth: 1 }});"),
+ &["border-top-width-0-8px--255", "border-width-0-4px--255", "color-0-red--255"]
+)]
+#[serial]
+fn same_level_keeps_both_and_the_longhand_wins(#[case] code: String, #[case] expected: &[&str]) {
+ assert_eq!(atoms("a.tsx", &code), expected);
+}
+
+/// Across a boundary the longhand still stays where the build cannot tell the
+/// shorthand replaces it: written later, under another selector or breakpoint,
+/// under a condition, or at another style order
+#[rstest]
+#[case::longhand_in_later_argument(
+ format!("{CSS} export const a = css({{ borderWidth: 1 }}, {{ borderTopWidth: 2 }});"),
+ &["border-top-width-0-8px--255", "border-width-0-4px--255"]
+)]
+#[case::other_selector(
+ format!("{CSS} export const a = css({{ borderTopWidth: 2 }}, {{ _hover: {{ borderWidth: 1 }} }});"),
+ &["border-top-width-0-8px--255", "border-width-0-4px-_a__c_hover-255"]
+)]
+#[case::other_breakpoint(
+ format!("{CSS} export const a = css({{ borderTopWidth: [2, 3] }}, {{ borderWidth: 1 }});"),
+ &["border-top-width-1-12px--255", "border-width-0-4px--255"]
+)]
+#[case::unrelated(
+ format!("{CSS} export const a = css({{ paddingTop: 2 }}, {{ margin: 1 }});"),
+ &["margin-0-4px--255", "padding-top-0-8px--255"]
+)]
+#[case::conditional_shorthand(
+ format!("{BOX} export const a = (on) => ;"),
+ &["border-top-width-0-8px--255", "border-width-0-12px--255", "border-width-0-4px--255"]
+)]
+#[case::conditional_longhand(
+ format!("{BOX} export const a = (on) => ;"),
+ &["border-top-width-0-12px--255", "border-top-width-0-8px--255", "border-width-0-4px--255"]
+)]
+#[case::other_style_order(
+ format!("{CSS} const b = css({{ borderTopWidth: 2, styleOrder: 3 }}); export const a = css(b, {{ borderWidth: 1 }});"),
+ &["border-top-width-0-8px--3", "border-width-0-4px--255"]
+)]
+#[serial]
+fn longhand_stays_unless_a_known_later_shorthand_replaces_it(
+ #[case] code: String,
+ #[case] expected: &[&str],
+) {
+ assert_eq!(atoms("a.tsx", &code), expected);
+}
+
+/// A global rule writes its declarations in the order written, so it keeps
+/// both: the later shorthand already wins there
+#[test]
+#[serial]
+fn global_rule_keeps_both_declarations() {
+ reset_class_map();
+ reset_file_map();
+ let code = "import { globalCss } from '@devup-ui/react'; globalCss({ body: { marginTop: 10, margin: 0 } });";
+ let output =
+ extract("a.tsx", code, ExtractOption::default()).unwrap_or_else(|error| panic!("{error}"));
+ let mut properties: Vec = output
+ .styles
+ .iter()
+ .filter_map(|style| match style {
+ crate::ExtractStyleValue::Static(style) => Some(style.property.clone()),
+ _ => None,
+ })
+ .collect();
+ properties.sort_unstable();
+ assert_eq!(properties, ["margin", "margin-top"]);
+}
+
+/// A shorthand held by a variable does not replace a longhand, nor is a
+/// longhand held by one replaced
+#[rstest]
+#[case(
+ "",
+ "border-top-width-0-8px--255"
+)]
+#[case(
+ "",
+ "border-width-0-4px--255"
+)]
+#[serial]
+fn dynamic_atoms_stay(#[case] element: &str, #[case] static_atom: &str) {
+ let code = format!("{BOX} export const a = (width) => {element};");
+ let atoms = atoms("a.tsx", &code);
+ assert!(atoms.iter().any(|atom| atom == static_atom), "{atoms:?}");
+ assert_eq!(atoms.len(), 2, "{atoms:?}");
+}
diff --git a/libs/extractor/src/composition_shorthands.rs b/libs/extractor/src/composition_shorthands.rs
new file mode 100644
index 000000000..94228b5af
--- /dev/null
+++ b/libs/extractor/src/composition_shorthands.rs
@@ -0,0 +1,178 @@
+//! A shorthand set across a boundary after a longhand it covers wins, as the
+//! later style (#688), whatever order the stylesheet gives the two: the sheet
+//! writes a longhand after every shorthand covering it, so the build drops the
+//! earlier longhand's atom instead.
+//!
+//! The boundaries are the ones that order styles: the arguments of `css(a, b)`,
+//! a spread among JSX attributes or object properties, and styled composition
+//! or extension. Declarations of one level, the keys of one object literal or
+//! the JSX attributes between two spreads, are not ordered by where they are
+//! written, so a shorthand there drops no longhand beside it: in
+//! `css({ borderTopWidth: 2, borderWidth: 1 })` both stay and the stylesheet's
+//! order (a longhand after its shorthands) lets `border-top-width` win.
+//!
+//! Only what the build fully knows is dropped: both atoms are static and set
+//! unconditionally, at the same selector, breakpoint, layer and style order. A
+//! longhand or shorthand under a condition, or held by a variable, stays, and
+//! the stylesheet's order decides between them.
+
+use crate::extract_style::extract_static_style::ExtractStaticStyle;
+use crate::{ExtractStyleProp, ExtractStyleValue};
+use css::style_selector::StyleSelector;
+
+/// Whether the static `shorthand` replaces the static `longhand` written
+/// before it: it covers the property where the two compete alike. A global
+/// rule keeps both: it writes its declarations in the order written, where
+/// the later one already wins
+pub(crate) fn replaces(shorthand: &ExtractStaticStyle, longhand: &ExtractStaticStyle) -> bool {
+ !matches!(shorthand.selector, Some(StyleSelector::Global(..)))
+ && css::property_order::covers(&shorthand.property, &longhand.property)
+ && shorthand.selector == longhand.selector
+ && shorthand.level == longhand.level
+ && shorthand.layer == longhand.layer
+ && shorthand.style_order == longhand.style_order
+}
+
+/// The atom `prop` sets unconditionally to a static value
+const fn static_atom<'p>(prop: &'p ExtractStyleProp<'_>) -> Option<&'p ExtractStaticStyle> {
+ match prop {
+ ExtractStyleProp::Static(ExtractStyleValue::Static(style)) => Some(style),
+ _ => None,
+ }
+}
+
+/// The static atoms of the declarations read so far, read from the last
+/// declaration to its first
+#[derive(Default)]
+struct LaterDeclarations(Vec);
+
+impl LaterDeclarations {
+ /// `styles` without the longhands a shorthand read so far covers
+ fn without_covered<'a>(&self, styles: Vec>) -> Vec> {
+ styles
+ .into_iter()
+ .filter_map(|prop| self.keep(prop))
+ .collect()
+ }
+
+ /// `prop` without what a later shorthand replaces; the atoms of a
+ /// responsive value apply unconditionally, each at its breakpoint
+ fn keep<'a>(&self, prop: ExtractStyleProp<'a>) -> Option> {
+ match prop {
+ ExtractStyleProp::StaticArray(props) => Some(ExtractStyleProp::StaticArray(
+ props
+ .into_iter()
+ .filter_map(|prop| self.keep(prop))
+ .collect(),
+ )),
+ prop => (!self.covers(&prop)).then_some(prop),
+ }
+ }
+
+ fn record(&mut self, prop: &ExtractStyleProp<'_>) {
+ match prop {
+ ExtractStyleProp::StaticArray(props) => {
+ for prop in props {
+ self.record(prop);
+ }
+ }
+ prop => self.0.extend(static_atom(prop).cloned()),
+ }
+ }
+
+ fn covers(&self, prop: &ExtractStyleProp<'_>) -> bool {
+ static_atom(prop)
+ .is_some_and(|longhand| self.0.iter().any(|shorthand| replaces(shorthand, longhand)))
+ }
+}
+
+/// The static atoms of the JSX attributes or object properties read so far,
+/// read from the last to the first.
+///
+/// The attributes or properties between two spreads form a run of one level:
+/// a shorthand in a run replaces no longhand of the same run, and the
+/// stylesheet's order (a longhand after its shorthands) decides between them.
+/// For JSX this also keeps a run the lint sorts by name
+/// (`perfectionist/sort-jsx-props`, `backgroundClip` before `bg`) as written.
+/// A spread keeps its place among the runs, so a shorthand in a later run or
+/// spread still replaces an earlier longhand. An object spread the build
+/// inlines keeps its properties in runs of their own, and the properties of a
+/// merge of several style objects, `css(a, b)`, run per object they were
+/// written in
+#[derive(Default)]
+pub(crate) struct LaterRuns {
+ /// The atoms of the runs and spreads after the run being read
+ later: LaterDeclarations,
+ /// The atoms of the run being read
+ run: LaterDeclarations,
+ /// Where the run being read was written
+ key: RunKey,
+}
+
+/// Where a property was written: the merged style object, when a call merged
+/// several, and the run between spreads within it
+pub(crate) type RunKey = (Option, usize);
+
+impl LaterRuns {
+ /// The styles of an attribute or property written at `key`, before every
+ /// one read so far, without the longhands a shorthand of a later run or
+ /// spread covers
+ pub(crate) fn member<'a>(
+ &mut self,
+ key: RunKey,
+ styles: Vec>,
+ ) -> Vec> {
+ if key != self.key {
+ self.end_run();
+ self.key = key;
+ }
+ let kept = self.later.without_covered(styles);
+ for prop in &kept {
+ self.run.record(prop);
+ }
+ kept
+ }
+
+ /// A spread, whatever the build reads of it, ends the run being read
+ pub(crate) fn end_run(&mut self) {
+ self.later.0.append(&mut self.run.0);
+ }
+
+ /// The styles of a spread written before every attribute or property read
+ /// so far, without the longhands a later shorthand covers. It ends the run
+ /// being read
+ pub(crate) fn spread<'a>(
+ &mut self,
+ styles: Vec>,
+ ) -> Vec> {
+ self.end_run();
+ let kept = self.later.without_covered(styles);
+ for prop in &kept {
+ self.later.record(prop);
+ }
+ kept
+ }
+}
+
+/// The styles of one property or spread of a style object
+pub(crate) enum Part<'a> {
+ /// A property, with where it was written
+ Property(RunKey, Vec>),
+ Spread(Vec>),
+}
+
+/// The styles of a style object's properties and spreads, given in source
+/// order, without the longhands a shorthand across a spread covers
+pub(crate) fn in_source_order<'a>(parts: Vec>) -> Vec> {
+ let mut later = LaterRuns::default();
+ let mut kept: Vec>> = parts
+ .into_iter()
+ .rev()
+ .map(|part| match part {
+ Part::Property(key, styles) => later.member(key, styles),
+ Part::Spread(styles) => later.spread(styles),
+ })
+ .collect();
+ kept.reverse();
+ kept.into_iter().flatten().collect()
+}
diff --git a/libs/extractor/src/extractor/extract_style_from_expression.rs b/libs/extractor/src/extractor/extract_style_from_expression.rs
index f7b872e40..d4d352765 100644
--- a/libs/extractor/src/extractor/extract_style_from_expression.rs
+++ b/libs/extractor/src/extractor/extract_style_from_expression.rs
@@ -1,6 +1,7 @@
use super::style_inputs::StyleInputs;
use crate::{
ExtractStyleProp,
+ composition::shorthands::{LaterRuns, Part, in_source_order},
css_utils::{css_to_style, css_to_style_literal, descendants, theme_var_reference},
extract_style::{
extract_dynamic_style::ExtractDynamicStyle,
@@ -86,56 +87,85 @@ fn literal_truthiness(expression: &Expression<'_>) -> Option {
/// Merge the object literals spread into `object` in place, a later property
/// replacing an earlier one of the same key as in the object JavaScript builds
pub(crate) fn flatten_spreads<'a>(ast_builder: &AstBuilder<'a>, object: &mut ObjectExpression<'a>) {
+ flatten_spreads_in_runs(ast_builder, object);
+}
+
+/// [`flatten_spreads`], returning for each property left the run it was
+/// written in: the properties between two spreads share a run, and those an
+/// object spread gives keep runs of their own, as the spread was a boundary
+fn flatten_spreads_in_runs<'a>(
+ ast_builder: &AstBuilder<'a>,
+ object: &mut ObjectExpression<'a>,
+) -> Vec {
+ let mut runs = vec![0; object.properties.len()];
if !object.properties.iter().any(|property| {
matches!(property, ObjectPropertyKind::SpreadProperty(spread)
if matches!(unwrap_syntax_only(&spread.argument), Expression::ObjectExpression(_)))
}) {
- return;
+ return runs;
}
+ runs.clear();
let properties = std::mem::replace(
&mut object.properties,
oxc_allocator::Vec::new_in(ast_builder),
);
+ let mut run = 0;
for property in properties {
match property {
ObjectPropertyKind::SpreadProperty(mut spread) => {
if let Expression::ObjectExpression(inner) =
unwrap_syntax_only_mut(&mut spread.argument)
{
- flatten_spreads(ast_builder, inner);
+ let inner_runs = flatten_spreads_in_runs(ast_builder, inner);
let spread_properties = std::mem::replace(
&mut inner.properties,
oxc_allocator::Vec::new_in(ast_builder),
);
- for property in spread_properties {
- push_replacing(&mut object.properties, property);
+ let first = run + 1;
+ run = first + inner_runs.last().copied().unwrap_or_default();
+ for (property, inner_run) in spread_properties.into_iter().zip(inner_runs) {
+ push_replacing(
+ &mut object.properties,
+ &mut runs,
+ property,
+ first + inner_run,
+ );
}
} else {
object
.properties
.push(ObjectPropertyKind::SpreadProperty(spread));
+ runs.push(run);
}
+ run += 1;
}
property @ ObjectPropertyKind::ObjectProperty(_) => {
- push_replacing(&mut object.properties, property);
+ push_replacing(&mut object.properties, &mut runs, property, run);
}
}
}
+ runs
}
fn push_replacing<'a>(
properties: &mut oxc_allocator::Vec<'a, ObjectPropertyKind<'a>>,
+ runs: &mut Vec,
property: ObjectPropertyKind<'a>,
+ run: usize,
) {
if let ObjectPropertyKind::ObjectProperty(added) = &property
&& let Some(key) = get_str_by_property_key(&added.key)
- {
- properties.retain(|existing| {
- !matches!(existing, ObjectPropertyKind::ObjectProperty(existing)
+ && let Some(index) = properties.iter().position(|existing| {
+ matches!(existing, ObjectPropertyKind::ObjectProperty(existing)
if get_str_by_property_key(&existing.key).as_deref() == Some(key.as_ref()))
- });
+ })
+ {
+ // An object literal holds each key once, so one earlier property at most
+ properties.remove(index);
+ runs.remove(index);
}
properties.push(property);
+ runs.push(run);
}
pub(crate) fn unreadable_key<'a>(key: &PropertyKey<'_>, prop: bool) -> ExtractStyleProp<'a> {
@@ -325,8 +355,11 @@ pub(super) fn extract_projected<'a>(
let mut props = None;
return match expression {
Expression::ObjectExpression(obj) => {
- flatten_spreads(ast_builder, obj);
+ let runs = flatten_spreads_in_runs(ast_builder, obj);
let mut props_styles: Vec> = vec![];
+ // Read from the last property, so the ones read so far are the
+ // later ones; only a spread orders them
+ let mut later = LaterRuns::default();
let mut tag = None;
projection.root();
for idx in (0..obj.properties.len()).rev() {
@@ -377,7 +410,10 @@ pub(super) fn extract_projected<'a>(
LiteralHandling::ExpandResponsiveThemeToken,
prepare,
);
- props_styles.extend(styles);
+ props_styles.extend(later.member(
+ (inputs.argument_of(prop.span), runs[idx]),
+ styles,
+ ));
tag = _tag.or(tag);
}
}
@@ -397,7 +433,7 @@ pub(super) fn extract_projected<'a>(
LiteralHandling::ExpandResponsiveThemeToken,
prepare,
);
- props_styles.extend(styles);
+ props_styles.extend(later.spread(styles));
tag = _tag.or(tag);
false
}
@@ -1064,8 +1100,9 @@ pub(super) fn extract_projected<'a>(
}
}
Expression::ObjectExpression(obj) => {
- flatten_spreads(ast_builder, obj);
- let mut props = vec![];
+ let runs = flatten_spreads_in_runs(ast_builder, obj);
+ // Each property's or spread's styles, in source order
+ let mut props: Vec> = vec![];
let selector = match super::selector_params::resolve(inputs, obj, selector) {
Ok(selector) => selector,
Err(error) => {
@@ -1076,11 +1113,11 @@ pub(super) fn extract_projected<'a>(
}
};
- for p in &mut obj.properties {
+ for (p, &run) in obj.properties.iter_mut().zip(&runs) {
let o = match p {
ObjectPropertyKind::ObjectProperty(o) => o,
ObjectPropertyKind::SpreadProperty(spread) => {
- props.extend(
+ props.push(Part::Spread(
projection
.extract(
inputs,
@@ -1091,7 +1128,7 @@ pub(super) fn extract_projected<'a>(
prepare,
)
.styles,
- );
+ ));
continue;
}
};
@@ -1102,7 +1139,10 @@ pub(super) fn extract_projected<'a>(
else {
let error = unreadable_key(&o.key, false);
projection.record(ast_builder, &error);
- props.push(error);
+ props.push(Part::Property(
+ (inputs.argument_of(o.span), run),
+ vec![error],
+ ));
continue;
};
if key_name == "params" {
@@ -1113,7 +1153,10 @@ pub(super) fn extract_projected<'a>(
o.key.span().start,
) {
projection.record(ast_builder, &error);
- props.push(error);
+ props.push(Part::Property(
+ (inputs.argument_of(o.span), run),
+ vec![error],
+ ));
continue;
}
let mut properties = style_key_properties(&key_name, &o.value);
@@ -1121,7 +1164,8 @@ pub(super) fn extract_projected<'a>(
let name: &str = &name;
let mut sibling = (properties.len() != 0)
.then(|| o.value.clone_in_with_semantic_ids(ast_builder.allocator()));
- props.extend(
+ props.push(Part::Property(
+ (inputs.argument_of(o.span), run),
projection
.extract(
inputs,
@@ -1132,11 +1176,11 @@ pub(super) fn extract_projected<'a>(
prepare,
)
.styles,
- );
+ ));
}
}
ExtractResult {
- styles: props,
+ styles: in_source_order(props),
..ExtractResult::default()
}
}
diff --git a/libs/extractor/src/extractor/style_inputs.rs b/libs/extractor/src/extractor/style_inputs.rs
index f90195d27..5b377d728 100644
--- a/libs/extractor/src/extractor/style_inputs.rs
+++ b/libs/extractor/src/extractor/style_inputs.rs
@@ -6,11 +6,15 @@ use oxc_ast::{
ast::{Expression, UnaryOperator},
builder::AstBuilder,
};
+use oxc_span::Span;
#[derive(Clone, Copy)]
pub(crate) struct StyleInputs<'s, 'a> {
pub ast: &'s AstBuilder<'a>,
values: Option<&'s StyleValues<'s>>,
+ /// The source spans of the style objects a call merged into the one
+ /// being read, in order: each is a level of its own
+ arguments: &'s [Span],
}
impl<'s, 'a> StyleInputs<'s, 'a> {
@@ -18,9 +22,22 @@ impl<'s, 'a> StyleInputs<'s, 'a> {
Self {
ast,
values: Some(values),
+ arguments: &[],
}
}
+ /// Read a merge of the style objects at `arguments`
+ pub const fn with_arguments(self, arguments: &'s [Span]) -> Self {
+ Self { arguments, ..self }
+ }
+
+ /// Which of the merged style objects a property at `span` was written in
+ pub fn argument_of(self, span: Span) -> Option {
+ self.arguments
+ .iter()
+ .position(|argument| argument.start <= span.start && span.end <= argument.end)
+ }
+
pub fn absent(self, expression: &Expression<'_>) -> bool {
absent(expression, self.values)
}
@@ -28,7 +45,11 @@ impl<'s, 'a> StyleInputs<'s, 'a> {
impl<'s, 'a> From<&'s AstBuilder<'a>> for StyleInputs<'s, 'a> {
fn from(ast: &'s AstBuilder<'a>) -> Self {
- Self { ast, values: None }
+ Self {
+ ast,
+ values: None,
+ arguments: &[],
+ }
}
}
diff --git a/libs/extractor/src/lib.rs b/libs/extractor/src/lib.rs
index fe1bb8dc4..17516dcd5 100644
--- a/libs/extractor/src/lib.rs
+++ b/libs/extractor/src/lib.rs
@@ -22,6 +22,8 @@ mod class_selection_support;
mod class_selection_tests;
mod component;
mod composition;
+#[cfg(test)]
+mod composition_shorthand_tests;
mod const_fold;
#[cfg(test)]
mod css_composition_rest_tests;
diff --git a/libs/extractor/src/snapshots/extractor__tests__style_results_read_as_values.snap b/libs/extractor/src/snapshots/extractor__tests__style_results_read_as_values.snap
index 835289962..08fa1ab88 100644
--- a/libs/extractor/src/snapshots/extractor__tests__style_results_read_as_values.snap
+++ b/libs/extractor/src/snapshots/extractor__tests__style_results_read_as_values.snap
@@ -141,5 +141,5 @@ ToBTreeSet {
},
),
},
- code: "import \"@devup-ui/react/devup-ui-0.css\";\nimport { forwardRef as __devupForwardRef } from \"react\";\nconst __devupStyled = (c) => (c.styledComponentId = \"devup\", c);\nimport { Global } from \"@devup-ui/react/compat\";\nconst fadeIn = \"a-a\";\nconst slide = \"a-b\";\nconst card = \"a-c\";\nexport const a = \"a-d a-e\";\nexport const b = \"a-c a-f\";\nexport const c = \"a-g\";\nexport const d = ;\nexport const E = __devupStyled(__devupForwardRef(({ style, className, as: DevupAs = \"div\", forwardedAs, ...rest }, __devupRef) => k[0] !== \"$\" && k !== \"theme\"))} ref={__devupRef} as={forwardedAs} className={className ? `a--a a-i ${className}` : \"a--a a-i\"} style={style} />));\n;\nexport const g = ;\n",
+ code: "import \"@devup-ui/react/devup-ui-0.css\";\nimport { forwardRef as __devupForwardRef } from \"react\";\nconst __devupStyled = (c) => (c.styledComponentId = \"devup\", c);\nimport { Global } from \"@devup-ui/react/compat\";\nconst fadeIn = \"a-a\";\nconst slide = \"a-b\";\nconst card = \"a-c\";\nexport const a = \"a-d a-e\";\nexport const b = \"a-c a-f\";\nexport const c = \"a-g\";\nexport const d = ;\nexport const E = __devupStyled(__devupForwardRef(({ style, className, as: DevupAs = \"div\", forwardedAs, ...rest }, __devupRef) => k[0] !== \"$\" && k !== \"theme\"))} ref={__devupRef} as={forwardedAs} className={className ? `a--a a-i ${className}` : \"a--a a-i\"} style={style} />));\n;\nexport const g = ;\n",
}
diff --git a/libs/extractor/src/visit.rs b/libs/extractor/src/visit.rs
index 922795ae0..abe0c4f6e 100644
--- a/libs/extractor/src/visit.rs
+++ b/libs/extractor/src/visit.rs
@@ -4359,10 +4359,13 @@ impl<'a> VisitMut<'a> for DevupVisitor<'a> {
call.arguments =
oxc_allocator::Vec::from_array_in([Argument::from(classes)], &self.ast);
}
+ // The style objects merged below stay levels of their own
+ let mut merged_arguments = Vec::new();
let composed_classes = if is_css
&& let Some(StyleArguments { classes, rules }) =
style_arguments(&self.ast, &call.arguments)
{
+ merged_arguments = call.arguments.iter().map(GetSpan::span).collect();
call.arguments =
oxc_allocator::Vec::from_array_in([Argument::from(rules)], &self.ast);
classes
@@ -4379,7 +4382,8 @@ impl<'a> VisitMut<'a> for DevupVisitor<'a> {
*it = if r.is_css() {
let (result, authored) =
crate::extractor::style_order_projection::extract_with_order(
- StyleInputs::with_values(&self.ast, &self.style_values),
+ StyleInputs::with_values(&self.ast, &self.style_values)
+ .with_arguments(&merged_arguments),
None,
if let Argument::SpreadElement(spread) = &mut call.arguments[0] {
&mut spread.argument
@@ -5508,6 +5512,10 @@ impl<'a> VisitMut<'a> for DevupVisitor<'a> {
// extract ExtractStyleProp and remain style and class name, just extract
let mut duplicate_set = FxHashSet::default();
+ // Attributes are read from the last, so the ones read so far are
+ // the later ones; only a spread orders them, as the lint sorts the
+ // rest by name
+ let mut later = crate::composition::shorthands::LaterRuns::default();
let mut parsed_style_order = ParsedStyleOrder::None;
let mut style_vars = None;
let mut props = None;
@@ -5576,13 +5584,15 @@ impl<'a> VisitMut<'a> for DevupVisitor<'a> {
&disassembled,
at,
);
- props_styles.extend(styles.into_iter().rev());
+ props_styles
+ .extend(later.member((None, 0), styles).into_iter().rev());
tag_name = tag.unwrap_or(tag_name);
}
duplicate_set.insert(disassembled);
}
}
} else if let JSXAttributeItem::SpreadAttribute(spread) = &mut attr {
+ later.end_run();
if self.is_rule_branch(&spread.argument) {
self.style_values.read_in(&self.ast, &mut spread.argument);
crate::style_order_validation::validate_rules(
@@ -5598,7 +5608,7 @@ impl<'a> VisitMut<'a> for DevupVisitor<'a> {
&None,
LiteralHandling::ExpandResponsiveThemeToken,
);
- props_styles.extend(styles.into_iter().rev());
+ props_styles.extend(later.spread(styles).into_iter().rev());
if element_props::has_runtime_props(&spread.argument) {
attrs.insert(i, attr);
}
@@ -5646,7 +5656,7 @@ impl<'a> VisitMut<'a> for DevupVisitor<'a> {
}
style_vars = style_vars.or(extracted.style_vars);
props = props.or(extracted.props);
- props_styles.extend(extracted.styles);
+ props_styles.extend(later.spread(extracted.styles));
if !object.properties.is_empty() {
attrs.insert(i, attr);
}
diff --git a/libs/sheet/src/lib.rs b/libs/sheet/src/lib.rs
index 4a3478516..ecb8e8a82 100644
--- a/libs/sheet/src/lib.rs
+++ b/libs/sheet/src/lib.rs
@@ -2126,7 +2126,7 @@ mod tests {
"import * as stylex from '@stylexjs/stylex';const s=stylex.create({a:{borderTopWidth:2,alignItems:'end'},b:{borderWidth:1,placeItems:'start'}});"
)]
#[case::box_props(
- "import {Box} from '@devup-ui/react';"
+ "import {Box} from '@devup-ui/react';"
)]
#[serial]
fn extracted_longhands_win_over_shorthands(#[case] code: &str) {