From d723316ef62c15dd5707359ac88d2b552f2017f3 Mon Sep 17 00:00:00 2001 From: owjs3901 Date: Mon, 16 Nov 2026 03:36:20 +0900 Subject: [PATCH] feat(stylex): read stylex.create() under StyleX's styleResolution Every plugin takes `stylex: { styleResolution }`, StyleX's babel plugin option, validated before setup (`StylexConfigError`) and handed to the engine through the new `setStylexStyleResolution()` binding export. - `property-specificity` (default) expands nothing: the sheet writes a longhand after its shorthands (#974). - `application-order` gives a static `create()` key the `null` resets StyleX's table lists, and reads its aliases, so the key applied last wins in `stylex.props()` and within a namespace. - `legacy-expand-shorthands` splits a shorthand into its longhands as StyleX's table does, `!important`, `containIntrinsicSize` and `listStyle` included. Both tables are generated from @stylexjs/babel-plugin 0.19.1. A later key of a static namespace replaces an earlier one of the same name. Dynamic namespaces and `float`/`clear` logical values stay as written. Devup UI's own APIs ignore the option. Refs #690 Co-Authored-By: Claude Opus 5.5 --- ...hangepack_log_stylex_style_resolution.json | 14 + .../(detail)/docs/migration/stylex/page.mdx | 30 ++ bindings/argument-validation.cjs | 1 + bindings/devup-ui-binding/adapter.cjs | 2 + bindings/devup-ui-binding/index.d.cts | 7 + bindings/devup-ui-binding/index.mjs | 1 + bindings/devup-ui-binding/src/lib.rs | 5 + bindings/devup-ui-wasm/script.js | 6 +- bindings/devup-ui-wasm/src/lib.rs | 33 +++ e2e/binding/corpus/boundary.mjs | 17 ++ e2e/binding/host.mjs | 6 +- e2e/binding/validation-cases.mjs | 9 +- libs/binding/src/lib.rs | 1 + libs/css/src/lib.rs | 1 + libs/css/src/style_resolution.rs | 109 +++++++ libs/css/src/test_state.rs | 8 +- libs/css/src/test_state/tests.rs | 9 + .../extractor/extract_style_from_stylex.rs | 177 +++++++++--- libs/extractor/src/lib.rs | 3 + libs/extractor/src/stylex_resolution.rs | 238 +++++++++++++++ .../src/stylex_resolution_extract_tests.rs | 225 +++++++++++++++ .../extractor/src/stylex_resolution_tables.rs | 272 ++++++++++++++++++ libs/extractor/src/stylex_resolution_tests.rs | 228 +++++++++++++++ .../bun-plugin/src/__tests__/plugin.test.ts | 29 ++ packages/bun-plugin/src/plugin.ts | 10 +- .../next-plugin/src/__tests__/plugin.test.ts | 28 ++ packages/next-plugin/src/plugin.ts | 5 + .../src/__tests__/compiler-types.test.ts | 2 +- .../src/__tests__/stylex-options.test.ts | 52 ++++ .../src/__tests__/wasm-abi.test.ts | 18 ++ packages/plugin-utils/src/index.ts | 7 + packages/plugin-utils/src/shared.ts | 3 + packages/plugin-utils/src/stylex-options.ts | 52 ++++ .../src/__tests__/plugin.test.ts | 18 ++ packages/rsbuild-plugin/src/plugin.ts | 6 +- .../vite-plugin/src/__tests__/plugin.test.ts | 23 ++ packages/vite-plugin/src/plugin.ts | 6 +- .../src/__tests__/plugin.test.ts | 32 +++ packages/webpack-plugin/src/plugin.ts | 9 +- 39 files changed, 1654 insertions(+), 48 deletions(-) create mode 100644 .changepacks/changepack_log_stylex_style_resolution.json create mode 100644 libs/css/src/style_resolution.rs create mode 100644 libs/extractor/src/stylex_resolution.rs create mode 100644 libs/extractor/src/stylex_resolution_extract_tests.rs create mode 100644 libs/extractor/src/stylex_resolution_tables.rs create mode 100644 libs/extractor/src/stylex_resolution_tests.rs create mode 100644 packages/plugin-utils/src/__tests__/stylex-options.test.ts create mode 100644 packages/plugin-utils/src/stylex-options.ts diff --git a/.changepacks/changepack_log_stylex_style_resolution.json b/.changepacks/changepack_log_stylex_style_resolution.json new file mode 100644 index 000000000..b808f358c --- /dev/null +++ b/.changepacks/changepack_log_stylex_style_resolution.json @@ -0,0 +1,14 @@ +{ + "changes": { + "bindings/devup-ui-wasm/package.json": "Patch", + "bindings/devup-ui-binding/package.json": "Patch", + "packages/plugin-utils/package.json": "Patch", + "packages/vite-plugin/package.json": "Patch", + "packages/rsbuild-plugin/package.json": "Patch", + "packages/webpack-plugin/package.json": "Patch", + "packages/next-plugin/package.json": "Patch", + "packages/bun-plugin/package.json": "Patch" + }, + "note": "Every plugin takes `stylex: { styleResolution }`, StyleX's babel plugin option of the same name, and the engines take it through the new `setStylexStyleResolution()`. `'property-specificity'` stays the default. `'application-order'` gives a static `stylex.create()` key the `null` resets StyleX's table lists for the longhands it covers (and reads its aliases, `marginStart` as `margin-inline-start`), so the key applied last wins in `stylex.props()` and within a namespace. `'legacy-expand-shorthands'` splits a shorthand into its longhands at build time as StyleX's table does (`padding: '1px 2px'` into `padding-top`, `padding-inline-end`, `padding-bottom`, `padding-inline-start`). A later key of a static namespace now replaces an earlier one of the same name. New build errors under the two non-default policies only: a shorthand given `firstThatWorks()` fallbacks, `all` under `application-order` and a `listStyle` StyleX cannot sort under `legacy-expand-shorthands`; an unknown `styleResolution` is a configuration error (`StylexConfigError`). Devup UI's own APIs ignore the option", + "date": "2026-11-16T00:00:00.000Z" +} diff --git a/apps/landing/src/app/(detail)/docs/migration/stylex/page.mdx b/apps/landing/src/app/(detail)/docs/migration/stylex/page.mdx index dda8454c7..5ee720774 100644 --- a/apps/landing/src/app/(detail)/docs/migration/stylex/page.mdx +++ b/apps/landing/src/app/(detail)/docs/migration/stylex/page.mdx @@ -46,6 +46,36 @@ stylex.props(on && styles.active) // conditional stylex.props(styles?.base) // optional chaining ``` +## Shorthands and `styleResolution` + +StyleX's babel plugin decides between a shorthand and the longhands it covers with its `styleResolution` option. Pass the same option to the Devup UI plugin: + +```ts +// vite.config.ts (every plugin takes the same option) +DevupUI({ stylex: { styleResolution: 'application-order' } }) +``` + +| `styleResolution` | What wins | +| ---------------------------------- | ------------------------------------------------------------------------ | +| `'property-specificity'` (default) | A longhand beats a shorthand, whatever order they apply in | +| `'application-order'` | The property applied last, shorthand or not | +| `'legacy-expand-shorthands'` | No shorthand is left: each one is split into its longhands at build time | + +```tsx +const styles = stylex.create({ + top: { paddingTop: '1px' }, + pad: { padding: '2px' }, +}) + +const el =
+``` + +- `'property-specificity'` keeps both classes and writes `padding-top` after `padding` in the stylesheet, so `padding-top: 1px` wins. +- `'application-order'` gives `padding` `null` resets for the longhands it covers, as StyleX does, so the later `padding` removes `padding-top`. In the other order both stay and `padding-top` wins. +- `'legacy-expand-shorthands'` turns `padding: '1px 2px'` into `padding-top`, `padding-inline-end`, `padding-bottom` and `padding-inline-start`, which merge key by key like any longhand. + +The two non-default policies read StyleX's own shorthand tables, including its aliases (`marginStart` is `margin-inline-start`, `blockSize` is `height`), and apply to static `create()` namespaces only. A shorthand there cannot take `firstThatWorks()` fallbacks, and `application-order` rejects `all`, as StyleX does; both are build errors naming the key. Dynamic (arrow-function) namespaces keep their shorthands as written, and `float`/`clear` keep logical values such as `inline-start` as written, because StyleX's polyfill for them relies on its own runtime variables. An unknown `styleResolution` is a configuration error when the plugin is created. Devup UI's own APIs (`css()`, `styled`, `Box` props) ignore the option: there a shorthand written after a longhand wins. + ## Variables and themes ```tsx diff --git a/bindings/argument-validation.cjs b/bindings/argument-validation.cjs index 66e41fb08..8ca96408d 100644 --- a/bindings/argument-validation.cjs +++ b/bindings/argument-validation.cjs @@ -23,6 +23,7 @@ module.exports = function createBoundary() { setDebug: 'debug:b', setModuleResolver: 'resolver:f', setPrefix: 'prefix:p', + setStylexStyleResolution: 'resolution:p', } const labels = { s: 'a string', diff --git a/bindings/devup-ui-binding/adapter.cjs b/bindings/devup-ui-binding/adapter.cjs index 77bf341e9..62b06c750 100644 --- a/bindings/devup-ui-binding/adapter.cjs +++ b/bindings/devup-ui-binding/adapter.cjs @@ -111,5 +111,7 @@ exports.createBinding = function createBinding(raw) { setDebug: (value) => raw.setDebug(value), setModuleResolver, setPrefix: (value) => raw.setPrefix(value == null ? undefined : value), + setStylexStyleResolution: (value) => + raw.setStylexStyleResolution(value == null ? undefined : value), }) } diff --git a/bindings/devup-ui-binding/index.d.cts b/bindings/devup-ui-binding/index.d.cts index cd21d7210..5a1d0e67c 100644 --- a/bindings/devup-ui-binding/index.d.cts +++ b/bindings/devup-ui-binding/index.d.cts @@ -87,3 +87,10 @@ export function setModuleResolver( | null, ): void export function setPrefix(prefix?: string | null): void +export function setStylexStyleResolution( + value?: + | 'property-specificity' + | 'application-order' + | 'legacy-expand-shorthands' + | null, +): void diff --git a/bindings/devup-ui-binding/index.mjs b/bindings/devup-ui-binding/index.mjs index c9f981b23..1f71404f0 100644 --- a/bindings/devup-ui-binding/index.mjs +++ b/bindings/devup-ui-binding/index.mjs @@ -30,4 +30,5 @@ export const { setDebug, setModuleResolver, setPrefix, + setStylexStyleResolution, } = binding diff --git a/bindings/devup-ui-binding/src/lib.rs b/bindings/devup-ui-binding/src/lib.rs index 205575d4c..842dfa68d 100644 --- a/bindings/devup-ui-binding/src/lib.rs +++ b/bindings/devup-ui-binding/src/lib.rs @@ -190,6 +190,11 @@ pub fn get_prefix() -> Either { pub fn set_prefix(value: Option) { core::set_prefix(value); } +/// Install the named `StyleX` `styleResolution`, the default when nullish; an unknown name fails. +#[napi] +pub fn set_stylex_style_resolution(env: Env, value: Option) -> Result<()> { + core::set_stylex_style_resolution(value.as_deref()).map_err(|error| binding_error(env, error)) +} /// Return the default theme as a string or undefined. #[napi] pub fn get_default_theme() -> Either { diff --git a/bindings/devup-ui-wasm/script.js b/bindings/devup-ui-wasm/script.js index 279a62ba6..e25c5da00 100644 --- a/bindings/devup-ui-wasm/script.js +++ b/bindings/devup-ui-wasm/script.js @@ -39,9 +39,9 @@ for (const operation of ['begin', 'end', 'error', 'fail']) ) assert.equal([...source.matchAll(/__devupBoundary/g)].length, 4) const names = [...source.matchAll(/^exports\.(\w+) = \1;/gm)] -assert.equal(names.length, 29) -assert.equal(new Set(names.map((match) => match[1])).size, 29) -assert.equal([...source.matchAll(/^exports\./gm)].length, 29) +assert.equal(names.length, 30) +assert.equal(new Set(names.map((match) => match[1])).size, 30) +assert.equal([...source.matchAll(/^exports\./gm)].length, 30) assert.equal(source.includes('module.exports'), false) for (const name of ['codeExtract', 'codeExtractWithoutSourceMap']) { const signatures = [ diff --git a/bindings/devup-ui-wasm/src/lib.rs b/bindings/devup-ui-wasm/src/lib.rs index 6c2e7ed92..a0a2c25e7 100644 --- a/bindings/devup-ui-wasm/src/lib.rs +++ b/bindings/devup-ui-wasm/src/lib.rs @@ -197,6 +197,19 @@ pub fn set_prefix(prefix: Option) { binding_core::set_prefix(prefix); } +/// Install the named `StyleX` `styleResolution` (testable without `JsValue`) +pub fn set_stylex_style_resolution_internal(value: Option<&str>) -> Result<(), String> { + binding_core::set_stylex_style_resolution(value) +} + +/// Read `stylex.create()` under the `StyleX` `styleResolution` `value` names, +/// the default when nullish; an unknown name fails +#[wasm_bindgen(js_name = "setStylexStyleResolution")] +#[cfg(not(tarpaulin_include))] +pub fn set_stylex_style_resolution(value: Option) -> Result<(), JsValue> { + set_stylex_style_resolution_internal(value.as_deref()).map_err(js_error) +} + #[wasm_bindgen(js_name = "getPrefix")] #[must_use] pub fn get_prefix() -> Option { @@ -1919,4 +1932,24 @@ mod tests { ); register_shorthands_internal(BTreeMap::new()).unwrap(); } + + #[test] + #[serial] + fn test_set_stylex_style_resolution_internal() { + use css::style_resolution::{StyleResolution, style_resolution}; + let _state = TestStateGuard::new(); + assert_eq!( + set_stylex_style_resolution_internal(Some("application-order")), + Ok(()) + ); + assert_eq!(style_resolution(), StyleResolution::ApplicationOrder); + assert!( + set_stylex_style_resolution_internal(Some("nope")) + .unwrap_err() + .contains("stylex.styleResolution") + ); + assert_eq!(style_resolution(), StyleResolution::ApplicationOrder); + assert_eq!(set_stylex_style_resolution_internal(None), Ok(())); + assert_eq!(style_resolution(), StyleResolution::PropertySpecificity); + } } diff --git a/e2e/binding/corpus/boundary.mjs b/e2e/binding/corpus/boundary.mjs index c7dd0a5a6..6d3bddbff 100644 --- a/e2e/binding/corpus/boundary.mjs +++ b/e2e/binding/corpus/boundary.mjs @@ -201,6 +201,23 @@ add('prefix-valid-and-malformed-boolean-strict', (h) => { } h.call('setPrefix') }) +add('stylex-style-resolution-valid-unknown-and-malformed', (h) => { + const stylex = `import * as stylex from '@stylexjs/stylex' +const s = stylex.create({ top: { paddingTop: '1px' }, pad: { padding: '1px 2px' } }) +export const a = stylex.props(s.top, s.pad)` + for (const value of [ + 'application-order', + 'legacy-expand-shorthands', + 'last-wins', + null, + undefined, + false, + ]) { + h.call('setStylexStyleResolution', value) + h.extract(stylex) + } + h.call('setStylexStyleResolution') +}) export const boundary = cases export function capturePatched(patches, action) { diff --git a/e2e/binding/host.mjs b/e2e/binding/host.mjs index 12046f85a..05c6b6827 100644 --- a/e2e/binding/host.mjs +++ b/e2e/binding/host.mjs @@ -68,7 +68,7 @@ save('provenance.json', { scenarios: corpus.map((c) => c.name), }) const names = - 'Output codeExtract codeExtractWithoutSourceMap exportCanonicalMap exportClassMap exportFileMap exportSheet getCss getDefaultTheme getPrefix getThemeInterface getUnreservedClassSlotCount hasDevupUI importCanonicalMap importClassMap importFileMap importFileRoutes importSheet isDebug registerShorthands registerTheme reserveClassSlots resetBuildState resetStateForTesting seedFileMap setAtomHoist setDebug setModuleResolver setPrefix'.split( + 'Output codeExtract codeExtractWithoutSourceMap exportCanonicalMap exportClassMap exportFileMap exportSheet getCss getDefaultTheme getPrefix getThemeInterface getUnreservedClassSlotCount hasDevupUI importCanonicalMap importClassMap importFileMap importFileRoutes importSheet isDebug registerShorthands registerTheme reserveClassSlots resetBuildState resetStateForTesting seedFileMap setAtomHoist setDebug setModuleResolver setPrefix setStylexStyleResolution'.split( ' ', ) const abi = { @@ -199,8 +199,8 @@ const h = { ) }, } -assert.equal(corpus.length, 25) -assert.equal(new Set(corpus.map((c) => c.name)).size, 25) +assert.equal(corpus.length, 26) +assert.equal(new Set(corpus.map((c) => c.name)).size, 26) h.note('public-error-inventory', runDiagnostics(w)) for (const test of corpus) { scenario = test.name diff --git a/e2e/binding/validation-cases.mjs b/e2e/binding/validation-cases.mjs index c90b0fda0..7a4ede5b2 100644 --- a/e2e/binding/validation-cases.mjs +++ b/e2e/binding/validation-cases.mjs @@ -48,6 +48,11 @@ export const positions = [ ['setDebug', 'debug:b', () => [true]], ['setModuleResolver', 'resolver:resolver', () => [null]], ['setPrefix', 'prefix:prefix', () => ['valid-']], + [ + 'setStylexStyleResolution', + 'resolution:prefix', + () => ['application-order'], + ], ].flatMap(([fn, slots, args]) => slots.split(' ').map((slot, index) => { const [parameter, kind] = slot.split(':') @@ -153,6 +158,6 @@ export const cases = positions.flatMap((position) => .map((good, index) => (index === position.index ? value : good)), })), ) -assert.equal(positions.length, 45) -assert.equal(new Set(positions.map((p) => p.fn)).size, 18) +assert.equal(positions.length, 46) +assert.equal(new Set(positions.map((p) => p.fn)).size, 19) assert.equal(new Set(cases.map((c) => c.id)).size, cases.length) diff --git a/libs/binding/src/lib.rs b/libs/binding/src/lib.rs index cc89b9a04..5b8552cc1 100644 --- a/libs/binding/src/lib.rs +++ b/libs/binding/src/lib.rs @@ -8,6 +8,7 @@ pub use css::atom_hoist::set_atom_hoist; pub use css::debug::{is_debug, set_debug}; pub use css::file_routes::set_file_routes as import_file_routes_internal; pub use css::slot_reservation::unreserved_slot_count as get_unreserved_class_slot_count; +pub use css::style_resolution::set_style_resolution_option as set_stylex_style_resolution; pub use css::{get_prefix, set_custom_shorthands as register_shorthands_internal, set_prefix}; pub use extractor::{has_devup_ui, has_devup_ui_with}; pub use output::{CssOptions, ExtractionMode, Output, SourceMapMode, code_extract}; diff --git a/libs/css/src/lib.rs b/libs/css/src/lib.rs index 22de4cdde..1e7202bd8 100644 --- a/libs/css/src/lib.rs +++ b/libs/css/src/lib.rs @@ -20,6 +20,7 @@ pub mod selector_params; mod selector_separator; pub mod shorthand; pub mod slot_reservation; +pub mod style_resolution; pub mod style_selector; pub mod tailwind_definitions; #[doc(hidden)] diff --git a/libs/css/src/style_resolution.rs b/libs/css/src/style_resolution.rs new file mode 100644 index 000000000..c835676b5 --- /dev/null +++ b/libs/css/src/style_resolution.rs @@ -0,0 +1,109 @@ +//! The `StyleX` `styleResolution` policy a build reads `stylex.create()` with. +//! Devup's own APIs ignore it. + +use std::sync::atomic::{AtomicU8, Ordering}; + +/// How `StyleX` decides between a shorthand and the longhands it covers +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum StyleResolution { + /// A longhand beats a shorthand whatever the order (the `StyleX` default) + #[default] + PropertySpecificity, + /// The property applied last wins, shorthand or not + ApplicationOrder, + /// Shorthands are expanded into longhands at compile time + LegacyExpandShorthands, +} + +/// Every policy, indexed by the number the global stores +const POLICIES: [StyleResolution; 3] = [ + StyleResolution::PropertySpecificity, + StyleResolution::ApplicationOrder, + StyleResolution::LegacyExpandShorthands, +]; + +impl StyleResolution { + /// The option value naming the policy + pub const fn name(self) -> &'static str { + match self { + Self::PropertySpecificity => "property-specificity", + Self::ApplicationOrder => "application-order", + Self::LegacyExpandShorthands => "legacy-expand-shorthands", + } + } + + /// The policy an option value names + pub fn parse(value: &str) -> Result { + POLICIES + .into_iter() + .find(|policy| policy.name() == value) + .ok_or_else(|| { + format!( + "devup-ui option stylex.styleResolution must be 'property-specificity', 'application-order' or 'legacy-expand-shorthands', got {value:?}" + ) + }) + } +} + +static STYLE_RESOLUTION: AtomicU8 = AtomicU8::new(0); + +/// Read `stylex.create()` under `policy` from now on +pub fn set_style_resolution(policy: StyleResolution) { + STYLE_RESOLUTION.store(policy as u8, Ordering::Relaxed); +} + +/// The policy `stylex.create()` is read under +pub fn style_resolution() -> StyleResolution { + POLICIES[usize::from(STYLE_RESOLUTION.load(Ordering::Relaxed))] +} + +/// Install the policy an option value names; nothing names the default +pub fn set_style_resolution_option(value: Option<&str>) -> Result<(), String> { + let policy = value.map_or_else(|| Ok(StyleResolution::default()), StyleResolution::parse)?; + set_style_resolution(policy); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use rstest::rstest; + use serial_test::serial; + + #[rstest] + #[case(None, StyleResolution::PropertySpecificity)] + #[case(Some("property-specificity"), StyleResolution::PropertySpecificity)] + #[case(Some("application-order"), StyleResolution::ApplicationOrder)] + #[case( + Some("legacy-expand-shorthands"), + StyleResolution::LegacyExpandShorthands + )] + #[serial] + fn option_values_name_their_policy( + #[case] value: Option<&str>, + #[case] expected: StyleResolution, + ) { + let _state = crate::test_state::TestStateGuard::new(); + set_style_resolution(StyleResolution::ApplicationOrder); + assert_eq!(set_style_resolution_option(value), Ok(())); + assert_eq!(style_resolution(), expected); + assert_eq!(StyleResolution::parse(expected.name()), Ok(expected)); + } + + #[rstest] + #[case("")] + #[case("Application-Order")] + #[case("last-wins")] + #[serial] + fn unknown_values_are_config_errors_that_keep_the_policy(#[case] value: &str) { + let _state = crate::test_state::TestStateGuard::new(); + set_style_resolution(StyleResolution::ApplicationOrder); + assert_eq!( + set_style_resolution_option(Some(value)), + Err(format!( + "devup-ui option stylex.styleResolution must be 'property-specificity', 'application-order' or 'legacy-expand-shorthands', got {value:?}" + )) + ); + assert_eq!(style_resolution(), StyleResolution::ApplicationOrder); + } +} diff --git a/libs/css/src/test_state.rs b/libs/css/src/test_state.rs index 4a0929e5c..a1400bb47 100644 --- a/libs/css/src/test_state.rs +++ b/libs/css/src/test_state.rs @@ -8,8 +8,8 @@ use std::rc::Rc; use std::sync::atomic::Ordering; use crate::{ - atom_hoist, class_map, debug, file_map, file_routes, slot_reservation, tailwind_definitions, - theme_tokens, + atom_hoist, class_map, debug, file_map, file_routes, slot_reservation, style_resolution, + tailwind_definitions, theme_tokens, }; pub(crate) fn replace_shorthands( @@ -29,6 +29,7 @@ pub(crate) fn replace_shorthands( pub fn reset_state_for_testing() { crate::set_prefix(None); debug::set_debug(false); + style_resolution::set_style_resolution(Default::default()); atom_hoist::set_atom_hoist(None); atom_hoist::restore_atom_plan(None); slot_reservation::reset(); @@ -47,6 +48,7 @@ pub fn reset_state_for_testing() { pub struct TestStateGuard { prefix: Option, debug: bool, + resolution: style_resolution::StyleResolution, hoist: Option, plan: Option>, reservation: slot_reservation::State, @@ -66,6 +68,7 @@ impl TestStateGuard { let guard = Self { prefix: crate::get_prefix(), debug: debug::is_debug(), + resolution: style_resolution::style_resolution(), hoist: atom_hoist::atom_hoist_threshold(), plan: atom_hoist::atom_plan(), reservation: slot_reservation::replace_state(Default::default()), @@ -93,6 +96,7 @@ impl Drop for TestStateGuard { fn drop(&mut self) { crate::set_prefix(self.prefix.take()); debug::set_debug(self.debug); + style_resolution::set_style_resolution(self.resolution); atom_hoist::set_atom_hoist(self.hoist); atom_hoist::restore_atom_plan(self.plan.take()); slot_reservation::replace_state(std::mem::take(&mut self.reservation)); diff --git a/libs/css/src/test_state/tests.rs b/libs/css/src/test_state/tests.rs index 82057e0f9..86693f10d 100644 --- a/libs/css/src/test_state/tests.rs +++ b/libs/css/src/test_state/tests.rs @@ -4,6 +4,7 @@ use serial_test::serial; fn seed() { crate::set_prefix(Some("outer".into())); debug::set_debug(true); + style_resolution::set_style_resolution(style_resolution::StyleResolution::ApplicationOrder); atom_hoist::set_atom_hoist(Some(3)); class_map::set_class_map(HashMap::from([( "x".into(), @@ -34,6 +35,10 @@ fn seed() { fn assert_seed() { assert_eq!(crate::get_prefix().as_deref(), Some("outer")); assert!(debug::is_debug()); + assert_eq!( + style_resolution::style_resolution(), + style_resolution::StyleResolution::ApplicationOrder + ); assert_eq!(atom_hoist::atom_hoist_threshold(), Some(3)); assert_eq!(class_map::get_class_map()["x"]["y"], 7); assert_eq!(file_map::get_file_map().len(), 1); @@ -77,6 +82,10 @@ fn assert_seed() { fn assert_clean() { assert_eq!(crate::get_prefix(), None); assert!(!debug::is_debug()); + assert_eq!( + style_resolution::style_resolution(), + style_resolution::StyleResolution::PropertySpecificity + ); assert_eq!(atom_hoist::atom_hoist_threshold(), None); assert_eq!(class_map::get_class_map(), HashMap::new()); assert_eq!(file_map::get_file_map().len(), 0); diff --git a/libs/extractor/src/extractor/extract_style_from_stylex.rs b/libs/extractor/src/extractor/extract_style_from_stylex.rs index 42bdc0f32..1343cb4bf 100644 --- a/libs/extractor/src/extractor/extract_style_from_stylex.rs +++ b/libs/extractor/src/extractor/extract_style_from_stylex.rs @@ -7,8 +7,10 @@ use crate::stylex::{ dynamic_number_suffix, is_first_that_works_call, is_include_call_static, is_types_call, normalize_stylex_property, stylex_value, }; +use crate::stylex_resolution::{self, Expansion}; use css::optimize_value::optimize_value; use css::sheet_to_variable_name; +use css::style_resolution::{StyleResolution, style_resolution}; use css::style_selector::StyleSelector; use oxc_ast::ast::{ Argument, ArrowFunctionExpression, BindingPattern, Expression, ObjectExpression, @@ -241,9 +243,8 @@ fn extract_stylex_namespace<'a>( Vec, Vec<(String, usize)>, ) { - let mut styles = vec![]; + let mut keys = Keys::default(); let mut include_refs = vec![]; - let mut groups = vec![]; for style_prop in &namespace.properties { let style_prop = match style_prop { ObjectPropertyKind::ObjectProperty(style_prop) => style_prop, @@ -275,7 +276,7 @@ fn extract_stylex_namespace<'a>( continue; }; let parent_selectors = [SelectorPart::Pseudo(prop_name.to_string())]; - let before = styles.len(); + let mut inner = Keys::default(); for inner_prop in &inner_obj.properties { let inner_prop = match inner_prop { ObjectPropertyKind::ObjectProperty(inner_prop) => inner_prop, @@ -296,19 +297,20 @@ fn extract_stylex_namespace<'a>( )); continue; } - push_decomposed( - &mut styles, - decompose_value_conditions( - &property, - &inner_prop.value, - &parent_selectors, - leaf, - errors, - resolver, - ), - ); + let written = Written { + key: inner_name.as_ref(), + property: &property, + value: &inner_prop.value, + }; + inner.extend(resolved_keys( + &written, + &parent_selectors, + leaf, + errors, + resolver, + )); } - groups.push((prop_name.to_string(), styles.len() - before)); + keys.set(prop_name.to_string(), inner.into_styles()); continue; } @@ -320,34 +322,143 @@ fn extract_stylex_namespace<'a>( )); continue; } - if SHORTHAND_PROPERTIES.contains(css_property.as_str()) { + if style_resolution() == StyleResolution::PropertySpecificity + && SHORTHAND_PROPERTIES.contains(css_property.as_str()) + { eprintln!( "[stylex] WARNING: Shorthand property '{css_property}' may cause unexpected specificity issues. Consider using longhand properties (e.g., 'marginTop', 'paddingLeft')." ); } - let before = styles.len(); - push_decomposed( - &mut styles, - decompose_value_conditions( - &css_property, - &style_prop.value, - &[], - leaf, - errors, - resolver, - ), - ); - groups.push((prop_name.to_string(), styles.len() - before)); + let written = Written { + key: prop_name.as_ref(), + property: &css_property, + value: &style_prop.value, + }; + keys.extend(resolved_keys(&written, &[], leaf, errors, resolver)); } + let (styles, groups) = keys.into_groups(); (styles, include_refs, groups) } -fn push_decomposed(styles: &mut Vec>, decomposed: Vec) { - for style in decomposed { - if let Some(value) = style.value { - styles.push(raw_static_style(style.property, &value, style.selector)); +/// The styles of a namespace by key: a later key replaces an earlier one +/// where that one stands, as an object literal keeps it +#[derive(Default)] +struct Keys<'a>(Vec<(String, Vec>)>); + +impl<'a> Keys<'a> { + fn set(&mut self, key: String, styles: Vec>) { + match self.0.iter_mut().find(|(written, _)| *written == key) { + Some(entry) => entry.1 = styles, + None => self.0.push((key, styles)), + } + } + + fn extend(&mut self, keys: Vec<(String, Vec)>) { + for (key, decomposed) in keys { + self.set(key, decomposed_styles(decomposed)); + } + } + + fn into_styles(self) -> Vec> { + self.0.into_iter().flat_map(|(_, styles)| styles).collect() + } + + /// The styles, with each key and how many of them it gives + fn into_groups(self) -> (Vec>, Vec<(String, usize)>) { + let groups = self + .0 + .iter() + .map(|(key, styles)| (key.clone(), styles.len())) + .collect(); + (self.into_styles(), groups) + } +} + +fn decomposed_styles<'a>(decomposed: Vec) -> Vec> { + decomposed + .into_iter() + .filter_map(|style| { + let value = style.value?; + Some(raw_static_style(style.property, &value, style.selector)) + }) + .collect() +} + +/// A `stylex.create()` key as written, with the CSS property it names +struct Written<'w, 'a> { + key: &'w str, + property: &'w str, + value: &'w Expression<'a>, +} + +/// The keys `written` gives under the build's `styleResolution`, each with +/// its decomposed styles; a key the policy rejects gives none +fn resolved_keys( + written: &Written<'_, '_>, + parent_selectors: &[SelectorPart], + leaf: &Leaf<'_>, + errors: &mut Vec<(u32, String)>, + resolver: StylexResolver<'_>, +) -> Vec<(String, Vec)> { + let decomposed = decompose_value_conditions( + written.property, + written.value, + parent_selectors, + leaf, + errors, + resolver, + ); + let policy = style_resolution(); + let Some(expansion) = stylex_resolution::expansion(policy, written.key) else { + return vec![(written.key.to_string(), decomposed)]; + }; + expand(expansion, decomposed).unwrap_or_else(|message| { + errors.push(( + written.value.span().start, + build_time_error( + "stylex.create", + written.key, + &format!("{message} (styleResolution: '{}')", policy.name()), + ), + )); + vec![] + }) +} + +/// The keys `expansion` spreads the leaves of one key over, in the order +/// `StyleX` gives them +fn expand( + expansion: &Expansion, + leaves: Vec, +) -> Result)>, String> { + if has_fallbacks(&leaves) { + return Err("Cannot use fallbacks for shorthands. Use the expansion instead.".to_string()); + } + let mut keys: Vec<(String, Vec)> = vec![]; + for leaf in leaves { + for (key, value) in expansion.apply(leaf.value.as_deref())? { + let style = DecomposedStyle { + property: normalize_stylex_property(key), + value, + selector: leaf.selector.clone(), + }; + match keys.iter_mut().find(|(written, _)| written == key) { + Some((_, styles)) => styles.push(style), + None => keys.push((key.to_string(), vec![style])), + } } } + Ok(keys) +} + +/// Whether two leaves apply under the same conditions: the fallbacks of +/// `firstThatWorks()` +fn has_fallbacks(leaves: &[DecomposedStyle]) -> bool { + leaves.iter().enumerate().any(|(index, style)| { + leaves[..index] + .iter() + .any(|earlier| earlier.selector == style.selector) + }) } /// `...stylex.include(base.member)`: `None` when the spread is not an diff --git a/libs/extractor/src/lib.rs b/libs/extractor/src/lib.rs index 56f562777..deced77c6 100644 --- a/libs/extractor/src/lib.rs +++ b/libs/extractor/src/lib.rs @@ -132,6 +132,9 @@ mod stylesheet_policy; #[cfg(test)] mod stylesheet_regression_tests; mod stylex; +mod stylex_resolution; +#[cfg(test)] +mod stylex_resolution_extract_tests; mod tailwind; mod tailwind_children; mod tailwind_color; diff --git a/libs/extractor/src/stylex_resolution.rs b/libs/extractor/src/stylex_resolution.rs new file mode 100644 index 000000000..00db9e1a8 --- /dev/null +++ b/libs/extractor/src/stylex_resolution.rs @@ -0,0 +1,238 @@ +//! `StyleX`'s `styleResolution` read at build time: under `application-order` +//! and `legacy-expand-shorthands`, a `stylex.create()` key expands as +//! `@stylexjs/babel-plugin` expands it, into the keys it sets and the keys it +//! resets to `null`. `stylex.props()` then merges those keys as `StyleX` does: +//! a later key wins and a `null` key removes the earlier one. +//! `property-specificity` (the default) expands nothing: the stylesheet writes +//! a longhand after every shorthand covering it. + +use css::style_resolution::StyleResolution; + +#[path = "stylex_resolution_tables.rs"] +mod tables; + +/// How a key's value spreads over the keys it sets +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Split { + /// Every key gets the whole value + Whole, + /// `a b` over two keys, the second defaulting to the first + Pair, + /// `top right bottom left` over four keys, as `margin` reads them + Box, + /// `containIntrinsicSize`: an `auto` joins the size after it + ContainIntrinsicSize, + /// `listStyle`: its parts sorted into type, position and image + ListStyle, + /// A key `StyleX` rejects under the policy + Unsupported(&'static str), +} + +/// What one `stylex.create()` key expands to +#[derive(Debug)] +pub(crate) struct Expansion { + split: Split, + targets: &'static [&'static str], + resets: &'static [&'static str], +} + +/// A key a value expands to, with its value; `None` resets it +pub(crate) type ExpandedKey = (&'static str, Option); + +impl Expansion { + pub(crate) const fn new( + split: Split, + targets: &'static [&'static str], + resets: &'static [&'static str], + ) -> Self { + Self { + split, + targets, + resets, + } + } + + /// The keys `value` sets and resets, in the order `StyleX` gives them + pub(crate) fn apply(&self, value: Option<&str>) -> Result, String> { + let values = spread(self.split, value, self.targets.len())?; + Ok(self + .targets + .iter() + .copied() + .zip(values) + .chain(self.resets.iter().map(|reset| (*reset, None))) + .collect()) + } +} + +/// What `key` expands to under `policy`; `None` when it stays as written +pub(crate) fn expansion(policy: StyleResolution, key: &str) -> Option<&'static Expansion> { + match policy { + StyleResolution::PropertySpecificity => None, + StyleResolution::ApplicationOrder => tables::APPLICATION_ORDER.get(key), + StyleResolution::LegacyExpandShorthands => tables::LEGACY_EXPAND_SHORTHANDS.get(key), + } +} + +/// The values of the `keys` keys `split` spreads `value` over; a `null` +/// value resets every one of them +fn spread(split: Split, value: Option<&str>, keys: usize) -> Result>, String> { + let Some(value) = value else { + return Ok(vec![None; keys]); + }; + match split { + Split::Whole => Ok(vec![Some(value.to_string()); keys]), + Split::Pair => Ok(sides(split_value(value), &[0, 0])), + Split::Box => Ok(sides(split_value(value), &[0, 0, 0, 1])), + Split::ContainIntrinsicSize => Ok(sides(join_auto(split_value(value)), &[0, 0])), + Split::ListStyle => list_style(value), + Split::Unsupported(message) => Err(message.to_string()), + } +} + +/// `parts` over sides whose missing part repeats the part `defaults` names +fn sides(parts: Vec, defaults: &[usize]) -> Vec> { + let mut sides: Vec = Vec::with_capacity(defaults.len()); + let mut parts = parts.into_iter(); + for &default in defaults { + let side = parts + .next() + .or_else(|| sides.get(default).cloned()) + .unwrap_or_default(); + sides.push(side); + } + sides.into_iter().map(Some).collect() +} + +/// `auto 10px` stays one size, as `containIntrinsicSize` reads it +fn join_auto(parts: Vec) -> Vec { + let mut joined: Vec = Vec::with_capacity(parts.len()); + for part in parts { + match joined.last_mut() { + Some(last) if last == "auto" => *last = format!("auto {part}"), + _ => joined.push(part), + } + } + joined +} + +/// The parts of a value as `StyleX` splits it: at spaces, commas and slashes +/// outside functions and strings, a final `!important` applying to each part. +/// A value without parts is one empty part +pub(crate) fn split_value(value: &str) -> Vec { + let mut parts = vec![]; + let mut current = String::new(); + let mut depth = 0usize; + let mut quote: Option = None; + for c in value.chars() { + match quote { + Some(open) => { + current.push(c); + quote = (c != open).then_some(open); + } + None if depth == 0 && (c.is_whitespace() || c == ',' || c == '/') => { + flush(&mut parts, &mut current); + } + None => { + depth = nesting(depth, c); + quote = matches!(c, '"' | '\'').then_some(c); + current.push(c); + } + } + } + flush(&mut parts, &mut current); + important(parts) +} + +/// The function depth after `c` +const fn nesting(depth: usize, c: char) -> usize { + match c { + '(' => depth + 1, + ')' => depth.saturating_sub(1), + _ => depth, + } +} + +fn flush(parts: &mut Vec, current: &mut String) { + if !current.is_empty() { + parts.push(std::mem::take(current)); + } +} + +/// A trailing `!important` marks every part before it +fn important(mut parts: Vec) -> Vec { + if parts.len() > 1 && parts[parts.len() - 1].eq_ignore_ascii_case("!important") { + parts.pop(); + return parts + .into_iter() + .map(|part| format!("{part} !important")) + .collect(); + } + if parts.is_empty() { + parts.push(String::new()); + } + parts +} + +/// Values every `listStyle` longhand takes alike +const LIST_STYLE_GLOBALS: [&str; 4] = ["inherit", "initial", "revert", "unset"]; + +/// `listStyle` sorted into its type, position and image, as `StyleX` sorts it +fn list_style(value: &str) -> Result>, String> { + let parts = split_value(value); + if let [part] = parts.as_slice() + && LIST_STYLE_GLOBALS.contains(&part.as_str()) + { + return Ok(vec![Some(part.clone()); 3]); + } + let invalid = || format!("invalid \"listStyle\" value of {value:?}"); + let mut sorted = ListStyle::default(); + let mut remaining = vec![]; + for part in parts { + if LIST_STYLE_GLOBALS.contains(&part.as_str()) || part.contains("var(--") { + return Err(invalid()); + } + if part == "inside" || part == "outside" { + sorted.position = Some(take(sorted.position, part).ok_or_else(invalid)?); + } else if part != "none" && is_list_style_type(&part) { + sorted.kind = Some(take(sorted.kind, part).ok_or_else(invalid)?); + } else { + remaining.push(part); + } + } + for part in remaining { + if part == "none" && sorted.kind.is_none() { + sorted.kind = Some(part); + } else { + sorted.image = Some(take(sorted.image, part).ok_or_else(invalid)?); + } + } + Ok(vec![sorted.kind, sorted.position, sorted.image]) +} + +/// The longhands `listStyle` sorts its parts into +#[derive(Default)] +struct ListStyle { + kind: Option, + position: Option, + image: Option, +} + +/// `part` for a longhand not set yet; `None` when it already is +fn take(set: Option, part: String) -> Option { + set.is_none().then_some(part) +} + +/// A keyword or a quoted string, as `StyleX` reads a `list-style-type` +fn is_list_style_type(part: &str) -> bool { + let quoted = |quote: char| part.len() >= 2 && part.starts_with(quote) && part.ends_with(quote); + let keyword = !part.is_empty() + && part + .bytes() + .all(|byte| byte.is_ascii_lowercase() || byte == b'-'); + keyword || quoted('"') || quoted('\'') +} + +#[cfg(test)] +#[path = "stylex_resolution_tests.rs"] +mod tests; diff --git a/libs/extractor/src/stylex_resolution_extract_tests.rs b/libs/extractor/src/stylex_resolution_extract_tests.rs new file mode 100644 index 000000000..1987b11aa --- /dev/null +++ b/libs/extractor/src/stylex_resolution_extract_tests.rs @@ -0,0 +1,225 @@ +//! `stylex.create()` read under each `styleResolution`, and `stylex.props()` +//! merging the keys it gives +use crate::{ExtractOption, extract, test_state::TestStateGuard}; +use css::style_resolution::{StyleResolution, set_style_resolution}; +use css::{class_map::reset_class_map, file_map::reset_file_map}; +use rstest::rstest; +use serial_test::serial; + +/// The code `create` and `use_` give under `policy`, with debug class names +/// short of their file suffix +fn code_under(policy: StyleResolution, create: &str, use_: &str) -> String { + let _state = TestStateGuard::new(); + reset_class_map(); + reset_file_map(); + css::debug::set_debug(true); + set_style_resolution(policy); + let code = format!( + "import * as stylex from '@stylexjs/stylex'; +const s = stylex.create({{ {create} }}); +export const result = {use_};" + ); + extract("test.tsx", &code, ExtractOption::default()) + .map_or_else(|error| error.to_string(), |output| output.code) + .replace("-255-a", "-255") +} + +/// The classes of the first string after `marker` in `code`, sorted +fn classes(code: &str, marker: &str) -> Vec { + let (_, rest) = code.split_once(marker).unwrap_or_default(); + let (list, _) = rest.split_once('"').unwrap_or_default(); + let mut classes: Vec = list.split_whitespace().map(str::to_string).collect(); + classes.sort_unstable(); + classes +} + +fn sorted(expected: &[&str]) -> Vec { + let mut expected: Vec = expected.iter().map(|class| (*class).to_string()).collect(); + expected.sort_unstable(); + expected +} + +const SIDES: &str = "top: { paddingTop: '1px' }, pad: { padding: '2px' }"; + +#[rstest] +// The default leaves both: the sheet writes the longhand after its shorthand +#[case( + StyleResolution::PropertySpecificity, + "stylex.props(s.top, s.pad)", + &["padding-top-0-1px--255", "padding-0-2px--255"] +)] +// A later shorthand resets the longhands it covers +#[case( + StyleResolution::ApplicationOrder, + "stylex.props(s.top, s.pad)", + &["padding-0-2px--255"] +)] +// A later longhand applies after its shorthand +#[case( + StyleResolution::ApplicationOrder, + "stylex.props(s.pad, s.top)", + &["padding-0-2px--255", "padding-top-0-1px--255"] +)] +// The shorthand is gone: its sides merge like any longhand +#[case( + StyleResolution::LegacyExpandShorthands, + "stylex.props(s.pad, s.top)", + &[ + "padding-top-0-1px--255", + "padding-inline-end-0-2px--255", + "padding-bottom-0-2px--255", + "padding-inline-start-0-2px--255", + ] +)] +#[case( + StyleResolution::LegacyExpandShorthands, + "stylex.props(s.top, s.pad)", + &[ + "padding-top-0-2px--255", + "padding-inline-end-0-2px--255", + "padding-bottom-0-2px--255", + "padding-inline-start-0-2px--255", + ] +)] +#[serial] +fn props_merge_the_keys_a_policy_gives( + #[case] policy: StyleResolution, + #[case] use_: &str, + #[case] expected: &[&str], +) { + let code = code_under(policy, SIDES, use_); + assert_eq!(classes(&code, "className: \""), sorted(expected), "{code}"); +} + +#[rstest] +// Within a namespace, a later key replaces an earlier one where it stands +#[case( + StyleResolution::ApplicationOrder, + "a: { paddingTop: '1px', padding: '2px' }", + &["padding-0-2px--255"] +)] +#[case( + StyleResolution::ApplicationOrder, + "a: { padding: '2px', paddingTop: '1px' }", + &["padding-0-2px--255", "padding-top-0-1px--255"] +)] +#[case( + StyleResolution::PropertySpecificity, + "a: { paddingTop: '1px', padding: '2px' }", + &["padding-top-0-1px--255", "padding-0-2px--255"] +)] +#[case( + StyleResolution::LegacyExpandShorthands, + "a: { margin: '1px 2px', marginTop: '3px' }", + &[ + "margin-top-0-3px--255", + "margin-inline-end-0-2px--255", + "margin-bottom-0-1px--255", + "margin-inline-start-0-2px--255", + ] +)] +// An alias names the property it stands for +#[case( + StyleResolution::ApplicationOrder, + "a: { marginStart: 4 }", + &["margin-inline-start-0-4px--255"] +)] +#[case( + StyleResolution::LegacyExpandShorthands, + "a: { paddingBlock: '1px 2px' }", + &["padding-top-0-1px--255", "padding-bottom-0-2px--255"] +)] +// Each condition of a value expands on its own +#[case( + StyleResolution::LegacyExpandShorthands, + "a: { gap: { default: '1px 2px', ':hover': null, '@media (min-width: 1px)': '3px' } }", + &[ + "row-gap-0-1px--255", + "row-gap-0-3px-_at_media_lp_min-width_c_1px_rp_-255", + "column-gap-0-2px--255", + "column-gap-0-3px-_at_media_lp_min-width_c_1px_rp_-255", + ] +)] +// A pseudo-class object expands its own keys +#[case( + StyleResolution::ApplicationOrder, + "a: { ':hover': { paddingTop: '1px', padding: '2px' } }", + &["padding-0-2px-_a__c_hover-255"] +)] +// Only the keys StyleX's tables name expand +#[case( + StyleResolution::LegacyExpandShorthands, + "a: { 'padding': '1px 2px', 'padding-block': '3px' }", + &[ + "padding-top-0-1px--255", + "padding-inline-end-0-2px--255", + "padding-bottom-0-1px--255", + "padding-inline-start-0-2px--255", + "padding-block-0-3px--255", + ] +)] +#[serial] +fn namespaces_expand_their_keys( + #[case] policy: StyleResolution, + #[case] create: &str, + #[case] expected: &[&str], +) { + let code = code_under(policy, create, "s"); + assert_eq!(classes(&code, "\"a\": \""), sorted(expected), "{code}"); +} + +#[rstest] +// A null shorthand resets every key it expands to +#[case(StyleResolution::LegacyExpandShorthands)] +#[case(StyleResolution::ApplicationOrder)] +#[serial] +fn null_shorthands_reset_what_they_cover(#[case] policy: StyleResolution) { + let code = code_under( + policy, + "top: { paddingTop: '1px' }, none: { padding: null }", + "stylex.props(s.top, s.none)", + ); + assert!(code.contains("{ className: \"\" }"), "{code}"); +} + +#[rstest] +#[case( + StyleResolution::ApplicationOrder, + "a: { all: 'unset' }", + "`stylex.create()` cannot use `all` at build time: all is not supported (styleResolution: 'application-order')" +)] +#[case( + StyleResolution::ApplicationOrder, + "a: { padding: stylex.firstThatWorks('1px', '2px') }", + "`stylex.create()` cannot use `padding` at build time: Cannot use fallbacks for shorthands. Use the expansion instead. (styleResolution: 'application-order')" +)] +#[case( + StyleResolution::LegacyExpandShorthands, + "a: { listStyle: 'inside outside' }", + "`stylex.create()` cannot use `listStyle` at build time: invalid \"listStyle\" value of \"inside outside\" (styleResolution: 'legacy-expand-shorthands')" +)] +#[serial] +fn rejected_keys_are_build_errors( + #[case] policy: StyleResolution, + #[case] create: &str, + #[case] expected: &str, +) { + let code = code_under(policy, create, "s"); + assert!(code.contains(expected), "{expected}\n{code}"); +} + +// Fallbacks of a longhand stay, as the default reads them +#[test] +#[serial] +fn longhand_fallbacks_stay() { + let code = code_under( + StyleResolution::LegacyExpandShorthands, + "a: { position: stylex.firstThatWorks('sticky', 'fixed') }", + "s", + ); + assert_eq!( + classes(&code, "\"a\": \""), + sorted(&["position-0-fixed--255", "position-0-sticky--255"]), + "{code}" + ); +} diff --git a/libs/extractor/src/stylex_resolution_tables.rs b/libs/extractor/src/stylex_resolution_tables.rs new file mode 100644 index 000000000..44b2be4c4 --- /dev/null +++ b/libs/extractor/src/stylex_resolution_tables.rs @@ -0,0 +1,272 @@ +//! The shorthand tables of `@stylexjs/babel-plugin` 0.19.1 (its `expansions` +//! by `styleResolution`), generated from that source: each key gives the keys +//! it sets, how its value spreads over them, and the keys it resets to `null`. +//! `float` and `clear` keep their value: the logical-value polyfill they +//! expand to needs `StyleX`'s own runtime variables. + +use super::{Expansion, Split}; + +/// `application-order`: a key keeps its value and resets the keys it covers +pub(super) static APPLICATION_ORDER: phf::Map<&'static str, Expansion> = phf::phf_map! { + "all" => Expansion::new(Split::Unsupported("all is not supported"), &[], &[]), + "animation" => Expansion::new(Split::Whole, &["animation"], &["animationComposition", "animationName", "animationDuration", "animationTimingFunction", "animationDelay", "animationIterationCount", "animationDirection", "animationFillMode", "animationPlayState", "animationRange", "animationRangeEnd", "animationRangeStart", "animationTimeline"]), + "animationRange" => Expansion::new(Split::Whole, &["animationRange"], &["animationRangeEnd", "animationRangeStart"]), + "background" => Expansion::new(Split::Whole, &["background"], &["backgroundAttachment", "backgroundClip", "backgroundColor", "backgroundImage", "backgroundOrigin", "backgroundPosition", "backgroundPositionX", "backgroundPositionY", "backgroundRepeat", "backgroundSize"]), + "backgroundPosition" => Expansion::new(Split::Whole, &["backgroundPosition"], &["backgroundPositionX", "backgroundPositionY"]), + "blockSize" => Expansion::new(Split::Whole, &["height"], &[]), + "border" => Expansion::new(Split::Whole, &["border"], &["borderWidth", "borderInlineWidth", "borderInlineStartWidth", "borderLeftWidth", "borderInlineEndWidth", "borderRightWidth", "borderBlockWidth", "borderTopWidth", "borderBottomWidth", "borderStyle", "borderInlineStyle", "borderInlineStartStyle", "borderLeftStyle", "borderInlineEndStyle", "borderRightStyle", "borderBlockStyle", "borderTopStyle", "borderBottomStyle", "borderColor", "borderInlineColor", "borderInlineStartColor", "borderLeftColor", "borderInlineEndColor", "borderRightColor", "borderBlockColor", "borderTopColor", "borderBottomColor"]), + "borderBlock" => Expansion::new(Split::Whole, &["borderBlock"], &["borderBlockWidth", "borderTopWidth", "borderBottomWidth", "borderBlockStyle", "borderTopStyle", "borderBottomStyle", "borderBlockColor", "borderTopColor", "borderBottomColor"]), + "borderBlockColor" => Expansion::new(Split::Whole, &["borderBlockColor"], &["borderTopColor", "borderBottomColor"]), + "borderBlockEnd" => Expansion::new(Split::Whole, &["borderBottom"], &["borderBottomWidth", "borderBottomStyle", "borderBottomColor"]), + "borderBlockEndColor" => Expansion::new(Split::Whole, &["borderBottomColor"], &[]), + "borderBlockEndStyle" => Expansion::new(Split::Whole, &["borderBottomStyle"], &[]), + "borderBlockEndWidth" => Expansion::new(Split::Whole, &["borderBottomWidth"], &[]), + "borderBlockStart" => Expansion::new(Split::Whole, &["borderTop"], &["borderTopWidth", "borderTopStyle", "borderTopColor"]), + "borderBlockStartColor" => Expansion::new(Split::Whole, &["borderTopColor"], &[]), + "borderBlockStartStyle" => Expansion::new(Split::Whole, &["borderTopStyle"], &[]), + "borderBlockStartWidth" => Expansion::new(Split::Whole, &["borderTopWidth"], &[]), + "borderBlockStyle" => Expansion::new(Split::Whole, &["borderBlockStyle"], &["borderTopStyle", "borderBottomStyle"]), + "borderBlockWidth" => Expansion::new(Split::Whole, &["borderBlockWidth"], &["borderTopWidth", "borderBottomWidth"]), + "borderBottom" => Expansion::new(Split::Whole, &["borderBottom"], &["borderBottomWidth", "borderBottomStyle", "borderBottomColor"]), + "borderBottomEndRadius" => Expansion::new(Split::Whole, &["borderEndEndRadius"], &[]), + "borderBottomLeftRadius" => Expansion::new(Split::Whole, &["borderBottomLeftRadius"], &["borderEndStartRadius", "borderEndEndRadius"]), + "borderBottomRightRadius" => Expansion::new(Split::Whole, &["borderBottomRightRadius"], &["borderEndStartRadius", "borderEndEndRadius"]), + "borderBottomStartRadius" => Expansion::new(Split::Whole, &["borderEndStartRadius"], &[]), + "borderColor" => Expansion::new(Split::Whole, &["borderColor"], &["borderInlineColor", "borderInlineStartColor", "borderLeftColor", "borderInlineEndColor", "borderRightColor", "borderBlockColor", "borderTopColor", "borderBottomColor"]), + "borderEnd" => Expansion::new(Split::Whole, &["borderInlineEnd"], &["borderInlineEndWidth", "borderLeftWidth", "borderRightWidth", "borderInlineEndStyle", "borderLeftStyle", "borderRightStyle", "borderInlineEndColor", "borderLeftColor", "borderRightColor"]), + "borderEndColor" => Expansion::new(Split::Whole, &["borderInlineEndColor"], &["borderLeftColor", "borderRightColor"]), + "borderEndEndRadius" => Expansion::new(Split::Whole, &["borderEndEndRadius"], &["borderBottomLeftRadius", "borderBottomRightRadius"]), + "borderEndStartRadius" => Expansion::new(Split::Whole, &["borderEndStartRadius"], &["borderBottomLeftRadius", "borderBottomRightRadius"]), + "borderEndStyle" => Expansion::new(Split::Whole, &["borderInlineEndStyle"], &["borderLeftStyle", "borderRightStyle"]), + "borderEndWidth" => Expansion::new(Split::Whole, &["borderInlineEndWidth"], &["borderLeftWidth", "borderRightWidth"]), + "borderHorizontal" => Expansion::new(Split::Whole, &["borderInline"], &["borderInlineWidth", "borderInlineStartWidth", "borderLeftWidth", "borderInlineEndWidth", "borderRightWidth", "borderInlineStyle", "borderInlineStartStyle", "borderLeftStyle", "borderInlineEndStyle", "borderRightStyle", "borderInlineColor", "borderInlineStartColor", "borderLeftColor", "borderInlineEndColor", "borderRightColor"]), + "borderHorizontalColor" => Expansion::new(Split::Whole, &["borderInlineColor"], &["borderInlineStartColor", "borderLeftColor", "borderInlineEndColor", "borderRightColor"]), + "borderHorizontalStyle" => Expansion::new(Split::Whole, &["borderInlineStyle"], &["borderInlineStartStyle", "borderLeftStyle", "borderInlineEndStyle", "borderRightStyle"]), + "borderHorizontalWidth" => Expansion::new(Split::Whole, &["borderInlineWidth"], &["borderInlineStartWidth", "borderLeftWidth", "borderInlineEndWidth", "borderRightWidth"]), + "borderImage" => Expansion::new(Split::Whole, &["borderImage"], &["borderImageOutset", "borderImageRepeat", "borderImageSlice", "borderImageSource", "borderImageWidth"]), + "borderInline" => Expansion::new(Split::Whole, &["borderInline"], &["borderInlineWidth", "borderInlineStartWidth", "borderLeftWidth", "borderInlineEndWidth", "borderRightWidth", "borderInlineStyle", "borderInlineStartStyle", "borderLeftStyle", "borderInlineEndStyle", "borderRightStyle", "borderInlineColor", "borderInlineStartColor", "borderLeftColor", "borderInlineEndColor", "borderRightColor"]), + "borderInlineColor" => Expansion::new(Split::Whole, &["borderInlineColor"], &["borderInlineStartColor", "borderLeftColor", "borderInlineEndColor", "borderRightColor"]), + "borderInlineEnd" => Expansion::new(Split::Whole, &["borderInlineEnd"], &["borderInlineEndWidth", "borderLeftWidth", "borderRightWidth", "borderInlineEndStyle", "borderLeftStyle", "borderRightStyle", "borderInlineEndColor", "borderLeftColor", "borderRightColor"]), + "borderInlineEndColor" => Expansion::new(Split::Whole, &["borderInlineEndColor"], &["borderLeftColor", "borderRightColor"]), + "borderInlineEndStyle" => Expansion::new(Split::Whole, &["borderInlineEndStyle"], &["borderLeftStyle", "borderRightStyle"]), + "borderInlineEndWidth" => Expansion::new(Split::Whole, &["borderInlineEndWidth"], &["borderLeftWidth", "borderRightWidth"]), + "borderInlineStart" => Expansion::new(Split::Whole, &["borderInlineStart"], &["borderInlineStartWidth", "borderLeftWidth", "borderRightWidth", "borderInlineStartStyle", "borderLeftStyle", "borderRightStyle", "borderInlineStartColor", "borderLeftColor", "borderRightColor"]), + "borderInlineStartColor" => Expansion::new(Split::Whole, &["borderInlineStartColor"], &["borderLeftColor", "borderRightColor"]), + "borderInlineStartStyle" => Expansion::new(Split::Whole, &["borderInlineStartStyle"], &["borderLeftStyle", "borderRightStyle"]), + "borderInlineStartWidth" => Expansion::new(Split::Whole, &["borderInlineStartWidth"], &["borderLeftWidth", "borderRightWidth"]), + "borderInlineStyle" => Expansion::new(Split::Whole, &["borderInlineStyle"], &["borderInlineStartStyle", "borderLeftStyle", "borderInlineEndStyle", "borderRightStyle"]), + "borderInlineWidth" => Expansion::new(Split::Whole, &["borderInlineWidth"], &["borderInlineStartWidth", "borderLeftWidth", "borderInlineEndWidth", "borderRightWidth"]), + "borderLeft" => Expansion::new(Split::Whole, &["borderLeft"], &["borderLeftWidth", "borderInlineStartWidth", "borderInlineEndWidth", "borderLeftStyle", "borderInlineStartStyle", "borderInlineEndStyle", "borderLeftColor", "borderInlineStartColor", "borderInlineEndColor"]), + "borderLeftColor" => Expansion::new(Split::Whole, &["borderLeftColor"], &["borderInlineStartColor", "borderInlineEndColor"]), + "borderLeftStyle" => Expansion::new(Split::Whole, &["borderLeftStyle"], &["borderInlineStartStyle", "borderInlineEndStyle"]), + "borderLeftWidth" => Expansion::new(Split::Whole, &["borderLeftWidth"], &["borderInlineStartWidth", "borderInlineEndWidth"]), + "borderRadius" => Expansion::new(Split::Whole, &["borderRadius"], &["borderStartStartRadius", "borderStartEndRadius", "borderEndStartRadius", "borderEndEndRadius", "borderTopLeftRadius", "borderTopRightRadius", "borderBottomLeftRadius", "borderBottomRightRadius"]), + "borderRight" => Expansion::new(Split::Whole, &["borderRight"], &["borderRightWidth", "borderInlineStartWidth", "borderInlineEndWidth", "borderRightStyle", "borderInlineStartStyle", "borderInlineEndStyle", "borderRightColor", "borderInlineStartColor", "borderInlineEndColor"]), + "borderRightColor" => Expansion::new(Split::Whole, &["borderRightColor"], &["borderInlineStartColor", "borderInlineEndColor"]), + "borderRightStyle" => Expansion::new(Split::Whole, &["borderRightStyle"], &["borderInlineStartStyle", "borderInlineEndStyle"]), + "borderRightWidth" => Expansion::new(Split::Whole, &["borderRightWidth"], &["borderInlineStartWidth", "borderInlineEndWidth"]), + "borderStart" => Expansion::new(Split::Whole, &["borderInlineStart"], &["borderInlineStartWidth", "borderLeftWidth", "borderRightWidth", "borderInlineStartStyle", "borderLeftStyle", "borderRightStyle", "borderInlineStartColor", "borderLeftColor", "borderRightColor"]), + "borderStartColor" => Expansion::new(Split::Whole, &["borderInlineStartColor"], &["borderLeftColor", "borderRightColor"]), + "borderStartEndRadius" => Expansion::new(Split::Whole, &["borderStartEndRadius"], &["borderTopLeftRadius", "borderTopRightRadius"]), + "borderStartStartRadius" => Expansion::new(Split::Whole, &["borderStartStartRadius"], &["borderTopLeftRadius", "borderTopRightRadius"]), + "borderStartStyle" => Expansion::new(Split::Whole, &["borderInlineStartStyle"], &["borderLeftStyle", "borderRightStyle"]), + "borderStartWidth" => Expansion::new(Split::Whole, &["borderInlineStartWidth"], &["borderLeftWidth", "borderRightWidth"]), + "borderStyle" => Expansion::new(Split::Whole, &["borderStyle"], &["borderInlineStyle", "borderInlineStartStyle", "borderLeftStyle", "borderInlineEndStyle", "borderRightStyle", "borderBlockStyle", "borderTopStyle", "borderBottomStyle"]), + "borderTop" => Expansion::new(Split::Whole, &["borderTop"], &["borderTopWidth", "borderTopStyle", "borderTopColor"]), + "borderTopEndRadius" => Expansion::new(Split::Whole, &["borderStartEndRadius"], &[]), + "borderTopLeftRadius" => Expansion::new(Split::Whole, &["borderTopLeftRadius"], &["borderStartStartRadius", "borderStartEndRadius"]), + "borderTopRightRadius" => Expansion::new(Split::Whole, &["borderTopRightRadius"], &["borderStartStartRadius", "borderStartEndRadius"]), + "borderTopStartRadius" => Expansion::new(Split::Whole, &["borderStartStartRadius"], &[]), + "borderVertical" => Expansion::new(Split::Whole, &["borderBlock"], &["borderBlockWidth", "borderTopWidth", "borderBottomWidth", "borderBlockStyle", "borderTopStyle", "borderBottomStyle", "borderBlockColor", "borderTopColor", "borderBottomColor"]), + "borderVerticalColor" => Expansion::new(Split::Whole, &["borderBlockColor"], &["borderTopColor", "borderBottomColor"]), + "borderVerticalStyle" => Expansion::new(Split::Whole, &["borderBlockStyle"], &["borderTopStyle", "borderBottomStyle"]), + "borderVerticalWidth" => Expansion::new(Split::Whole, &["borderBlockWidth"], &["borderTopWidth", "borderBottomWidth"]), + "borderWidth" => Expansion::new(Split::Whole, &["borderWidth"], &["borderInlineWidth", "borderInlineStartWidth", "borderLeftWidth", "borderInlineEndWidth", "borderRightWidth", "borderBlockWidth", "borderTopWidth", "borderBottomWidth"]), + "columnRule" => Expansion::new(Split::Whole, &["columnRule"], &["columnRuleColor", "columnRuleStyle", "columnRuleWidth"]), + "columns" => Expansion::new(Split::Whole, &["columns"], &["columnCount", "columnWidth"]), + "containIntrinsicBlockSize" => Expansion::new(Split::Whole, &["containIntrinsicHeight"], &[]), + "containIntrinsicInlineSize" => Expansion::new(Split::Whole, &["containIntrinsicWidth"], &[]), + "containIntrinsicSize" => Expansion::new(Split::Whole, &["containIntrinsicSize"], &["containIntrinsicWidth", "containIntrinsicHeight"]), + "container" => Expansion::new(Split::Whole, &["container"], &["containerName", "containerType"]), + "cornerBottomLeftShape" => Expansion::new(Split::Whole, &["cornerBottomLeftShape"], &["cornerEndStartShape", "cornerEndEndShape"]), + "cornerBottomRightShape" => Expansion::new(Split::Whole, &["cornerBottomRightShape"], &["cornerEndStartShape", "cornerEndEndShape"]), + "cornerEndEndShape" => Expansion::new(Split::Whole, &["cornerEndEndShape"], &["cornerBottomLeftShape", "cornerBottomRightShape"]), + "cornerEndStartShape" => Expansion::new(Split::Whole, &["cornerEndStartShape"], &["cornerBottomLeftShape", "cornerBottomRightShape"]), + "cornerShape" => Expansion::new(Split::Whole, &["cornerShape"], &["cornerStartStartShape", "cornerStartEndShape", "cornerEndStartShape", "cornerEndEndShape", "cornerTopLeftShape", "cornerTopRightShape", "cornerBottomLeftShape", "cornerBottomRightShape"]), + "cornerStartEndShape" => Expansion::new(Split::Whole, &["cornerStartEndShape"], &["cornerTopLeftShape", "cornerTopRightShape"]), + "cornerStartStartShape" => Expansion::new(Split::Whole, &["cornerStartStartShape"], &["cornerTopLeftShape", "cornerTopRightShape"]), + "cornerTopLeftShape" => Expansion::new(Split::Whole, &["cornerTopLeftShape"], &["cornerStartStartShape", "cornerStartEndShape"]), + "cornerTopRightShape" => Expansion::new(Split::Whole, &["cornerTopRightShape"], &["cornerStartStartShape", "cornerStartEndShape"]), + "end" => Expansion::new(Split::Whole, &["insetInlineEnd"], &["left", "right"]), + "flex" => Expansion::new(Split::Whole, &["flex"], &["flexGrow", "flexShrink", "flexBasis"]), + "flexFlow" => Expansion::new(Split::Whole, &["flexFlow"], &["flexDirection", "flexWrap"]), + "font" => Expansion::new(Split::Whole, &["font"], &["fontFamily", "fontSize", "fontStretch", "fontStyle", "fontVariant", "fontVariantAlternates", "fontVariantCaps", "fontVariantEastAsian", "fontVariantEmoji", "fontVariantLigatures", "fontVariantNumeric", "fontVariantPosition", "fontWeight", "lineHeight"]), + "fontVariant" => Expansion::new(Split::Whole, &["fontVariant"], &["fontVariantAlternates", "fontVariantCaps", "fontVariantEastAsian", "fontVariantEmoji", "fontVariantLigatures", "fontVariantNumeric", "fontVariantPosition"]), + "gap" => Expansion::new(Split::Whole, &["gap"], &["rowGap", "columnGap"]), + "grid" => Expansion::new(Split::Whole, &["grid"], &["gridTemplate", "gridTemplateAreas", "gridTemplateColumns", "gridTemplateRows", "gridAutoRows", "gridAutoColumns", "gridAutoFlow"]), + "gridArea" => Expansion::new(Split::Whole, &["gridArea"], &["gridRow", "gridRowStart", "gridRowEnd", "gridColumn", "gridColumnStart", "gridColumnEnd"]), + "gridColumn" => Expansion::new(Split::Whole, &["gridColumn"], &["gridColumnStart", "gridColumnEnd"]), + "gridColumnGap" => Expansion::new(Split::Whole, &["columnGap"], &[]), + "gridGap" => Expansion::new(Split::Whole, &["gap"], &["rowGap", "columnGap"]), + "gridRow" => Expansion::new(Split::Whole, &["gridRow"], &["gridRowStart", "gridRowEnd"]), + "gridRowGap" => Expansion::new(Split::Whole, &["rowGap"], &[]), + "gridTemplate" => Expansion::new(Split::Whole, &["gridTemplate"], &["gridTemplateAreas", "gridTemplateColumns", "gridTemplateRows"]), + "inlineSize" => Expansion::new(Split::Whole, &["width"], &[]), + "inset" => Expansion::new(Split::Whole, &["inset"], &["insetInline", "insetInlineStart", "insetInlineEnd", "left", "right", "insetBlock", "top", "bottom"]), + "insetBlock" => Expansion::new(Split::Whole, &["insetBlock"], &["top", "bottom"]), + "insetBlockEnd" => Expansion::new(Split::Whole, &["bottom"], &[]), + "insetBlockStart" => Expansion::new(Split::Whole, &["top"], &[]), + "insetInline" => Expansion::new(Split::Whole, &["insetInline"], &["insetInlineStart", "insetInlineEnd", "left", "right"]), + "insetInlineEnd" => Expansion::new(Split::Whole, &["insetInlineEnd"], &["left", "right"]), + "insetInlineStart" => Expansion::new(Split::Whole, &["insetInlineStart"], &["left", "right"]), + "left" => Expansion::new(Split::Whole, &["left"], &["insetInlineStart", "insetInlineEnd"]), + "listStyle" => Expansion::new(Split::Whole, &["listStyle"], &["listStyleImage", "listStylePosition", "listStyleType"]), + "margin" => Expansion::new(Split::Whole, &["margin"], &["marginInline", "marginInlineStart", "marginLeft", "marginInlineEnd", "marginRight", "marginBlock", "marginTop", "marginBottom"]), + "marginBlock" => Expansion::new(Split::Whole, &["marginBlock"], &["marginTop", "marginBottom"]), + "marginBlockEnd" => Expansion::new(Split::Whole, &["marginBottom"], &[]), + "marginBlockStart" => Expansion::new(Split::Whole, &["marginTop"], &[]), + "marginEnd" => Expansion::new(Split::Whole, &["marginInlineEnd"], &["marginLeft", "marginRight"]), + "marginHorizontal" => Expansion::new(Split::Whole, &["marginInline"], &["marginInlineStart", "marginLeft", "marginInlineEnd", "marginRight"]), + "marginInline" => Expansion::new(Split::Whole, &["marginInline"], &["marginInlineStart", "marginLeft", "marginInlineEnd", "marginRight"]), + "marginInlineEnd" => Expansion::new(Split::Whole, &["marginInlineEnd"], &["marginLeft", "marginRight"]), + "marginInlineStart" => Expansion::new(Split::Whole, &["marginInlineStart"], &["marginLeft", "marginRight"]), + "marginLeft" => Expansion::new(Split::Whole, &["marginLeft"], &["marginInlineStart", "marginInlineEnd"]), + "marginRight" => Expansion::new(Split::Whole, &["marginRight"], &["marginInlineStart", "marginInlineEnd"]), + "marginStart" => Expansion::new(Split::Whole, &["marginInlineStart"], &["marginLeft", "marginRight"]), + "marginVertical" => Expansion::new(Split::Whole, &["marginBlock"], &["marginTop", "marginBottom"]), + "mask" => Expansion::new(Split::Whole, &["mask"], &["maskClip", "maskComposite", "maskImage", "maskMode", "maskOrigin", "maskPosition", "maskRepeat", "maskSize"]), + "maskBorder" => Expansion::new(Split::Whole, &["maskBorder"], &["maskBorderMode", "maskBorderOutset", "maskBorderRepeat", "maskBorderSlice", "maskBorderSource", "maskBorderWidth"]), + "maxBlockSize" => Expansion::new(Split::Whole, &["maxHeight"], &[]), + "maxInlineSize" => Expansion::new(Split::Whole, &["maxWidth"], &[]), + "minBlockSize" => Expansion::new(Split::Whole, &["minHeight"], &[]), + "minInlineSize" => Expansion::new(Split::Whole, &["minWidth"], &[]), + "offset" => Expansion::new(Split::Whole, &["offset"], &["offsetAnchor", "offsetDistance", "offsetPath", "offsetPosition", "offsetRotate"]), + "outline" => Expansion::new(Split::Whole, &["outline"], &["outlineColor", "outlineOffset", "outlineStyle", "outlineWidth"]), + "overflow" => Expansion::new(Split::Whole, &["overflow"], &["overflowX", "overflowY"]), + "overflowBlock" => Expansion::new(Split::Whole, &["overflowY"], &[]), + "overflowInline" => Expansion::new(Split::Whole, &["overflowX"], &[]), + "padding" => Expansion::new(Split::Whole, &["padding"], &["paddingInline", "paddingStart", "paddingLeft", "paddingEnd", "paddingRight", "paddingBlock", "paddingTop", "paddingBottom"]), + "paddingBlock" => Expansion::new(Split::Whole, &["paddingBlock"], &["paddingTop", "paddingBottom"]), + "paddingBlockEnd" => Expansion::new(Split::Whole, &["paddingBottom"], &[]), + "paddingBlockStart" => Expansion::new(Split::Whole, &["paddingTop"], &[]), + "paddingEnd" => Expansion::new(Split::Whole, &["paddingInlineEnd"], &["paddingLeft", "paddingRight"]), + "paddingHorizontal" => Expansion::new(Split::Whole, &["paddingInline"], &["paddingStart", "paddingLeft", "paddingEnd", "paddingRight"]), + "paddingInline" => Expansion::new(Split::Whole, &["paddingInline"], &["paddingStart", "paddingLeft", "paddingEnd", "paddingRight"]), + "paddingInlineEnd" => Expansion::new(Split::Whole, &["paddingInlineEnd"], &["paddingLeft", "paddingRight"]), + "paddingInlineStart" => Expansion::new(Split::Whole, &["paddingInlineStart"], &["paddingLeft", "paddingRight"]), + "paddingLeft" => Expansion::new(Split::Whole, &["paddingLeft"], &["paddingInlineStart", "paddingInlineEnd"]), + "paddingRight" => Expansion::new(Split::Whole, &["paddingRight"], &["paddingInlineStart", "paddingInlineEnd"]), + "paddingStart" => Expansion::new(Split::Whole, &["paddingInlineStart"], &["paddingLeft", "paddingRight"]), + "paddingVertical" => Expansion::new(Split::Whole, &["paddingBlock"], &["paddingTop", "paddingBottom"]), + "placeContent" => Expansion::new(Split::Whole, &["placeContent"], &["alignContent", "justifyContent"]), + "placeItems" => Expansion::new(Split::Whole, &["placeItems"], &["alignItems", "justifyItems"]), + "placeSelf" => Expansion::new(Split::Whole, &["placeSelf"], &["alignSelf", "justifySelf"]), + "right" => Expansion::new(Split::Whole, &["right"], &["insetInlineStart", "insetInlineEnd"]), + "scrollMargin" => Expansion::new(Split::Whole, &["scrollMargin"], &["scrollMarginBlock", "scrollMarginTop", "scrollMarginBottom", "scrollMarginInline", "scrollMarginInlineStart", "scrollMarginInlineEnd", "scrollMarginLeft", "scrollMarginRight"]), + "scrollMarginBlock" => Expansion::new(Split::Whole, &["scrollMarginBlock"], &["scrollMarginTop", "scrollMarginBottom"]), + "scrollMarginBlockEnd" => Expansion::new(Split::Whole, &["scrollMarginBottom"], &[]), + "scrollMarginBlockStart" => Expansion::new(Split::Whole, &["scrollMarginTop"], &[]), + "scrollMarginInline" => Expansion::new(Split::Whole, &["scrollMarginInline"], &["scrollMarginInlineStart", "scrollMarginInlineEnd", "scrollMarginLeft", "scrollMarginRight"]), + "scrollMarginInlineEnd" => Expansion::new(Split::Whole, &["scrollMarginInlineEnd"], &["scrollMarginLeft", "scrollMarginRight"]), + "scrollMarginInlineStart" => Expansion::new(Split::Whole, &["scrollMarginInlineStart"], &["scrollMarginLeft", "scrollMarginRight"]), + "scrollMarginLeft" => Expansion::new(Split::Whole, &["scrollMarginLeft"], &["scrollMarginInlineStart", "scrollMarginInlineEnd"]), + "scrollMarginRight" => Expansion::new(Split::Whole, &["scrollMarginRight"], &["scrollMarginInlineStart", "scrollMarginInlineEnd"]), + "scrollPadding" => Expansion::new(Split::Whole, &["scrollPadding"], &["scrollPaddingBlock", "scrollPaddingTop", "scrollPaddingBottom", "scrollPaddingInline", "scrollPaddingInlineStart", "scrollPaddingInlineEnd", "scrollPaddingLeft", "scrollPaddingRight"]), + "scrollPaddingBlock" => Expansion::new(Split::Whole, &["scrollPaddingBlock"], &["scrollPaddingTop", "scrollPaddingBottom"]), + "scrollPaddingInline" => Expansion::new(Split::Whole, &["scrollPaddingInline"], &["scrollPaddingInlineStart", "scrollPaddingInlineEnd", "scrollPaddingLeft", "scrollPaddingRight"]), + "scrollPaddingInlineEnd" => Expansion::new(Split::Whole, &["scrollPaddingInlineEnd"], &["scrollPaddingLeft", "scrollPaddingRight"]), + "scrollPaddingInlineStart" => Expansion::new(Split::Whole, &["scrollPaddingInlineStart"], &["scrollPaddingLeft", "scrollPaddingRight"]), + "scrollPaddingLeft" => Expansion::new(Split::Whole, &["scrollPaddingLeft"], &["scrollPaddingInlineStart", "scrollPaddingInlineEnd"]), + "scrollPaddingRight" => Expansion::new(Split::Whole, &["scrollPaddingRight"], &["scrollPaddingInlineStart", "scrollPaddingInlineEnd"]), + "scrollSnapType" => Expansion::new(Split::Whole, &["scrollSnapType"], &["scrollSnapTypeX", "scrollSnapTypeY"]), + "scrollTimeline" => Expansion::new(Split::Whole, &["scrollTimeline"], &["scrollTimelineName", "scrollTimelineAxis"]), + "start" => Expansion::new(Split::Whole, &["insetInlineStart"], &["left", "right"]), + "textDecoration" => Expansion::new(Split::Whole, &["textDecoration"], &["textDecorationColor", "textDecorationLine", "textDecorationStyle", "textDecorationThickness"]), + "textEmphasis" => Expansion::new(Split::Whole, &["textEmphasis"], &["textEmphasisColor", "textEmphasisStyle"]), + "transition" => Expansion::new(Split::Whole, &["transition"], &["transitionBehavior", "transitionDelay", "transitionDuration", "transitionProperty", "transitionTimingFunction"]), +}; + +/// `legacy-expand-shorthands`: a key spreads its value over longhands +pub(super) static LEGACY_EXPAND_SHORTHANDS: phf::Map<&'static str, Expansion> = phf::phf_map! { + "containIntrinsicSize" => Expansion::new(Split::ContainIntrinsicSize, &["containIntrinsicWidth", "containIntrinsicHeight"], &[]), + "listStyle" => Expansion::new(Split::ListStyle, &["listStyleType", "listStylePosition", "listStyleImage"], &[]), + "blockSize" => Expansion::new(Split::Whole, &["height"], &[]), + "border" => Expansion::new(Split::Whole, &["borderTop", "borderInlineEnd", "borderBottom", "borderInlineStart"], &[]), + "borderBlockColor" => Expansion::new(Split::Whole, &["borderTopColor", "borderBottomColor"], &[]), + "borderBlockEndColor" => Expansion::new(Split::Whole, &["borderBottomColor"], &[]), + "borderBlockEndStyle" => Expansion::new(Split::Whole, &["borderBottomStyle"], &[]), + "borderBlockEndWidth" => Expansion::new(Split::Whole, &["borderBottomWidth"], &[]), + "borderBlockStartColor" => Expansion::new(Split::Whole, &["borderTopColor"], &[]), + "borderBlockStartStyle" => Expansion::new(Split::Whole, &["borderTopStyle"], &[]), + "borderBlockStartWidth" => Expansion::new(Split::Whole, &["borderTopWidth"], &[]), + "borderBlockStyle" => Expansion::new(Split::Whole, &["borderTopStyle", "borderBottomStyle"], &[]), + "borderBlockWidth" => Expansion::new(Split::Whole, &["borderTopWidth", "borderBottomWidth"], &[]), + "borderBottomEndRadius" => Expansion::new(Split::Whole, &["borderEndEndRadius"], &[]), + "borderBottomStartRadius" => Expansion::new(Split::Whole, &["borderEndStartRadius"], &[]), + "borderColor" => Expansion::new(Split::Box, &["borderTopColor", "borderInlineEndColor", "borderBottomColor", "borderInlineStartColor"], &[]), + "borderEnd" => Expansion::new(Split::Whole, &["borderInlineEnd"], &[]), + "borderHorizontal" => Expansion::new(Split::Whole, &["borderInlineStart", "borderInlineEnd"], &[]), + "borderHorizontalColor" => Expansion::new(Split::Whole, &["borderInlineStartColor", "borderInlineEndColor"], &[]), + "borderHorizontalStyle" => Expansion::new(Split::Whole, &["borderInlineStartStyle", "borderInlineEndStyle"], &[]), + "borderHorizontalWidth" => Expansion::new(Split::Whole, &["borderInlineStartWidth", "borderInlineEndWidth"], &[]), + "borderInlineColor" => Expansion::new(Split::Whole, &["borderInlineStartColor", "borderInlineEndColor"], &[]), + "borderInlineStyle" => Expansion::new(Split::Whole, &["borderInlineStartStyle", "borderInlineEndStyle"], &[]), + "borderInlineWidth" => Expansion::new(Split::Whole, &["borderInlineStartWidth", "borderInlineEndWidth"], &[]), + "borderRadius" => Expansion::new(Split::Box, &["borderStartStartRadius", "borderStartEndRadius", "borderEndEndRadius", "borderEndStartRadius"], &[]), + "borderStart" => Expansion::new(Split::Whole, &["borderInlineStart"], &[]), + "borderStyle" => Expansion::new(Split::Box, &["borderTopStyle", "borderInlineEndStyle", "borderBottomStyle", "borderInlineStartStyle"], &[]), + "borderTopEndRadius" => Expansion::new(Split::Whole, &["borderStartEndRadius"], &[]), + "borderTopStartRadius" => Expansion::new(Split::Whole, &["borderStartStartRadius"], &[]), + "borderVertical" => Expansion::new(Split::Whole, &["borderTop", "borderBottom"], &[]), + "borderVerticalColor" => Expansion::new(Split::Whole, &["borderTopColor", "borderBottomColor"], &[]), + "borderVerticalStyle" => Expansion::new(Split::Whole, &["borderTopStyle", "borderBottomStyle"], &[]), + "borderVerticalWidth" => Expansion::new(Split::Whole, &["borderTopWidth", "borderBottomWidth"], &[]), + "borderWidth" => Expansion::new(Split::Box, &["borderTopWidth", "borderInlineEndWidth", "borderBottomWidth", "borderInlineStartWidth"], &[]), + "end" => Expansion::new(Split::Whole, &["insetInlineEnd"], &["left", "right"]), + "gap" => Expansion::new(Split::Pair, &["rowGap", "columnGap"], &[]), + "gridColumnGap" => Expansion::new(Split::Whole, &["columnGap"], &[]), + "gridGap" => Expansion::new(Split::Pair, &["rowGap", "columnGap"], &[]), + "gridRowGap" => Expansion::new(Split::Whole, &["rowGap"], &[]), + "inlineSize" => Expansion::new(Split::Whole, &["width"], &[]), + "inset" => Expansion::new(Split::Box, &["top", "insetInlineEnd", "bottom", "insetInlineStart"], &[]), + "insetBlock" => Expansion::new(Split::Pair, &["top", "bottom"], &[]), + "insetBlockEnd" => Expansion::new(Split::Whole, &["bottom"], &[]), + "insetBlockStart" => Expansion::new(Split::Whole, &["top"], &[]), + "insetInline" => Expansion::new(Split::Pair, &["insetInlineStart", "insetInlineEnd"], &["left", "right"]), + "insetInlineEnd" => Expansion::new(Split::Whole, &["insetInlineEnd"], &["left", "right"]), + "insetInlineStart" => Expansion::new(Split::Whole, &["insetInlineStart"], &["left", "right"]), + "left" => Expansion::new(Split::Whole, &["left"], &["insetInlineStart", "insetInlineEnd"]), + "margin" => Expansion::new(Split::Box, &["marginTop", "marginInlineEnd", "marginBottom", "marginInlineStart"], &[]), + "marginBlock" => Expansion::new(Split::Pair, &["marginTop", "marginBottom"], &[]), + "marginBlockEnd" => Expansion::new(Split::Whole, &["marginBottom"], &[]), + "marginBlockStart" => Expansion::new(Split::Whole, &["marginTop"], &[]), + "marginEnd" => Expansion::new(Split::Whole, &["marginInlineEnd"], &["marginLeft", "marginRight"]), + "marginHorizontal" => Expansion::new(Split::Pair, &["marginInlineStart", "marginInlineEnd"], &["marginLeft", "marginRight"]), + "marginInline" => Expansion::new(Split::Pair, &["marginInlineStart", "marginInlineEnd"], &["marginLeft", "marginRight"]), + "marginLeft" => Expansion::new(Split::Whole, &["marginLeft"], &["marginInlineStart", "marginInlineEnd"]), + "marginRight" => Expansion::new(Split::Whole, &["marginRight"], &["marginInlineStart", "marginInlineEnd"]), + "marginStart" => Expansion::new(Split::Whole, &["marginInlineStart"], &["marginLeft", "marginRight"]), + "marginVertical" => Expansion::new(Split::Pair, &["marginTop", "marginBottom"], &[]), + "maxBlockSize" => Expansion::new(Split::Whole, &["maxHeight"], &[]), + "maxInlineSize" => Expansion::new(Split::Whole, &["maxWidth"], &[]), + "minBlockSize" => Expansion::new(Split::Whole, &["minHeight"], &[]), + "minInlineSize" => Expansion::new(Split::Whole, &["minWidth"], &[]), + "overflow" => Expansion::new(Split::Pair, &["overflowX", "overflowY"], &[]), + "overflowBlock" => Expansion::new(Split::Whole, &["overflowY"], &[]), + "overflowInline" => Expansion::new(Split::Whole, &["overflowX"], &[]), + "padding" => Expansion::new(Split::Box, &["paddingTop", "paddingInlineEnd", "paddingBottom", "paddingInlineStart"], &[]), + "paddingBlock" => Expansion::new(Split::Pair, &["paddingTop", "paddingBottom"], &[]), + "paddingBlockEnd" => Expansion::new(Split::Whole, &["paddingBottom"], &[]), + "paddingBlockStart" => Expansion::new(Split::Whole, &["paddingTop"], &[]), + "paddingEnd" => Expansion::new(Split::Whole, &["paddingInlineEnd"], &["paddingLeft", "paddingRight"]), + "paddingHorizontal" => Expansion::new(Split::Pair, &["paddingInlineStart", "paddingInlineEnd"], &["paddingLeft", "paddingRight"]), + "paddingInline" => Expansion::new(Split::Pair, &["paddingInlineStart", "paddingInlineEnd"], &["paddingLeft", "paddingRight"]), + "paddingLeft" => Expansion::new(Split::Whole, &["paddingLeft"], &["paddingInlineStart", "paddingInlineEnd"]), + "paddingRight" => Expansion::new(Split::Whole, &["paddingRight"], &["paddingInlineStart", "paddingInlineEnd"]), + "paddingStart" => Expansion::new(Split::Whole, &["paddingInlineStart"], &["paddingLeft", "paddingRight"]), + "paddingVertical" => Expansion::new(Split::Pair, &["paddingTop", "paddingBottom"], &[]), + "right" => Expansion::new(Split::Whole, &["right"], &["insetInlineStart", "insetInlineEnd"]), + "scrollMarginBlockEnd" => Expansion::new(Split::Whole, &["scrollMarginBottom"], &[]), + "scrollMarginBlockStart" => Expansion::new(Split::Whole, &["scrollMarginTop"], &[]), + "start" => Expansion::new(Split::Whole, &["insetInlineStart"], &["left", "right"]), +}; diff --git a/libs/extractor/src/stylex_resolution_tests.rs b/libs/extractor/src/stylex_resolution_tests.rs new file mode 100644 index 000000000..dca88f863 --- /dev/null +++ b/libs/extractor/src/stylex_resolution_tests.rs @@ -0,0 +1,228 @@ +use super::*; +use rstest::rstest; + +fn applied(policy: StyleResolution, key: &str, value: Option<&str>) -> Vec { + expansion(policy, key) + .map(|expansion| expansion.apply(value)) + .and_then(Result::ok) + .unwrap_or_default() +} + +fn set(key: &'static str, value: &str) -> ExpandedKey { + (key, Some(value.to_string())) +} + +#[rstest] +#[case(StyleResolution::PropertySpecificity, "padding")] +#[case(StyleResolution::ApplicationOrder, "color")] +#[case(StyleResolution::ApplicationOrder, "padding-top")] +#[case(StyleResolution::LegacyExpandShorthands, "float")] +#[case(StyleResolution::LegacyExpandShorthands, "clear")] +#[case(StyleResolution::LegacyExpandShorthands, "flex")] +fn keys_without_an_expansion_stay(#[case] policy: StyleResolution, #[case] key: &str) { + assert!(expansion(policy, key).is_none()); +} + +#[test] +fn application_order_keeps_the_value_and_resets_what_it_covers() { + assert_eq!( + applied( + StyleResolution::ApplicationOrder, + "padding", + Some("1px 2px") + ), + vec![ + set("padding", "1px 2px"), + ("paddingInline", None), + ("paddingStart", None), + ("paddingLeft", None), + ("paddingEnd", None), + ("paddingRight", None), + ("paddingBlock", None), + ("paddingTop", None), + ("paddingBottom", None), + ] + ); + assert_eq!( + applied( + StyleResolution::ApplicationOrder, + "marginStart", + Some("4px") + ), + vec![ + set("marginInlineStart", "4px"), + ("marginLeft", None), + ("marginRight", None) + ] + ); + assert_eq!( + applied(StyleResolution::ApplicationOrder, "blockSize", None), + vec![("height", None)] + ); +} + +#[test] +fn application_order_rejects_all() { + assert_eq!( + expansion(StyleResolution::ApplicationOrder, "all").map(|e| e.apply(Some("unset"))), + Some(Err("all is not supported".to_string())) + ); +} + +#[rstest] +#[case("margin", "1px", ["1px", "1px", "1px", "1px"])] +#[case("margin", "1px 2px", ["1px", "2px", "1px", "2px"])] +#[case("margin", "1px 2px 3px", ["1px", "2px", "3px", "2px"])] +#[case("margin", "1px 2px 3px 4px 5px", ["1px", "2px", "3px", "4px"])] +#[case("padding", "1px 2px !important", ["1px !important", "2px !important", "1px !important", "2px !important"])] +#[case("borderColor", "rgb(0, 0, 0) red", ["rgb(0, 0, 0)", "red", "rgb(0, 0, 0)", "red"])] +fn legacy_spreads_a_box_over_four_sides( + #[case] key: &str, + #[case] value: &str, + #[case] sides: [&str; 4], +) { + let values: Vec> = + applied(StyleResolution::LegacyExpandShorthands, key, Some(value)) + .into_iter() + .map(|(_, value)| value) + .collect(); + assert_eq!(values, sides.map(|side| Some(side.to_string())).to_vec()); +} + +#[test] +fn legacy_keeps_logical_sides_and_resets_physical_ones() { + assert_eq!( + applied( + StyleResolution::LegacyExpandShorthands, + "padding", + Some("1px 2px 3px 4px") + ), + vec![ + set("paddingTop", "1px"), + set("paddingInlineEnd", "2px"), + set("paddingBottom", "3px"), + set("paddingInlineStart", "4px"), + ] + ); + assert_eq!( + applied( + StyleResolution::LegacyExpandShorthands, + "marginInline", + Some("1px 2px") + ), + vec![ + set("marginInlineStart", "1px"), + set("marginInlineEnd", "2px"), + ("marginLeft", None), + ("marginRight", None), + ] + ); + assert_eq!( + applied(StyleResolution::LegacyExpandShorthands, "gap", Some("1px")), + vec![set("rowGap", "1px"), set("columnGap", "1px")] + ); + assert_eq!( + applied( + StyleResolution::LegacyExpandShorthands, + "border", + Some("1px solid red") + ), + vec![ + set("borderTop", "1px solid red"), + set("borderInlineEnd", "1px solid red"), + set("borderBottom", "1px solid red"), + set("borderInlineStart", "1px solid red"), + ] + ); + assert_eq!( + applied(StyleResolution::LegacyExpandShorthands, "overflow", None), + vec![("overflowX", None), ("overflowY", None)] + ); +} + +#[rstest] +#[case("auto 10px", ["auto 10px", "auto 10px"])] +#[case("10px auto 20px", ["10px", "auto 20px"])] +#[case("10px 20px", ["10px", "20px"])] +#[case("auto", ["auto", "auto"])] +fn legacy_contain_intrinsic_size_joins_auto(#[case] value: &str, #[case] sizes: [&str; 2]) { + assert_eq!( + applied( + StyleResolution::LegacyExpandShorthands, + "containIntrinsicSize", + Some(value) + ), + vec![ + set("containIntrinsicWidth", sizes[0]), + set("containIntrinsicHeight", sizes[1]), + ] + ); +} + +#[rstest] +#[case("square inside", [Some("square"), Some("inside"), None])] +#[case("inherit", [Some("inherit"), Some("inherit"), Some("inherit")])] +#[case("none url(a.png)", [Some("none"), None, Some("url(a.png)")])] +#[case("disc none", [Some("disc"), None, Some("none")])] +#[case("'-' outside", [Some("'-'"), Some("outside"), None])] +#[case("\"x\"", [Some("\"x\""), None, None])] +#[case("", [None, None, Some("")])] +fn legacy_list_style_sorts_its_parts(#[case] value: &str, #[case] parts: [Option<&str>; 3]) { + assert_eq!( + applied( + StyleResolution::LegacyExpandShorthands, + "listStyle", + Some(value) + ), + vec![ + ("listStyleType", parts[0].map(str::to_string)), + ("listStylePosition", parts[1].map(str::to_string)), + ("listStyleImage", parts[2].map(str::to_string)), + ] + ); +} + +#[rstest] +#[case("square inherit")] +#[case("var(--x) inside")] +#[case("inside outside")] +#[case("square disc")] +#[case("url(a.png) url(b.png)")] +fn legacy_list_style_rejects_what_stylex_rejects(#[case] value: &str) { + assert_eq!( + expansion(StyleResolution::LegacyExpandShorthands, "listStyle") + .map(|e| e.apply(Some(value))), + Some(Err(format!("invalid \"listStyle\" value of {value:?}"))) + ); +} + +#[rstest] +#[case("1px 2px", &["1px", "2px"])] +#[case(" a,b/c ", &["a", "b", "c"])] +#[case("calc(1px + 2px) 3px", &["calc(1px + 2px)", "3px"])] +#[case("\"a b\" 'c d'", &["\"a b\"", "'c d'"])] +#[case("f(g(1 2)) x)", &["f(g(1 2))", "x)"])] +#[case("!important", &["!important"])] +#[case("1px !IMPORTANT", &["1px !important"])] +#[case("", &[""])] +#[case(" ", &[""])] +fn values_split_as_stylex_splits_them(#[case] value: &str, #[case] parts: &[&str]) { + assert_eq!(split_value(value), parts); +} + +#[test] +fn tables_name_camel_case_keys() { + for table in [ + &tables::APPLICATION_ORDER, + &tables::LEGACY_EXPAND_SHORTHANDS, + ] { + for (key, expansion) in table.entries() { + for name in std::iter::once(key) + .chain(expansion.targets) + .chain(expansion.resets) + { + assert!(!name.contains('-'), "{name}"); + } + } + } +} diff --git a/packages/bun-plugin/src/__tests__/plugin.test.ts b/packages/bun-plugin/src/__tests__/plugin.test.ts index 6e2ea54a2..15abd50fe 100644 --- a/packages/bun-plugin/src/__tests__/plugin.test.ts +++ b/packages/bun-plugin/src/__tests__/plugin.test.ts @@ -76,6 +76,35 @@ describe('shorthand creation boundary', () => { selection.mockImplementation(selectCompiler) } }) + + it('reads StyleX under the styleResolution it is given when registered', async () => { + const resolution = spyOn(wasm, 'setStylexStyleResolution') + try { + await register({ + engine: 'wasm', + stylex: { styleResolution: 'application-order' }, + }) + expect(resolution.mock.calls).toEqual([['application-order']]) + } finally { + resolution.mockRestore() + wasm.setStylexStyleResolution(null) + } + }) + + it('rejects an unknown styleResolution before selecting a compiler', () => { + const selection = spyOn(pluginUtils, 'loadCompiler') + try { + expect(() => + Reflect.apply(register, undefined, [ + { stylex: { styleResolution: 'last-wins' } }, + ]), + ).toThrow(pluginUtils.StylexConfigError) + expect(selection).not.toHaveBeenCalled() + } finally { + selection.mockRestore() + selection.mockImplementation(selectCompiler) + } + }) }) const root = fs.mkdtempSync(join(tmpdir(), 'devup-ui-bun-hooks-')) diff --git a/packages/bun-plugin/src/plugin.ts b/packages/bun-plugin/src/plugin.ts index 284772623..7b0a95646 100644 --- a/packages/bun-plugin/src/plugin.ts +++ b/packages/bun-plugin/src/plugin.ts @@ -17,8 +17,11 @@ import { loadDevupConfig, mergeImportAliases, normalizeShorthands, + normalizeStylexOptions, readJsxImportSource, seedFileNumbers, + type StylexOptions, + type StylexStyleResolution, tailwindCssFiles, withTailwindCss, } from '@devup-ui/plugin-utils' @@ -45,6 +48,8 @@ export interface DevupUIBunPluginOptions { /** Native by default. Select WASM explicitly without automatic fallback. */ engine?: DevupEngine shorthands?: CustomShorthands + /** How code written against StyleX's API is read. */ + stylex?: StylexOptions /** * Readable class names. Defaults to `true` under the Bun runtime (tests) and * `false` in `Bun.build`. @@ -87,9 +92,11 @@ async function writeDataFiles(compiler: DevupCompiler): Promise { async function initialize( compiler: DevupCompiler, shorthands: Record, + styleResolution: StylexStyleResolution, watchTailwindCss: ReturnType, ) { compiler.registerShorthands(shorthands) + compiler.setStylexStyleResolution(styleResolution) compiler.setPrefix(null) compiler.setModuleResolver(createModuleResolver()) if (!existsSync(distDir)) await mkdir(distDir, { recursive: true }) @@ -174,6 +181,7 @@ async function loadSourceFile( */ function DevupUI(options: DevupUIBunPluginOptions = {}) { const shorthands = normalizeShorthands(options.shorthands ?? {}) + const styleResolution = normalizeStylexOptions(options.stylex) const compiler = loadCompiler(options.engine) const watchTailwindCss = createTailwindWatcher( writeDataFiles.bind(undefined, compiler), @@ -188,7 +196,7 @@ function DevupUI(options: DevupUIBunPluginOptions = {}) { // this process left in the engine const endBuild = beginBuild(compiler) build.onEnd?.(endBuild) - await initialize(compiler, shorthands, watchTailwindCss) + await initialize(compiler, shorthands, styleResolution, watchTailwindCss) const debug = options.debug ?? !bundling compiler.setDebug(debug) const slots = createSharedSlotReservation(compiler) diff --git a/packages/next-plugin/src/__tests__/plugin.test.ts b/packages/next-plugin/src/__tests__/plugin.test.ts index 639d7cfe3..6027e8c30 100644 --- a/packages/next-plugin/src/__tests__/plugin.test.ts +++ b/packages/next-plugin/src/__tests__/plugin.test.ts @@ -235,6 +235,34 @@ describe('DevupUINextPlugin', () => { } }) + it('reads StyleX under the styleResolution a Turbopack plugin is given', () => { + process.env.TURBOPACK = '1' + const resolution = spyOn(wasm, 'setStylexStyleResolution') + try { + DevupUI({}, { stylex: { styleResolution: 'legacy-expand-shorthands' } }) + expect(resolution.mock.calls).toEqual([['legacy-expand-shorthands']]) + } finally { + resolution.mockRestore() + wasm.setStylexStyleResolution(null) + } + }) + + it.each(['1', undefined])( + 'rejects an unknown styleResolution before setup in mode %s', + (mode) => { + if (mode === undefined) delete process.env.TURBOPACK + else process.env.TURBOPACK = mode + expect(() => + Reflect.apply(DevupUI, undefined, [ + {}, + { stylex: { styleResolution: 'last-wins' } }, + ]), + ).toThrow(importGraphModule.StylexConfigError) + expect(startCoordinatorSpy).not.toHaveBeenCalled() + expect(devupUIWebpackPluginSpy).not.toHaveBeenCalled() + }, + ) + it('rejects a typo before reading an available production handoff', () => { process.env.TURBOPACK = '1' setNodeEnv('production') diff --git a/packages/next-plugin/src/plugin.ts b/packages/next-plugin/src/plugin.ts index aa92f663e..1d3f457b9 100644 --- a/packages/next-plugin/src/plugin.ts +++ b/packages/next-plugin/src/plugin.ts @@ -21,6 +21,7 @@ import { loadDevupConfigSync, mergeImportAliases, normalizeShorthands, + normalizeStylexOptions, readJsxImportSource, seedFileNumbers, type StaticImportGraph, @@ -146,6 +147,7 @@ export function DevupUI( options: DevupUINextPluginOptions = {}, ): NextConfig { const normalizedShorthands = normalizeShorthands(options.shorthands ?? {}) + const styleResolution = normalizeStylexOptions(options.stylex) const engine = options.engine === undefined ? 'native' : options.engine const pluginStartedAt = profileStart() const isTurbo = @@ -205,6 +207,7 @@ export function DevupUI( shorthands: normalizedShorthands, singleCss, sourceMap, + styleResolution, }) const cachedSetup = watch ? undefined @@ -260,9 +263,11 @@ export function DevupUI( registerShorthands, registerTheme, setPrefix, + setStylexStyleResolution, } = wasm registerShorthands(normalizedShorthands) + setStylexStyleResolution(styleResolution) setPrefix(prefix ?? null) diff --git a/packages/plugin-utils/src/__tests__/compiler-types.test.ts b/packages/plugin-utils/src/__tests__/compiler-types.test.ts index 10e4921eb..c6b757714 100644 --- a/packages/plugin-utils/src/__tests__/compiler-types.test.ts +++ b/packages/plugin-utils/src/__tests__/compiler-types.test.ts @@ -78,7 +78,7 @@ describe('compiler structural types', () => { Object.keys(compiler).filter( (key) => key !== 'Output' && key !== 'default', ), - ).toHaveLength(28) + ).toHaveLength(29) } finally { compiler.resetStateForTesting() } diff --git a/packages/plugin-utils/src/__tests__/stylex-options.test.ts b/packages/plugin-utils/src/__tests__/stylex-options.test.ts new file mode 100644 index 000000000..d5e79528f --- /dev/null +++ b/packages/plugin-utils/src/__tests__/stylex-options.test.ts @@ -0,0 +1,52 @@ +import { describe, expect, it } from 'bun:test' + +import { + normalizeStylexOptions, + STYLEX_STYLE_RESOLUTIONS, + StylexConfigError, +} from '../index' + +describe('normalizeStylexOptions', () => { + it('defaults to property-specificity', () => { + expect(normalizeStylexOptions(undefined)).toBe('property-specificity') + expect(normalizeStylexOptions({})).toBe('property-specificity') + expect(normalizeStylexOptions({ styleResolution: undefined })).toBe( + 'property-specificity', + ) + }) + + it.each(STYLEX_STYLE_RESOLUTIONS)('accepts %s', (styleResolution) => { + expect(normalizeStylexOptions({ styleResolution })).toBe(styleResolution) + }) + + it.each([ + ['last-wins', 'got "last-wins"'], + ['Application-Order', 'got "Application-Order"'], + [null, 'got null'], + [1, 'got number'], + ])('rejects the styleResolution %p', (styleResolution, got) => { + const error = (() => { + try { + normalizeStylexOptions({ styleResolution }) + } catch (error) { + return error + } + })() + expect(error).toBeInstanceOf(StylexConfigError) + expect(error).toMatchObject({ + name: 'StylexConfigError', + path: 'stylex.styleResolution', + value: styleResolution, + message: `devup-ui option stylex.styleResolution must be one of 'property-specificity', 'application-order', 'legacy-expand-shorthands', ${got}`, + }) + }) + + it.each([null, 'application-order', ['application-order']])( + 'rejects a stylex option that is not an object: %p', + (stylex) => { + expect(() => normalizeStylexOptions(stylex)).toThrow( + /^devup-ui option stylex must be an object, got /, + ) + }, + ) +}) diff --git a/packages/plugin-utils/src/__tests__/wasm-abi.test.ts b/packages/plugin-utils/src/__tests__/wasm-abi.test.ts index 2edae3e78..e6f577edf 100644 --- a/packages/plugin-utils/src/__tests__/wasm-abi.test.ts +++ b/packages/plugin-utils/src/__tests__/wasm-abi.test.ts @@ -70,6 +70,7 @@ describe('@devup-ui/wasm exports', () => { 'setDebug', 'setModuleResolver', 'setPrefix', + 'setStylexStyleResolution', ]) }) }) @@ -142,6 +143,23 @@ describe('@devup-ui/wasm extraction', () => { wasm.setPrefix(null) expect(wasm.getPrefix()).toBeUndefined() }) + + it('reads stylex.create() under the StyleX styleResolution it is given', () => { + const source = `import * as stylex from '@stylexjs/stylex' +const s = stylex.create({ top: { paddingTop: '1px' }, pad: { padding: '2px' } }) +export const a = stylex.props(s.top, s.pad)` + const classes = () => + /className: "([^"]*)"/.exec(extract(source).code)?.[1].split(' ').length + wasm.setDebug(false) + expect(classes()).toBe(2) + wasm.setStylexStyleResolution('application-order') + expect(classes()).toBe(1) + expect(() => wasm.setStylexStyleResolution('last-wins')).toThrow( + 'stylex.styleResolution must be', + ) + wasm.setStylexStyleResolution(null) + expect(classes()).toBe(2) + }) }) describe('@devup-ui/wasm theme', () => { diff --git a/packages/plugin-utils/src/index.ts b/packages/plugin-utils/src/index.ts index bfc7b1e1b..1415fece0 100644 --- a/packages/plugin-utils/src/index.ts +++ b/packages/plugin-utils/src/index.ts @@ -76,6 +76,13 @@ export { type StateWriter, writeFileAtomically, } from './state-writer' +export { + normalizeStylexOptions, + STYLEX_STYLE_RESOLUTIONS, + StylexConfigError, + type StylexOptions, + type StylexStyleResolution, +} from './stylex-options' export { findTailwindCss, TAILWIND_CSS_CANDIDATES, diff --git a/packages/plugin-utils/src/shared.ts b/packages/plugin-utils/src/shared.ts index 20b7aac0e..4c9ee4ac4 100644 --- a/packages/plugin-utils/src/shared.ts +++ b/packages/plugin-utils/src/shared.ts @@ -1,4 +1,5 @@ import type { DevupEngine } from './compiler-types' +import type { StylexOptions } from './stylex-options' import type { CustomShorthands, ImportAliases } from './types' /** @@ -107,4 +108,6 @@ export interface DevupUIBasePluginOptions { importAliases?: ImportAliases /** Build-time aliases that expand one style prop into multiple CSS properties. */ shorthands?: CustomShorthands + /** How code written against StyleX's API is read. */ + stylex?: StylexOptions } diff --git a/packages/plugin-utils/src/stylex-options.ts b/packages/plugin-utils/src/stylex-options.ts new file mode 100644 index 000000000..e2f755532 --- /dev/null +++ b/packages/plugin-utils/src/stylex-options.ts @@ -0,0 +1,52 @@ +/** StyleX's `styleResolution`: how a shorthand and its longhands compete. */ +export const STYLEX_STYLE_RESOLUTIONS = [ + 'property-specificity', + 'application-order', + 'legacy-expand-shorthands', +] as const + +export type StylexStyleResolution = (typeof STYLEX_STYLE_RESOLUTIONS)[number] + +/** Options for code written against StyleX's API. */ +export interface StylexOptions { + /** + * How `stylex.create()` resolves a shorthand against its longhands, as the + * StyleX babel plugin option of the same name (default + * `'property-specificity'`). Devup's own APIs ignore it. + */ + styleResolution?: StylexStyleResolution +} + +export class StylexConfigError extends TypeError { + readonly name = 'StylexConfigError' + + constructor( + readonly path: string, + readonly value: unknown, + requirement: string, + ) { + super( + `devup-ui option ${path} ${requirement}, got ${typeof value === 'string' ? JSON.stringify(value) : value === null ? 'null' : typeof value}`, + ) + } +} + +function isStyleResolution(value: unknown): value is StylexStyleResolution { + return STYLEX_STYLE_RESOLUTIONS.some((resolution) => resolution === value) +} + +/** The `styleResolution` the `stylex` option names, or a clear config error. */ +export function normalizeStylexOptions(input: unknown): StylexStyleResolution { + if (input === undefined) return 'property-specificity' + if (typeof input !== 'object' || input === null || Array.isArray(input)) + throw new StylexConfigError('stylex', input, 'must be an object') + const styleResolution: unknown = Reflect.get(input, 'styleResolution') + if (styleResolution === undefined) return 'property-specificity' + if (!isStyleResolution(styleResolution)) + throw new StylexConfigError( + 'stylex.styleResolution', + styleResolution, + `must be one of ${STYLEX_STYLE_RESOLUTIONS.map((resolution) => `'${resolution}'`).join(', ')}`, + ) + return styleResolution +} diff --git a/packages/rsbuild-plugin/src/__tests__/plugin.test.ts b/packages/rsbuild-plugin/src/__tests__/plugin.test.ts index 15afbd3ad..8a6d26661 100644 --- a/packages/rsbuild-plugin/src/__tests__/plugin.test.ts +++ b/packages/rsbuild-plugin/src/__tests__/plugin.test.ts @@ -100,6 +100,24 @@ describe('shorthand creation boundary', () => { registration.mockRestore() } }) + + it('reads StyleX under the styleResolution it is given, the default otherwise', () => { + using resolution = spyOn(wasm, 'setStylexStyleResolution') + DevupUI({ stylex: { styleResolution: 'legacy-expand-shorthands' } }) + DevupUI() + expect(resolution.mock.calls).toEqual([ + ['legacy-expand-shorthands'], + ['property-specificity'], + ]) + }) + + it('rejects an unknown styleResolution before selecting a compiler', () => { + using selection = spyOn(pluginUtils, 'loadCompiler') + expect(() => + Reflect.apply(DevupUI, undefined, [{ stylex: { styleResolution: 1 } }]), + ).toThrow(pluginUtils.StylexConfigError) + expect(selection).not.toHaveBeenCalled() + }) }) type CodeExtractResult = pluginUtils.DevupCompilerOutput diff --git a/packages/rsbuild-plugin/src/plugin.ts b/packages/rsbuild-plugin/src/plugin.ts index 91dae66c8..0653f6da5 100644 --- a/packages/rsbuild-plugin/src/plugin.ts +++ b/packages/rsbuild-plugin/src/plugin.ts @@ -21,6 +21,7 @@ import { loadDevupConfig, mergeImportAliases, normalizeShorthands, + normalizeStylexOptions, planAtomHoist, readJsxImportSource, tailwindCssFiles, @@ -34,7 +35,7 @@ const PLUGIN_NAME = 'devup-ui-rsbuild-plugin' export interface DevupUIRsbuildPluginOptions extends Pick< DevupUIBasePluginOptions, - 'engine' + 'engine' | 'stylex' > { package: string cssDir: string @@ -134,13 +135,16 @@ export const DevupUI = ({ singleCss = false, prefix, shorthands, + stylex, engine, atomHoist = 2, importAliases: userImportAliases, }: Partial = {}): RsbuildPlugin => { const normalizedShorthands = normalizeShorthands(shorthands ?? {}) + const styleResolution = normalizeStylexOptions(stylex) const compiler = loadCompiler(engine) compiler.registerShorthands(normalizedShorthands) + compiler.setStylexStyleResolution(styleResolution) const importAliases = mergeImportAliases( userImportAliases, readJsxImportSource(), diff --git a/packages/vite-plugin/src/__tests__/plugin.test.ts b/packages/vite-plugin/src/__tests__/plugin.test.ts index cbc3643da..96070ae20 100644 --- a/packages/vite-plugin/src/__tests__/plugin.test.ts +++ b/packages/vite-plugin/src/__tests__/plugin.test.ts @@ -72,6 +72,29 @@ describe('shorthand creation boundary', () => { registration.mockRestore() } }) + + it('reads StyleX under the styleResolution it is given, the default otherwise', () => { + using resolution = spyOn(wasm, 'setStylexStyleResolution') + createPlugin({ + stylex: { styleResolution: 'application-order' }, + }).closeBundle() + createPlugin().closeBundle() + expect(resolution.mock.calls).toEqual([ + ['application-order'], + ['property-specificity'], + ]) + wasm.setStylexStyleResolution(null) + }) + + it('rejects an unknown styleResolution before selecting a compiler', () => { + using selection = spyOn(pluginUtils, 'loadCompiler') + expect(() => + Reflect.apply(DevupUI, undefined, [ + { stylex: { styleResolution: 'last-wins' } }, + ]), + ).toThrow(pluginUtils.StylexConfigError) + expect(selection).not.toHaveBeenCalled() + }) }) type CodeExtractResult = ReturnType diff --git a/packages/vite-plugin/src/plugin.ts b/packages/vite-plugin/src/plugin.ts index f9ce736fc..6b29814c2 100644 --- a/packages/vite-plugin/src/plugin.ts +++ b/packages/vite-plugin/src/plugin.ts @@ -21,6 +21,7 @@ import { loadDevupConfig, mergeImportAliases, normalizeShorthands, + normalizeStylexOptions, readJsxImportSource, seedFileNumbers, tailwindCssFiles, @@ -246,7 +247,7 @@ function createCssChunkBuildOptions( export interface DevupUIPluginOptions extends Pick< DevupUIBasePluginOptions, - 'engine' + 'engine' | 'stylex' > { package: string cssDir: string @@ -322,11 +323,13 @@ export function DevupUI({ singleCss = false, prefix, shorthands, + stylex, engine, atomHoist = 2, importAliases: userImportAliases, }: Partial = {}): PluginOption { const normalizedShorthands = normalizeShorthands(shorthands ?? {}) + const styleResolution = normalizeStylexOptions(stylex) const compiler = loadCompiler(engine) // A build starts from its own options: whatever an earlier build in this // process left in the engine (prefix, hoisting, routes, buckets, numbers, @@ -364,6 +367,7 @@ export function DevupUI({ } function configureEngine() { compiler.registerShorthands(normalizedShorthands) + compiler.setStylexStyleResolution(styleResolution) compiler.setDebug(debug) compiler.setPrefix(prefix ?? null) } diff --git a/packages/webpack-plugin/src/__tests__/plugin.test.ts b/packages/webpack-plugin/src/__tests__/plugin.test.ts index f22c489e3..59ce1eb68 100644 --- a/packages/webpack-plugin/src/__tests__/plugin.test.ts +++ b/packages/webpack-plugin/src/__tests__/plugin.test.ts @@ -135,6 +135,38 @@ describe('shorthand creation boundary', () => { registration.mockRestore() } }) + + it('reads StyleX under the styleResolution it is given, again when the compiler initializes', () => { + using resolution = spyOn(wasm, 'setStylexStyleResolution') + const compiler = createCompiler() + try { + const plugin = new DevupUIWebpackPlugin({ + engine: 'wasm', + stylex: { styleResolution: 'application-order' }, + }) + new DevupUIWebpackPlugin({ engine: 'wasm' }) + plugin.apply(asCompiler(compiler)) + expect(resolution.mock.calls).toEqual([ + ['application-order'], + ['property-specificity'], + ['application-order'], + ]) + } finally { + for (const [, endBuild] of compiler.hooks.shutdown.tap.mock.calls) + endBuild() + wasm.setStylexStyleResolution(null) + } + }) + + it('rejects an unknown styleResolution before selecting a compiler', () => { + using selection = spyOn(pluginUtils, 'loadCompiler') + expect(() => + Reflect.construct(DevupUIWebpackPlugin, [ + { stylex: 'application-order' }, + ]), + ).toThrow(pluginUtils.StylexConfigError) + expect(selection).not.toHaveBeenCalled() + }) }) type CodeExtractResult = pluginUtils.DevupCompilerOutput diff --git a/packages/webpack-plugin/src/plugin.ts b/packages/webpack-plugin/src/plugin.ts index 2c5bd2ed0..953eb37ae 100644 --- a/packages/webpack-plugin/src/plugin.ts +++ b/packages/webpack-plugin/src/plugin.ts @@ -23,9 +23,11 @@ import { loadDevupConfigSync, mergeImportAliases, normalizeShorthands, + normalizeStylexOptions, planAtomHoist, readJsxImportSource, seedFileNumbers, + type StylexStyleResolution, tailwindCssFiles, type WasmImportAliases, withTailwindCss, @@ -38,7 +40,7 @@ import { reconcileWatchCss } from './watch-css' export interface DevupUIWebpackPluginOptions extends Pick< DevupUIBasePluginOptions, - 'engine' + 'engine' | 'stylex' > { package: string cssDir: string @@ -79,6 +81,7 @@ export class DevupUIWebpackPlugin { fileMapFile: string private importAliases: WasmImportAliases private readonly normalizedShorthands: Record + private readonly styleResolution: StylexStyleResolution private readonly compiler: DevupCompiler constructor({ @@ -93,13 +96,16 @@ export class DevupUIWebpackPlugin { engine = 'native', prefix, shorthands, + stylex, atomHoist = 2, productionPrewarmFiles, importAliases: userImportAliases, }: Partial = {}) { this.normalizedShorthands = normalizeShorthands(shorthands ?? {}) + this.styleResolution = normalizeStylexOptions(stylex) this.compiler = loadCompiler(engine) this.compiler.registerShorthands(this.normalizedShorthands) + this.compiler.setStylexStyleResolution(this.styleResolution) this.importAliases = mergeImportAliases( userImportAliases, readJsxImportSource(), @@ -246,6 +252,7 @@ export class DevupUIWebpackPlugin { this.compiler.setDebug(this.options.debug) this.compiler.setPrefix(this.options.prefix ?? null) this.compiler.registerShorthands(this.normalizedShorthands) + this.compiler.setStylexStyleResolution(this.styleResolution) const existsDevup = existsSync(this.options.devupFile) // read devup.json if (!existsSync(this.options.distDir))