From 3bb2e83a8bbb555a187678424b1cb8b9f48db45a Mon Sep 17 00:00:00 2001 From: owjs3901 Date: Sun, 15 Nov 2026 23:24:06 +0900 Subject: [PATCH 1/4] fix(sheet): write a longhand after every shorthand that covers it Atomic rules of one selector and breakpoint were sorted by property name, so `border-width` came after `border-top-width` and `place-items` after `align-items`, and the shorthand won. StyleX's default property-specificity policy, and atomic CSS generally, let a longhand win regardless of order. css::property_order lists each CSS shorthand and the properties it sets. A property sorts under the greatest name among itself and its covering shorthands, then by how deeply it is covered, so it lands right after its last shorthand while unrelated properties keep their alphabetical order. `all` sorts first. The sheet uses this order for class and at-rule declarations of every source, not only StyleX. Co-Authored-By: Claude Opus 5.5 --- ...angepack_log_longhand_after_shorthand.json | 8 + libs/css/src/lib.rs | 1 + libs/css/src/property_order.rs | 572 ++++++++++++++++++ libs/sheet/src/lib.rs | 67 +- 4 files changed, 645 insertions(+), 3 deletions(-) create mode 100644 .changepacks/changepack_log_longhand_after_shorthand.json create mode 100644 libs/css/src/property_order.rs diff --git a/.changepacks/changepack_log_longhand_after_shorthand.json b/.changepacks/changepack_log_longhand_after_shorthand.json new file mode 100644 index 000000000..b34cc458a --- /dev/null +++ b/.changepacks/changepack_log_longhand_after_shorthand.json @@ -0,0 +1,8 @@ +{ + "changes": { + "bindings/devup-ui-wasm/package.json": "Patch", + "bindings/devup-ui-binding/package.json": "Patch" + }, + "note": "A longhand now wins over a shorthand that covers it, as StyleX's property-specificity policy and atomic CSS expect: rules of one selector and breakpoint were sorted by property name, so `border-width` came after `border-top-width` and `place-items` after `align-items` and the shorthand won. Each property now sorts right after the last shorthand covering it (`all` first); unrelated properties keep their alphabetical order. This applies to every path that writes the sheet: StyleX, Box props, css(), styled and the compat APIs. No new build errors", + "date": "2026-11-15T00:00:00.000Z" +} diff --git a/libs/css/src/lib.rs b/libs/css/src/lib.rs index 00dcc341d..22de4cdde 100644 --- a/libs/css/src/lib.rs +++ b/libs/css/src/lib.rs @@ -13,6 +13,7 @@ mod num_to_nm_base; pub mod optimize_multi_css_value; pub mod optimize_value; mod property_names; +pub mod property_order; pub mod quoted; pub mod rm_css_comment; pub mod selector_params; diff --git a/libs/css/src/property_order.rs b/libs/css/src/property_order.rs new file mode 100644 index 000000000..1fdce3c33 --- /dev/null +++ b/libs/css/src/property_order.rs @@ -0,0 +1,572 @@ +//! The order atomic rules take so a longhand always follows the shorthands that +//! cover it. +//! +//! Atomic rules of equal specificity win by their place in the sheet. Sorting them +//! by name alone put `border-width` after `border-top-width` and `place-items` after +//! `align-items`, so the shorthand won. A property is sorted under the greatest name +//! among itself and every shorthand covering it, then by how deeply it is covered, +//! so a covered property comes right after its last shorthand and every other pair +//! keeps its alphabetical order. + +use std::cmp::Ordering; +use std::collections::HashMap; +use std::sync::LazyLock; + +/// Each CSS shorthand and the properties it sets directly. +static SHORTHANDS: &[(&str, &[&str])] = &[ + ( + "animation", + &[ + "animation-name", + "animation-duration", + "animation-timing-function", + "animation-delay", + "animation-iteration-count", + "animation-direction", + "animation-fill-mode", + "animation-play-state", + "animation-timeline", + "animation-range", + ], + ), + ( + "animation-range", + &["animation-range-start", "animation-range-end"], + ), + ( + "background", + &[ + "background-attachment", + "background-clip", + "background-color", + "background-image", + "background-origin", + "background-position", + "background-repeat", + "background-size", + ], + ), + ( + "background-position", + &["background-position-x", "background-position-y"], + ), + ( + "border", + &[ + "border-color", + "border-style", + "border-width", + "border-top", + "border-right", + "border-bottom", + "border-left", + "border-image", + ], + ), + ( + "border-top", + &["border-top-color", "border-top-style", "border-top-width"], + ), + ( + "border-right", + &[ + "border-right-color", + "border-right-style", + "border-right-width", + ], + ), + ( + "border-bottom", + &[ + "border-bottom-color", + "border-bottom-style", + "border-bottom-width", + ], + ), + ( + "border-left", + &[ + "border-left-color", + "border-left-style", + "border-left-width", + ], + ), + ( + "border-color", + &[ + "border-top-color", + "border-right-color", + "border-bottom-color", + "border-left-color", + ], + ), + ( + "border-style", + &[ + "border-top-style", + "border-right-style", + "border-bottom-style", + "border-left-style", + ], + ), + ( + "border-width", + &[ + "border-top-width", + "border-right-width", + "border-bottom-width", + "border-left-width", + ], + ), + ( + "border-block", + &[ + "border-block-color", + "border-block-style", + "border-block-width", + "border-block-start", + "border-block-end", + ], + ), + ( + "border-block-start", + &[ + "border-block-start-color", + "border-block-start-style", + "border-block-start-width", + ], + ), + ( + "border-block-end", + &[ + "border-block-end-color", + "border-block-end-style", + "border-block-end-width", + ], + ), + ( + "border-block-color", + &["border-block-start-color", "border-block-end-color"], + ), + ( + "border-block-style", + &["border-block-start-style", "border-block-end-style"], + ), + ( + "border-block-width", + &["border-block-start-width", "border-block-end-width"], + ), + ( + "border-inline", + &[ + "border-inline-color", + "border-inline-style", + "border-inline-width", + "border-inline-start", + "border-inline-end", + ], + ), + ( + "border-inline-start", + &[ + "border-inline-start-color", + "border-inline-start-style", + "border-inline-start-width", + ], + ), + ( + "border-inline-end", + &[ + "border-inline-end-color", + "border-inline-end-style", + "border-inline-end-width", + ], + ), + ( + "border-inline-color", + &["border-inline-start-color", "border-inline-end-color"], + ), + ( + "border-inline-style", + &["border-inline-start-style", "border-inline-end-style"], + ), + ( + "border-inline-width", + &["border-inline-start-width", "border-inline-end-width"], + ), + ( + "border-image", + &[ + "border-image-outset", + "border-image-repeat", + "border-image-slice", + "border-image-source", + "border-image-width", + ], + ), + ( + "border-radius", + &[ + "border-top-left-radius", + "border-top-right-radius", + "border-bottom-right-radius", + "border-bottom-left-radius", + ], + ), + ( + "column-rule", + &[ + "column-rule-color", + "column-rule-style", + "column-rule-width", + ], + ), + ("columns", &["column-count", "column-width"]), + ( + "contain-intrinsic-size", + &["contain-intrinsic-width", "contain-intrinsic-height"], + ), + ("container", &["container-name", "container-type"]), + ("flex", &["flex-basis", "flex-grow", "flex-shrink"]), + ("flex-flow", &["flex-direction", "flex-wrap"]), + ( + "font", + &[ + "font-family", + "font-size", + "font-stretch", + "font-style", + "font-variant", + "font-weight", + "line-height", + "font-size-adjust", + "font-kerning", + "font-optical-sizing", + "font-variation-settings", + "font-feature-settings", + "font-language-override", + ], + ), + ( + "font-variant", + &[ + "font-variant-alternates", + "font-variant-caps", + "font-variant-east-asian", + "font-variant-emoji", + "font-variant-ligatures", + "font-variant-numeric", + "font-variant-position", + ], + ), + ( + "font-synthesis", + &[ + "font-synthesis-position", + "font-synthesis-small-caps", + "font-synthesis-style", + "font-synthesis-weight", + ], + ), + ("gap", &["row-gap", "column-gap"]), + ("grid-gap", &["grid-row-gap", "grid-column-gap"]), + ( + "grid", + &[ + "grid-auto-columns", + "grid-auto-flow", + "grid-auto-rows", + "grid-template", + ], + ), + ( + "grid-template", + &[ + "grid-template-areas", + "grid-template-columns", + "grid-template-rows", + ], + ), + ("grid-area", &["grid-row", "grid-column"]), + ("grid-row", &["grid-row-start", "grid-row-end"]), + ("grid-column", &["grid-column-start", "grid-column-end"]), + ("inset", &["top", "right", "bottom", "left"]), + ("inset-block", &["inset-block-start", "inset-block-end"]), + ("inset-inline", &["inset-inline-start", "inset-inline-end"]), + ( + "list-style", + &["list-style-image", "list-style-position", "list-style-type"], + ), + ( + "margin", + &["margin-top", "margin-right", "margin-bottom", "margin-left"], + ), + ("margin-block", &["margin-block-start", "margin-block-end"]), + ( + "margin-inline", + &["margin-inline-start", "margin-inline-end"], + ), + ( + "mask", + &[ + "mask-clip", + "mask-composite", + "mask-image", + "mask-mode", + "mask-origin", + "mask-position", + "mask-repeat", + "mask-size", + "mask-border", + ], + ), + ( + "mask-border", + &[ + "mask-border-mode", + "mask-border-outset", + "mask-border-repeat", + "mask-border-slice", + "mask-border-source", + "mask-border-width", + ], + ), + ( + "offset", + &[ + "offset-anchor", + "offset-distance", + "offset-path", + "offset-position", + "offset-rotate", + ], + ), + ( + "outline", + &["outline-color", "outline-style", "outline-width"], + ), + ("overflow", &["overflow-x", "overflow-y"]), + ( + "overscroll-behavior", + &["overscroll-behavior-x", "overscroll-behavior-y"], + ), + ( + "padding", + &[ + "padding-top", + "padding-right", + "padding-bottom", + "padding-left", + ], + ), + ( + "padding-block", + &["padding-block-start", "padding-block-end"], + ), + ( + "padding-inline", + &["padding-inline-start", "padding-inline-end"], + ), + ("place-content", &["align-content", "justify-content"]), + ("place-items", &["align-items", "justify-items"]), + ("place-self", &["align-self", "justify-self"]), + ( + "position-try", + &["position-try-order", "position-try-fallbacks"], + ), + ( + "scroll-margin", + &[ + "scroll-margin-top", + "scroll-margin-right", + "scroll-margin-bottom", + "scroll-margin-left", + ], + ), + ( + "scroll-margin-block", + &["scroll-margin-block-start", "scroll-margin-block-end"], + ), + ( + "scroll-margin-inline", + &["scroll-margin-inline-start", "scroll-margin-inline-end"], + ), + ( + "scroll-padding", + &[ + "scroll-padding-top", + "scroll-padding-right", + "scroll-padding-bottom", + "scroll-padding-left", + ], + ), + ( + "scroll-padding-block", + &["scroll-padding-block-start", "scroll-padding-block-end"], + ), + ( + "scroll-padding-inline", + &["scroll-padding-inline-start", "scroll-padding-inline-end"], + ), + ( + "scroll-timeline", + &["scroll-timeline-name", "scroll-timeline-axis"], + ), + ( + "view-timeline", + &[ + "view-timeline-name", + "view-timeline-axis", + "view-timeline-inset", + ], + ), + ( + "text-decoration", + &[ + "text-decoration-color", + "text-decoration-line", + "text-decoration-style", + "text-decoration-thickness", + ], + ), + ( + "text-emphasis", + &["text-emphasis-color", "text-emphasis-style"], + ), + ("text-wrap", &["text-wrap-mode", "text-wrap-style"]), + ("white-space", &["white-space-collapse", "text-wrap-mode"]), + ( + "transition", + &[ + "transition-behavior", + "transition-delay", + "transition-duration", + "transition-property", + "transition-timing-function", + ], + ), + ( + "-webkit-mask", + &[ + "-webkit-mask-attachment", + "-webkit-mask-clip", + "-webkit-mask-composite", + "-webkit-mask-image", + "-webkit-mask-origin", + "-webkit-mask-position", + "-webkit-mask-repeat", + "-webkit-mask-size", + ], + ), + ( + "-webkit-mask-position", + &["-webkit-mask-position-x", "-webkit-mask-position-y"], + ), + ( + "-webkit-mask-repeat", + &["-webkit-mask-repeat-x", "-webkit-mask-repeat-y"], + ), + ( + "-webkit-text-stroke", + &["-webkit-text-stroke-color", "-webkit-text-stroke-width"], + ), +]; + +/// 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 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); + } + } + let mut keys = HashMap::new(); + for property in parents.keys() { + covered_key(property, &parents, &mut keys); + } + keys +}); + +fn covered_key( + property: &'static str, + parents: &HashMap<&'static str, Vec<&'static str>>, + keys: &mut HashMap<&'static str, (&'static str, u8)>, +) -> (&'static str, u8) { + if let Some(key) = keys.get(property) { + return *key; + } + let key = parents.get(property).map_or((property, 0), |shorthands| { + shorthands + .iter() + .fold((property, 0), |(anchor, rank), shorthand| { + let (parent_anchor, parent_rank) = covered_key(shorthand, parents, keys); + (anchor.max(parent_anchor), rank.max(parent_rank + 1)) + }) + }); + keys.insert(property, key); + key +} + +/// Where `property` sorts: `all` resets every other property, so it sorts first. +fn property_key(property: &str) -> (&str, u8) { + if property == "all" { + return ("", 0); + } + COVERED.get(property).copied().unwrap_or((property, 0)) +} + +/// Order two kebab-case properties so a shorthand comes before every property it +/// covers, keeping the alphabetical order of unrelated properties. +pub fn cmp_properties(a: &str, b: &str) -> Ordering { + property_key(a).cmp(&property_key(b)).then_with(|| a.cmp(b)) +} + +#[cfg(test)] +mod tests { + use super::*; + use rstest::rstest; + + #[test] + fn every_shorthand_sorts_before_what_it_covers() { + fn covers(shorthand: &str, property: &str) -> bool { + SHORTHANDS.iter().any(|(name, longhands)| { + *name == shorthand + && longhands + .iter() + .any(|longhand| *longhand == property || covers(longhand, property)) + }) + } + let names: Vec<&str> = SHORTHANDS + .iter() + .flat_map(|(name, longhands)| std::iter::once(*name).chain(longhands.iter().copied())) + .collect(); + for shorthand in &names { + for property in &names { + if covers(shorthand, property) { + assert_eq!( + cmp_properties(shorthand, property), + Ordering::Less, + "{shorthand} must sort before {property}" + ); + } + } + } + } + + #[rstest] + #[case("border-width", "border-top-width", Ordering::Less)] + #[case("place-items", "align-items", Ordering::Less)] + #[case("border", "border-top-width", Ordering::Less)] + #[case("white-space", "text-wrap-mode", Ordering::Less)] + #[case("padding", "padding-top", Ordering::Less)] + #[case("all", "accent-color", Ordering::Less)] + #[case("accent-color", "all", Ordering::Greater)] + #[case("color", "display", Ordering::Less)] + #[case("--x", "color", Ordering::Less)] + #[case("margin-top", "margin-top", Ordering::Equal)] + #[case("align-items", "display", Ordering::Greater)] + fn orders_properties(#[case] a: &str, #[case] b: &str, #[case] expected: Ordering) { + assert_eq!(cmp_properties(a, b), expected); + } +} diff --git a/libs/sheet/src/lib.rs b/libs/sheet/src/lib.rs index b66cde22f..20add06d6 100644 --- a/libs/sheet/src/lib.rs +++ b/libs/sheet/src/lib.rs @@ -11,6 +11,7 @@ use css::{ atom_hoist::{atom_plan, freeze_atom_plan, is_atom_hoist, is_hoisted_bucket}, file_map::canonical, get_custom_shorthand_names, + property_order::cmp_properties, style_selector::{ AtRule, AtRuleKind, StyleSelector, get_selector_order, global_selector_order, write_at_rule, }, @@ -51,16 +52,16 @@ fn selector_group(selector: Option<&str>) -> (u8, u8) { /// Typography preset declarations come first so a declaration written directly /// on the same selector wins, and each preset stays contiguous so its rules merge. +/// Properties follow `cmp_properties`, so a longhand wins over a shorthand covering it. fn prop_cmp(a: &StyleSheetProperty, b: &StyleSheetProperty) -> std::cmp::Ordering { b.typography.cmp(&a.typography).then_with(|| { if a.typography { a.class_name .cmp(&b.class_name) - .then_with(|| a.property.cmp(&b.property)) + .then_with(|| cmp_properties(&a.property, &b.property)) .then_with(|| a.value.cmp(&b.value)) } else { - a.property - .cmp(&b.property) + cmp_properties(&a.property, &b.property) .then_with(|| a.value.cmp(&b.value)) .then_with(|| a.class_name.cmp(&b.class_name)) } @@ -2017,6 +2018,66 @@ mod tests { assert_debug_snapshot!(sheet.create_css(None, false).split("*/").nth(1).unwrap()); } + #[rstest] + #[case("border-width", "border-top-width")] + #[case("place-items", "align-items")] + #[case("border", "border-top-width")] + #[case("overflow", "overflow-x")] + #[case("padding", "padding-top")] + #[serial] + fn longhand_rule_follows_its_shorthand(#[case] shorthand: &str, #[case] longhand: &str) { + let _state = css::test_state::TestStateGuard::new(); + for selector in [None, Some(StyleSelector::from("hover"))] { + for (first, second) in [(shorthand, longhand), (longhand, shorthand)] { + let mut sheet = StyleSheet::default(); + sheet.add_property("a", first, 0, "1px", selector.as_ref(), None, None); + sheet.add_property("b", second, 0, "2px", selector.as_ref(), None, None); + sheet.add_property("c", first, 1, "1px", selector.as_ref(), Some(1), None); + sheet.add_property("d", second, 1, "2px", selector.as_ref(), Some(1), None); + let css = sheet.create_css(None, false); + let at = |property: &str| css.find(&format!("{{{property}:")).unwrap(); + // Within the default bucket and inside a breakpoint of an order layer. + let (shorthand_at, longhand_at) = (at(shorthand), at(longhand)); + assert!(shorthand_at < longhand_at, "{css}"); + let (shorthand_at, longhand_at) = ( + css.rfind(&format!("{{{shorthand}:")).unwrap(), + css.rfind(&format!("{{{longhand}:")).unwrap(), + ); + assert!(shorthand_at < longhand_at, "{css}"); + } + } + } + + #[rstest] + #[case::stylex( + "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';" + )] + #[serial] + fn extracted_longhands_win_over_shorthands(#[case] code: &str) { + let _state = css::test_state::TestStateGuard::new(); + let output = extract( + "index.tsx", + code, + ExtractOption { + package: "@devup-ui/react".to_string(), + css_dir: "@devup-ui/react".to_string(), + single_css: true, + import_main_css: false, + import_aliases: std::collections::HashMap::new(), + }, + ) + .unwrap(); + let mut sheet = StyleSheet::default(); + sheet.update_styles(&output.styles, "index.tsx", true); + let css = sheet.create_css(None, true); + let at = |property: &str| css.find(&format!("{{{property}:")).unwrap(); + assert!(at("border-width") < at("border-top-width"), "{css}"); + assert!(at("place-items") < at("align-items"), "{css}"); + } + #[test] #[serial] fn test_import_css() { From 404d173480aec1243fbc093e35ec7c3db74ee962 Mon Sep 17 00:00:00 2001 From: owjs3901 Date: Mon, 16 Nov 2026 00:58:01 +0900 Subject: [PATCH 2/4] fix(extractor): let a later shorthand replace the longhands it covers Now that the sheet writes a longhand after every shorthand covering it, `css({ borderTopWidth: 2, borderWidth: 1 })` let the earlier longhand win. A shorthand written later drops the earlier longhand's atom instead, so it wins by construction whatever the sheet order: - `css::property_order::covers` reads the shorthand table transitively. - A style object's declarations (css(), styled objects, nested selectors) and Box attributes drop a longhand a later declaration's shorthand covers. - css() composition drops it when a later part sets the shorthand. Only static, unconditional atoms at the same selector, breakpoint, layer and style order are dropped; conditional or dynamic values keep both, and global rules keep their declarations in the order written. Refs #688 Co-Authored-By: Claude Opus 5.5 --- .../changepack_log_later_shorthand_wins.json | 8 + libs/css/src/property_order.rs | 42 ++++- libs/extractor/src/composition.rs | 15 ++ .../src/composition_shorthand_tests.rs | 162 ++++++++++++++++++ libs/extractor/src/composition_shorthands.rs | 103 +++++++++++ .../extract_style_from_expression.rs | 21 ++- libs/extractor/src/lib.rs | 2 + libs/extractor/src/numeric_context_tests.rs | 4 +- ...__tests__style_results_read_as_values.snap | 13 +- libs/extractor/src/visit.rs | 9 +- libs/sheet/src/lib.rs | 2 +- 11 files changed, 350 insertions(+), 31 deletions(-) create mode 100644 .changepacks/changepack_log_later_shorthand_wins.json create mode 100644 libs/extractor/src/composition_shorthand_tests.rs create mode 100644 libs/extractor/src/composition_shorthands.rs diff --git a/.changepacks/changepack_log_later_shorthand_wins.json b/.changepacks/changepack_log_later_shorthand_wins.json new file mode 100644 index 000000000..cbb220a87 --- /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 written after a longhand it covers now wins, as the later declaration: `css({ borderTopWidth: 2, borderWidth: 1 })` keeps only `border-width`, now that the sheet writes a longhand after its shorthands. The earlier longhand's atom is dropped in a css() object, Box props, styled objects (and their nested selectors) and css() composition, 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..a2c35271b --- /dev/null +++ b/libs/extractor/src/composition_shorthand_tests.rs @@ -0,0 +1,162 @@ +//! A shorthand written 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 +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';"; + +#[rstest] +#[case::css_object( + format!("{CSS} export const a = css({{ borderTopWidth: 2, borderWidth: 1 }});"), + &["border-width-0-4px--255"] +)] +#[case::css_transitive( + format!("{CSS} export const a = css({{ borderTopWidth: 2, border: 'solid' }});"), + &["border-0-solid--255"] +)] +#[case::css_place( + format!("{CSS} export const a = css({{ alignItems: 'start', placeItems: 'center' }});"), + &["place-items-0-center--255"] +)] +#[case::css_style_order( + format!("{CSS} export const a = css({{ borderTopWidth: 2, borderWidth: 1, styleOrder: 3 }});"), + &["border-width-0-4px--3"] +)] +#[case::css_nested( + format!("{CSS} export const a = css({{ _hover: {{ borderTopWidth: 2, 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::box_props( + format!("{BOX} export const a = ;"), + &["border-width-0-4px--255"] +)] +#[case::box_selector( + format!("{BOX} export const a = ;"), + &["border-width-0-4px-_a__c_hover-255"] +)] +#[case::box_spread( + format!("{BOX} export const a = ;"), + &["border-width-0-4px--255"] +)] +#[case::styled_member( + format!("{STYLED} export const A = styled.div({{ borderTopWidth: 2, borderWidth: 1 }});"), + &["border-width-0-4px--255"] +)] +#[case::styled_call( + format!("{STYLED} export const A = styled('div')({{ borderTopWidth: 2, borderWidth: 1 }});"), + &["border-width-0-4px--255"] +)] +#[serial] +fn later_shorthand_drops_the_longhand_it_covers(#[case] code: String, #[case] expected: &[&str]) { + assert_eq!(atoms("a.tsx", &code), expected); +} + +/// The longhand 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_later( + 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..54cd02011 --- /dev/null +++ b/libs/extractor/src/composition_shorthands.rs @@ -0,0 +1,103 @@ +//! A shorthand written after a longhand it covers wins, as the later +//! declaration (#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. +//! +//! 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 (a longhand after its shorthands) 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 of a style object to its first +#[derive(Default)] +pub(crate) struct LaterDeclarations(Vec); + +impl LaterDeclarations { + /// The styles of a declaration written before every one read so far, + /// without the longhands a shorthand among those covers + pub(crate) fn before<'a>( + &mut self, + styles: Vec>, + ) -> Vec> { + let kept: Vec> = styles + .into_iter() + .filter_map(|prop| self.keep(prop)) + .collect(); + for prop in &kept { + self.record(prop); + } + kept + } + + /// `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 styles of a style object's declarations, given in source order, without +/// the longhands a later shorthand covers +pub(crate) fn in_source_order<'a>( + declarations: Vec>>, +) -> Vec> { + let mut later = LaterDeclarations::default(); + let mut kept: Vec>> = declarations + .into_iter() + .rev() + .map(|styles| later.before(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 b75a50661..848a7d68e 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::LaterDeclarations, css_utils::{css_to_style, css_to_style_literal, theme_var_reference}, extract_style::{ extract_dynamic_style::ExtractDynamicStyle, @@ -326,6 +327,9 @@ pub(super) fn extract_projected<'a>( Expression::ObjectExpression(obj) => { flatten_spreads(ast_builder, obj); let mut props_styles: Vec> = vec![]; + // Read from the last declaration, so the ones read so far are + // the later ones + let mut later = LaterDeclarations::default(); let mut tag = None; projection.root(); for idx in (0..obj.properties.len()).rev() { @@ -375,7 +379,7 @@ pub(super) fn extract_projected<'a>( LiteralHandling::ExpandResponsiveThemeToken, prepare, ); - props_styles.extend(styles); + props_styles.extend(later.before(styles)); tag = _tag.or(tag); } } @@ -395,7 +399,7 @@ pub(super) fn extract_projected<'a>( LiteralHandling::ExpandResponsiveThemeToken, prepare, ); - props_styles.extend(styles); + props_styles.extend(later.before(styles)); tag = _tag.or(tag); false } @@ -1067,7 +1071,8 @@ pub(super) fn extract_projected<'a>( } Expression::ObjectExpression(obj) => { flatten_spreads(ast_builder, obj); - let mut props = vec![]; + // Each declaration'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) => { @@ -1082,7 +1087,7 @@ pub(super) fn extract_projected<'a>( let o = match p { ObjectPropertyKind::ObjectProperty(o) => o, ObjectPropertyKind::SpreadProperty(spread) => { - props.extend( + props.push( projection .extract( inputs, @@ -1104,7 +1109,7 @@ pub(super) fn extract_projected<'a>( else { let error = unreadable_key(&o.key, false); projection.record(ast_builder, &error); - props.push(error); + props.push(vec![error]); continue; }; if key_name == "params" { @@ -1115,7 +1120,7 @@ pub(super) fn extract_projected<'a>( o.key.span().start, ) { projection.record(ast_builder, &error); - props.push(error); + props.push(vec![error]); continue; } let mut properties = disassemble_property(&key_name); @@ -1123,7 +1128,7 @@ 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( projection .extract( inputs, @@ -1138,7 +1143,7 @@ pub(super) fn extract_projected<'a>( } } ExtractResult { - styles: props, + styles: crate::composition::shorthands::in_source_order(props), ..ExtractResult::default() } } diff --git a/libs/extractor/src/lib.rs b/libs/extractor/src/lib.rs index 71b38efe2..56f562777 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/numeric_context_tests.rs b/libs/extractor/src/numeric_context_tests.rs index 9fa1de568..2c36de272 100644 --- a/libs/extractor/src/numeric_context_tests.rs +++ b/libs/extractor/src/numeric_context_tests.rs @@ -221,9 +221,9 @@ fn unknown_local_numbers_when_api_has_no_element_remain_located_error() { } #[rstest] -#[case("return
;")] +#[case("return
;")] #[case( - "const inner={padding:3,lineHeight:2,p:3,mx:2,margin:0,vars:{'--raw':3}}; return
;" + "const inner={padding:3,lineHeight:2,p:3,margin:0,mx:2,vars:{'--raw':3}}; return
;" )] #[serial] fn static_numbers_when_css_prop_expands_keep_shorthands_and_unitless_values( 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 0ba740b0e..7dbe6cff8 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 @@ -1,6 +1,5 @@ --- source: libs/extractor/src/lib.rs -assertion_line: 22196 expression: "ToBTreeSet::from(output)" --- ToBTreeSet { @@ -62,16 +61,6 @@ ToBTreeSet { layer: None, }, ), - Static( - ExtractStaticStyle { - property: "animation-name", - value: "a-a", - level: 0, - selector: None, - style_order: None, - layer: None, - }, - ), Static( ExtractStaticStyle { property: "animation-name", @@ -142,5 +131,5 @@ ToBTreeSet { }, ), }, - code: "import \"@devup-ui/react/devup-ui-0.css\";\nimport { forwardRef as __devupForwardRef } from \"react\";\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 = __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\";\nimport { Global } from \"@devup-ui/react/compat\";\nconst fadeIn = \"a-a\";\nconst slide = \"a-b\";\nconst card = \"a-c\";\nexport const a = \"a-d\";\nexport const b = \"a-c a-e\";\nexport const c = \"a-f\";\nexport const d =
;\nexport const E = __devupForwardRef(({ style, className, as: DevupAs = \"div\", forwardedAs, ...rest }, __devupRef) => k[0] !== \"$\" && k !== \"theme\"))} ref={__devupRef} as={forwardedAs} className={className ? `a--a a-h ${className}` : \"a--a a-h\"} style={style} />);\n;\nexport const g = ;\n", } diff --git a/libs/extractor/src/visit.rs b/libs/extractor/src/visit.rs index 4adfbc731..e500f3593 100644 --- a/libs/extractor/src/visit.rs +++ b/libs/extractor/src/visit.rs @@ -5402,6 +5402,9 @@ 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 + let mut later = crate::composition::shorthands::LaterDeclarations::default(); let mut parsed_style_order = ParsedStyleOrder::None; let mut style_vars = None; let mut props = None; @@ -5470,7 +5473,7 @@ impl<'a> VisitMut<'a> for DevupVisitor<'a> { &disassembled, at, ); - props_styles.extend(styles.into_iter().rev()); + props_styles.extend(later.before(styles).into_iter().rev()); tag_name = tag.unwrap_or(tag_name); } duplicate_set.insert(disassembled); @@ -5492,7 +5495,7 @@ impl<'a> VisitMut<'a> for DevupVisitor<'a> { &None, LiteralHandling::ExpandResponsiveThemeToken, ); - props_styles.extend(styles.into_iter().rev()); + props_styles.extend(later.before(styles).into_iter().rev()); if element_props::has_runtime_props(&spread.argument) { attrs.insert(i, attr); } @@ -5540,7 +5543,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.before(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 20add06d6..2ceed85b6 100644 --- a/libs/sheet/src/lib.rs +++ b/libs/sheet/src/lib.rs @@ -2053,7 +2053,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) { From 79ea8c97707a894e9ea48fb2648f3085ff035218 Mon Sep 17 00:00:00 2001 From: owjs3901 Date: Tue, 17 Nov 2026 11:28:28 +0900 Subject: [PATCH 3/4] fix(extractor): keep a longhand JSX attribute its sibling shorthand covers The lint sorts JSX attributes by name (perfectionist/sort-jsx-props), so their order is not the order the author chose: `backgroundClip` always comes before `bg`. Treating it as written order dropped the `background-clip: text` atom of ``, which broke the gradient text of the landing DevupUICard and its mobile benchmark screenshot. Attributes between two spreads now replace none of each other's longhands, and the sheet order (a longhand after its shorthands) decides as in #974. A spread keeps its place: a shorthand in a later spread or in the attributes after a spread still replaces an earlier longhand. Co-Authored-By: Claude Opus 5.5 --- .../changepack_log_later_shorthand_wins.json | 2 +- .../src/composition_shorthand_tests.rs | 28 +++++++-- libs/extractor/src/composition_shorthands.rs | 59 +++++++++++++++++-- libs/extractor/src/visit.rs | 12 ++-- libs/sheet/src/lib.rs | 2 +- 5 files changed, 87 insertions(+), 16 deletions(-) diff --git a/.changepacks/changepack_log_later_shorthand_wins.json b/.changepacks/changepack_log_later_shorthand_wins.json index cbb220a87..1fcde1599 100644 --- a/.changepacks/changepack_log_later_shorthand_wins.json +++ b/.changepacks/changepack_log_later_shorthand_wins.json @@ -3,6 +3,6 @@ "bindings/devup-ui-wasm/package.json": "Patch", "bindings/devup-ui-binding/package.json": "Patch" }, - "note": "A shorthand written after a longhand it covers now wins, as the later declaration: `css({ borderTopWidth: 2, borderWidth: 1 })` keeps only `border-width`, now that the sheet writes a longhand after its shorthands. The earlier longhand's atom is dropped in a css() object, Box props, styled objects (and their nested selectors) and css() composition, 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", + "note": "A shorthand written after a longhand it covers now wins, as the later declaration: `css({ borderTopWidth: 2, borderWidth: 1 })` keeps only `border-width`, now that the sheet writes a longhand after its shorthands. The earlier longhand's atom is dropped in a css() object, styled objects (and their nested selectors), css() composition and Box props split by a spread, 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. Box props between two spreads have no written order, as the lint sorts them by name, so there the longhand still wins (`` keeps its gradient text). globalCss keeps every declaration in the order written. No new build errors", "date": "2026-11-16T00:00:00.000Z" } diff --git a/libs/extractor/src/composition_shorthand_tests.rs b/libs/extractor/src/composition_shorthand_tests.rs index a2c35271b..79bb10819 100644 --- a/libs/extractor/src/composition_shorthand_tests.rs +++ b/libs/extractor/src/composition_shorthand_tests.rs @@ -1,7 +1,9 @@ //! A shorthand written 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 +//! unconditional at the same selector, breakpoint, layer and style order. +//! JSX attributes between two spreads have no written order (the lint sorts +//! them by name), so only a spread orders them use crate::{ExtractOption, extract}; use css::{class_map::reset_class_map, file_map::reset_file_map}; use rstest::rstest; @@ -55,10 +57,6 @@ const STYLED: &str = "import { styled } from '@devup-ui/react';"; 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::box_props( - format!("{BOX} export const a = ;"), - &["border-width-0-4px--255"] -)] #[case::box_selector( format!("{BOX} export const a = ;"), &["border-width-0-4px-_a__c_hover-255"] @@ -67,6 +65,14 @@ const STYLED: &str = "import { styled } from '@devup-ui/react';"; 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"] +)] #[case::styled_member( format!("{STYLED} export const A = styled.div({{ borderTopWidth: 2, borderWidth: 1 }});"), &["border-width-0-4px--255"] @@ -96,6 +102,18 @@ fn later_shorthand_drops_the_longhand_it_covers(#[case] code: String, #[case] ex format!("{CSS} export const a = css({{ borderTopWidth: [2, 3], borderWidth: 1 }});"), &["border-top-width-1-12px--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::unrelated( format!("{CSS} export const a = css({{ paddingTop: 2, margin: 1 }});"), &["margin-0-4px--255", "padding-top-0-8px--255"] diff --git a/libs/extractor/src/composition_shorthands.rs b/libs/extractor/src/composition_shorthands.rs index 54cd02011..1a2393128 100644 --- a/libs/extractor/src/composition_shorthands.rs +++ b/libs/extractor/src/composition_shorthands.rs @@ -46,16 +46,21 @@ impl LaterDeclarations { &mut self, styles: Vec>, ) -> Vec> { - let kept: Vec> = styles - .into_iter() - .filter_map(|prop| self.keep(prop)) - .collect(); + let kept = self.without_covered(styles); for prop in &kept { self.record(prop); } kept } + /// `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> { @@ -87,6 +92,52 @@ impl LaterDeclarations { } } +/// The static atoms of an element's attributes read so far, read from the last +/// attribute to its first. +/// +/// The attributes between two spreads have no written order: the lint sorts +/// them by name (`perfectionist/sort-jsx-props`), so `backgroundClip` always +/// comes before `bg`. A shorthand attribute then replaces no longhand +/// attribute of its run, and the stylesheet's order (a longhand after its +/// shorthands) decides between them. A spread keeps its place among them, so a +/// shorthand in a later run or spread still replaces an earlier longhand +#[derive(Default)] +pub(crate) struct LaterAttributes { + /// The atoms of the runs and spreads after the run being read + later: LaterDeclarations, + /// The atoms of the run being read + run: LaterDeclarations, +} + +impl LaterAttributes { + /// The styles of an attribute written before every one read so far, + /// without the longhands a shorthand of a later run or spread covers + pub(crate) fn attribute<'a>( + &mut self, + styles: Vec>, + ) -> Vec> { + 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 read so far, + /// without the longhands a later shorthand covers + pub(crate) fn spread<'a>( + &mut self, + styles: Vec>, + ) -> Vec> { + self.later.before(styles) + } +} + /// The styles of a style object's declarations, given in source order, without /// the longhands a later shorthand covers pub(crate) fn in_source_order<'a>( diff --git a/libs/extractor/src/visit.rs b/libs/extractor/src/visit.rs index e500f3593..5b5966510 100644 --- a/libs/extractor/src/visit.rs +++ b/libs/extractor/src/visit.rs @@ -5403,8 +5403,9 @@ 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 - let mut later = crate::composition::shorthands::LaterDeclarations::default(); + // the later ones; only a spread orders them, as the lint sorts the + // rest by name + let mut later = crate::composition::shorthands::LaterAttributes::default(); let mut parsed_style_order = ParsedStyleOrder::None; let mut style_vars = None; let mut props = None; @@ -5473,13 +5474,14 @@ impl<'a> VisitMut<'a> for DevupVisitor<'a> { &disassembled, at, ); - props_styles.extend(later.before(styles).into_iter().rev()); + props_styles.extend(later.attribute(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( @@ -5495,7 +5497,7 @@ impl<'a> VisitMut<'a> for DevupVisitor<'a> { &None, LiteralHandling::ExpandResponsiveThemeToken, ); - props_styles.extend(later.before(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); } @@ -5543,7 +5545,7 @@ impl<'a> VisitMut<'a> for DevupVisitor<'a> { } style_vars = style_vars.or(extracted.style_vars); props = props.or(extracted.props); - props_styles.extend(later.before(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 a1f988c61..9cd383120 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) { From 84c500535c52b8647a6edd3f560e31134c24558e Mon Sep 17 00:00:00 2001 From: owjs3901 Date: Tue, 17 Nov 2026 17:28:02 +0900 Subject: [PATCH 4/4] fix(extractor): drop a covered longhand only across a boundary, not within one level In css({ borderTopWidth: 2, borderWidth: 1 }) both keys sit in one object literal, and key order there is no "later wins" signal, as for JSX props between two spreads. Both atoms now stay and the sheet order from #974 (a longhand after its shorthands) lets border-top-width win. This applies to css() and styled objects and to each nested selector or breakpoint object. A later shorthand still drops the earlier longhand it covers across a boundary: css() arguments, a spread among JSX props or object keys (a prop after a spread, a later spread), and css()/styled composition. - composition::shorthands::LaterRuns (was LaterAttributes) now reads both JSX attributes and object properties. Members of one run never drop each other; a spread ends the run. - flatten_spreads keeps where each inlined property came from, so a literal or local-constant object spread stays a boundary after it is inlined. - css() merges literal arguments into one object; StyleInputs now carries the argument spans, so properties from different arguments run apart. - The test_style_results_read_as_values snapshot is back to main for css({ animationName, animation }) and still drops animation-name in . The numeric_context_tests case is back to its original key order. Refs #688 Co-Authored-By: Claude Opus 5.5 --- .../changepack_log_later_shorthand_wins.json | 2 +- .../src/composition_shorthand_tests.rs | 155 +++++++++++++----- libs/extractor/src/composition_shorthands.rs | 110 ++++++++----- .../extract_style_from_expression.rs | 93 ++++++++--- libs/extractor/src/extractor/style_inputs.rs | 23 ++- libs/extractor/src/numeric_context_tests.rs | 4 +- ...__tests__style_results_read_as_values.snap | 12 +- libs/extractor/src/visit.rs | 11 +- 8 files changed, 290 insertions(+), 120 deletions(-) diff --git a/.changepacks/changepack_log_later_shorthand_wins.json b/.changepacks/changepack_log_later_shorthand_wins.json index 1fcde1599..c21e9b3c6 100644 --- a/.changepacks/changepack_log_later_shorthand_wins.json +++ b/.changepacks/changepack_log_later_shorthand_wins.json @@ -3,6 +3,6 @@ "bindings/devup-ui-wasm/package.json": "Patch", "bindings/devup-ui-binding/package.json": "Patch" }, - "note": "A shorthand written after a longhand it covers now wins, as the later declaration: `css({ borderTopWidth: 2, borderWidth: 1 })` keeps only `border-width`, now that the sheet writes a longhand after its shorthands. The earlier longhand's atom is dropped in a css() object, styled objects (and their nested selectors), css() composition and Box props split by a spread, 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. Box props between two spreads have no written order, as the lint sorts them by name, so there the longhand still wins (`` keeps its gradient text). globalCss keeps every declaration in the order written. No new build errors", + "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/extractor/src/composition_shorthand_tests.rs b/libs/extractor/src/composition_shorthand_tests.rs index 79bb10819..b1d2411ef 100644 --- a/libs/extractor/src/composition_shorthand_tests.rs +++ b/libs/extractor/src/composition_shorthand_tests.rs @@ -1,9 +1,11 @@ -//! A shorthand written 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. -//! JSX attributes between two spreads have no written order (the lint sorts -//! them by name), so only a spread orders them +//! 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; @@ -32,35 +34,48 @@ 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_object( - format!("{CSS} export const a = css({{ borderTopWidth: 2, borderWidth: 1 }});"), +#[case::css_arguments( + format!("{CSS} export const a = css({{ borderTopWidth: 2 }}, {{ borderWidth: 1 }});"), &["border-width-0-4px--255"] )] -#[case::css_transitive( - format!("{CSS} export const a = css({{ borderTopWidth: 2, border: 'solid' }});"), +#[case::css_arguments_transitive( + format!("{CSS} export const a = css({{ borderTopWidth: 2 }}, {{ border: 'solid' }});"), &["border-0-solid--255"] )] -#[case::css_place( - format!("{CSS} export const a = css({{ alignItems: 'start', placeItems: 'center' }});"), +#[case::css_arguments_place( + format!("{CSS} export const a = css({{ alignItems: 'start' }}, {{ placeItems: 'center' }});"), &["place-items-0-center--255"] )] -#[case::css_style_order( - format!("{CSS} export const a = css({{ borderTopWidth: 2, borderWidth: 1, styleOrder: 3 }});"), - &["border-width-0-4px--3"] -)] -#[case::css_nested( - format!("{CSS} export const a = css({{ _hover: {{ borderTopWidth: 2, borderWidth: 1 }} }});"), +#[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::box_selector( - format!("{BOX} export const a = ;"), +#[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"] @@ -73,35 +88,58 @@ const STYLED: &str = "import { styled } from '@devup-ui/react';"; 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-width-0-4px--255"] + &["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-width-0-4px--255"] + &["border-top-width-0-8px--255", "border-width-0-4px--255"] )] -#[serial] -fn later_shorthand_drops_the_longhand_it_covers(#[case] code: String, #[case] expected: &[&str]) { - assert_eq!(atoms("a.tsx", &code), expected); -} - -/// The longhand 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_later( 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::box_props( format!("{BOX} export const a = ;"), &["border-top-width-0-8px--255", "border-width-0-4px--255"] @@ -114,16 +152,49 @@ fn later_shorthand_drops_the_longhand_it_covers(#[case] code: String, #[case] ex 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 }});"), + 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) => ;"), + 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) => ;"), + 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( diff --git a/libs/extractor/src/composition_shorthands.rs b/libs/extractor/src/composition_shorthands.rs index 1a2393128..94228b5af 100644 --- a/libs/extractor/src/composition_shorthands.rs +++ b/libs/extractor/src/composition_shorthands.rs @@ -1,13 +1,20 @@ -//! A shorthand written after a longhand it covers wins, as the later -//! declaration (#688), whatever order the stylesheet gives the two: the sheet +//! 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 (a longhand after its shorthands) decides between -//! them. +//! the stylesheet's order decides between them. use crate::extract_style::extract_static_style::ExtractStaticStyle; use crate::{ExtractStyleProp, ExtractStyleValue}; @@ -35,24 +42,11 @@ const fn static_atom<'p>(prop: &'p ExtractStyleProp<'_>) -> Option<&'p ExtractSt } /// The static atoms of the declarations read so far, read from the last -/// declaration of a style object to its first +/// declaration to its first #[derive(Default)] -pub(crate) struct LaterDeclarations(Vec); +struct LaterDeclarations(Vec); impl LaterDeclarations { - /// The styles of a declaration written before every one read so far, - /// without the longhands a shorthand among those covers - pub(crate) fn before<'a>( - &mut self, - styles: Vec>, - ) -> Vec> { - let kept = self.without_covered(styles); - for prop in &kept { - self.record(prop); - } - kept - } - /// `styles` without the longhands a shorthand read so far covers fn without_covered<'a>(&self, styles: Vec>) -> Vec> { styles @@ -92,30 +86,46 @@ impl LaterDeclarations { } } -/// The static atoms of an element's attributes read so far, read from the last -/// attribute to its first. +/// The static atoms of the JSX attributes or object properties read so far, +/// read from the last to the first. /// -/// The attributes between two spreads have no written order: the lint sorts -/// them by name (`perfectionist/sort-jsx-props`), so `backgroundClip` always -/// comes before `bg`. A shorthand attribute then replaces no longhand -/// attribute of its run, and the stylesheet's order (a longhand after its -/// shorthands) decides between them. A spread keeps its place among them, so a -/// shorthand in a later run or spread still replaces an earlier longhand +/// 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 LaterAttributes { +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, } -impl LaterAttributes { - /// The styles of an attribute written before every one read so far, - /// without the longhands a shorthand of a later run or spread covers - pub(crate) fn attribute<'a>( +/// 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); @@ -128,26 +138,40 @@ impl LaterAttributes { self.later.0.append(&mut self.run.0); } - /// The styles of a spread written before every attribute read so far, - /// without the longhands a later shorthand covers + /// 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.later.before(styles) + self.end_run(); + let kept = self.later.without_covered(styles); + for prop in &kept { + self.later.record(prop); + } + kept } } -/// The styles of a style object's declarations, given in source order, without -/// the longhands a later shorthand covers -pub(crate) fn in_source_order<'a>( - declarations: Vec>>, -) -> Vec> { - let mut later = LaterDeclarations::default(); - let mut kept: Vec>> = declarations +/// 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(|styles| later.before(styles)) + .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 28f81e85f..d4d352765 100644 --- a/libs/extractor/src/extractor/extract_style_from_expression.rs +++ b/libs/extractor/src/extractor/extract_style_from_expression.rs @@ -1,7 +1,7 @@ use super::style_inputs::StyleInputs; use crate::{ ExtractStyleProp, - composition::shorthands::LaterDeclarations, + 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, @@ -87,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> { @@ -326,11 +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 declaration, so the ones read so far are - // the later ones - let mut later = LaterDeclarations::default(); + // 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() { @@ -381,7 +410,10 @@ pub(super) fn extract_projected<'a>( LiteralHandling::ExpandResponsiveThemeToken, prepare, ); - props_styles.extend(later.before(styles)); + props_styles.extend(later.member( + (inputs.argument_of(prop.span), runs[idx]), + styles, + )); tag = _tag.or(tag); } } @@ -401,7 +433,7 @@ pub(super) fn extract_projected<'a>( LiteralHandling::ExpandResponsiveThemeToken, prepare, ); - props_styles.extend(later.before(styles)); + props_styles.extend(later.spread(styles)); tag = _tag.or(tag); false } @@ -1068,9 +1100,9 @@ pub(super) fn extract_projected<'a>( } } Expression::ObjectExpression(obj) => { - flatten_spreads(ast_builder, obj); - // Each declaration's styles, in source order - let mut props: Vec>> = 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) => { @@ -1081,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.push( + props.push(Part::Spread( projection .extract( inputs, @@ -1096,7 +1128,7 @@ pub(super) fn extract_projected<'a>( prepare, ) .styles, - ); + )); continue; } }; @@ -1107,7 +1139,10 @@ pub(super) fn extract_projected<'a>( else { let error = unreadable_key(&o.key, false); projection.record(ast_builder, &error); - props.push(vec![error]); + props.push(Part::Property( + (inputs.argument_of(o.span), run), + vec![error], + )); continue; }; if key_name == "params" { @@ -1118,7 +1153,10 @@ pub(super) fn extract_projected<'a>( o.key.span().start, ) { projection.record(ast_builder, &error); - props.push(vec![error]); + props.push(Part::Property( + (inputs.argument_of(o.span), run), + vec![error], + )); continue; } let mut properties = style_key_properties(&key_name, &o.value); @@ -1126,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.push( + props.push(Part::Property( + (inputs.argument_of(o.span), run), projection .extract( inputs, @@ -1137,11 +1176,11 @@ pub(super) fn extract_projected<'a>( prepare, ) .styles, - ); + )); } } ExtractResult { - styles: crate::composition::shorthands::in_source_order(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/numeric_context_tests.rs b/libs/extractor/src/numeric_context_tests.rs index 2c36de272..9fa1de568 100644 --- a/libs/extractor/src/numeric_context_tests.rs +++ b/libs/extractor/src/numeric_context_tests.rs @@ -221,9 +221,9 @@ fn unknown_local_numbers_when_api_has_no_element_remain_located_error() { } #[rstest] -#[case("return
;")] +#[case("return
;")] #[case( - "const inner={padding:3,lineHeight:2,p:3,margin:0,mx:2,vars:{'--raw':3}}; return
;" + "const inner={padding:3,lineHeight:2,p:3,mx:2,margin:0,vars:{'--raw':3}}; return
;" )] #[serial] fn static_numbers_when_css_prop_expands_keep_shorthands_and_unitless_values( 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 7a3e75fd8..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 @@ -61,6 +61,16 @@ ToBTreeSet { layer: None, }, ), + Static( + ExtractStaticStyle { + property: "animation-name", + value: "a-a", + level: 0, + selector: None, + style_order: None, + layer: None, + }, + ), Static( ExtractStaticStyle { property: "animation-name", @@ -131,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\";\nexport const b = \"a-c a-e\";\nexport const c = \"a-f\";\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-h ${className}` : \"a--a a-h\"} 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 73aa13a7b..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 @@ -5511,7 +5515,7 @@ impl<'a> VisitMut<'a> for DevupVisitor<'a> { // 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::LaterAttributes::default(); + let mut later = crate::composition::shorthands::LaterRuns::default(); let mut parsed_style_order = ParsedStyleOrder::None; let mut style_vars = None; let mut props = None; @@ -5580,7 +5584,8 @@ impl<'a> VisitMut<'a> for DevupVisitor<'a> { &disassembled, at, ); - props_styles.extend(later.attribute(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);