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 a0e3edb41..a2cc1b130 100644
--- a/bindings/argument-validation.cjs
+++ b/bindings/argument-validation.cjs
@@ -24,6 +24,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/README.md b/bindings/devup-ui-binding/README.md
index 71afa1212..e14a9b931 100644
--- a/bindings/devup-ui-binding/README.md
+++ b/bindings/devup-ui-binding/README.md
@@ -2,7 +2,7 @@
Synchronous native build-time compiler for Node.js and Bun. Both
`require('@devup-ui/binding')` and named ESM imports expose exactly the existing
-30 compiler names, with identical function/class identities and no default init.
+31 compiler names, with identical function/class identities and no default init.
Authored CommonJS/ESM declarations are included; no WASM dependency is required.
The private loader selects one optional platform sibling: Windows MSVC, macOS,
@@ -96,4 +96,4 @@ The decoder is private and target-bounded: unused Serde hints use trait forwardi
Malformed-enum error paths follow shipped serde-wasm-bindgen 0.6.5: Object.entries result length is read and coerced once for the check, then read and coerced again for the invalid-length diagnostic when the first length is not one, before any index read. The second value supplies the diagnostic; errors thrown by its getter or coercion propagate unchanged. Valid enums retain one length read.
-The shared native/WASM boundary validates ordinary calls at 46 argument positions in 19 functions: malformed inputs throw a genuine `TypeError` naming the function, parameter and required type before state mutation. Preflight defaults the entire alias map on schema failure (after diagnostics) or a caught iterator-import failure whose `new Error(String(error))` conversion succeeds. Raw access failures and conversion faults escape unchanged before resolver selection; conversion runs once with the pending failure cleared, so reentry is isolated and resolver changes take effect before the outer core starts. Extraction and reservation remain strict. For example, `setPrefix(false)` throws `setPrefix(): argument prefix must be a string, null or undefined`; string/nullish prefixes remain supported. Extraction wrappers retain the measured metadata, receiver, extra-argument and apply/construct policy; `seedFileMap` validates and copies the caller's array before engine entry without rereading its indices. Same-revision Node/Bun identity, 272-case invalid-input, 73-exception preservation and seed-safety gates cover these contracts, not optimized shipping-native performance or real Node-host Linux Rust/authored-JS 100% coverage, which remain public-delivery gates.
+The shared native/WASM boundary validates ordinary calls at 47 argument positions in 20 functions: malformed inputs throw a genuine `TypeError` naming the function, parameter and required type before state mutation. Preflight defaults the entire alias map on schema failure (after diagnostics) or a caught iterator-import failure whose `new Error(String(error))` conversion succeeds. Raw access failures and conversion faults escape unchanged before resolver selection; conversion runs once with the pending failure cleared, so reentry is isolated and resolver changes take effect before the outer core starts. Extraction and reservation remain strict. For example, `setPrefix(false)` throws `setPrefix(): argument prefix must be a string, null or undefined`; string/nullish prefixes remain supported. Extraction wrappers retain the measured metadata, receiver, extra-argument and apply/construct policy; `seedFileMap` validates and copies the caller's array before engine entry without rereading its indices. Same-revision Node/Bun identity, 276-case invalid-input, 73-exception preservation and seed-safety gates cover these contracts, not optimized shipping-native performance or real Node-host Linux Rust/authored-JS 100% coverage, which remain public-delivery gates.
diff --git a/bindings/devup-ui-binding/adapter.cjs b/bindings/devup-ui-binding/adapter.cjs
index a34c93cac..0b65f962b 100644
--- a/bindings/devup-ui-binding/adapter.cjs
+++ b/bindings/devup-ui-binding/adapter.cjs
@@ -112,5 +112,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 eae4ba96a..ba1022d44 100644
--- a/bindings/devup-ui-binding/index.d.cts
+++ b/bindings/devup-ui-binding/index.d.cts
@@ -11,7 +11,7 @@ export class Output {
readonly updatedBaseStyle: boolean
}
-// Positional signatures intentionally match the existing 30-name compiler ABI.
+// Positional signatures intentionally match the existing 31-name compiler ABI.
export function codeExtract(
filename: string,
code: string,
@@ -89,3 +89,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 015b58724..c6a7cc0a0 100644
--- a/bindings/devup-ui-binding/index.mjs
+++ b/bindings/devup-ui-binding/index.mjs
@@ -31,4 +31,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 7211b6d16..5f708c3e1 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 7bc343dff..bb5fa103d 100644
--- a/bindings/devup-ui-wasm/script.js
+++ b/bindings/devup-ui-wasm/script.js
@@ -50,9 +50,9 @@ types = types.replace(hookType, '')
assert.equal(types.includes('install_panic_hook'), false)
writeFileSync('pkg/index.d.ts', types, 'utf8')
const names = [...source.matchAll(/^exports\.(\w+) = \1;/gm)]
-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(names.length, 31)
+assert.equal(new Set(names.map((match) => match[1])).size, 31)
+assert.equal([...source.matchAll(/^exports\./gm)].length, 31)
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 067b5abb6..ab0062ae8 100644
--- a/bindings/devup-ui-wasm/src/lib.rs
+++ b/bindings/devup-ui-wasm/src/lib.rs
@@ -199,6 +199,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 {
@@ -1949,4 +1962,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 a86141ce5..e249309a1 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 removeFile 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 removeFile reserveClassSlots resetBuildState resetStateForTesting seedFileMap setAtomHoist setDebug setModuleResolver setPrefix setStylexStyleResolution'.split(
' ',
)
const abi = {
@@ -199,8 +199,8 @@ const h = {
)
},
}
-assert.equal(corpus.length, 26)
-assert.equal(new Set(corpus.map((c) => c.name)).size, 26)
+assert.equal(corpus.length, 27)
+assert.equal(new Set(corpus.map((c) => c.name)).size, 27)
h.note('public-error-inventory', runDiagnostics(w))
for (const test of corpus) {
scenario = test.name
diff --git a/e2e/binding/package/consumer.mjs b/e2e/binding/package/consumer.mjs
index 3940b9cca..ddb59fdee 100644
--- a/e2e/binding/package/consumer.mjs
+++ b/e2e/binding/package/consumer.mjs
@@ -136,7 +136,7 @@ export async function consume(options) {
]
.map((match) => match[1])
.sort()
- assert.equal(names.length, 30)
+ assert.equal(names.length, 31)
for (const manager of ['npm', 'bun']) {
for (const omit of [false, true]) {
const startRequest = server.requests.length
diff --git a/e2e/binding/validation-cases.mjs b/e2e/binding/validation-cases.mjs
index f69d04387..2f7c8f8d2 100644
--- a/e2e/binding/validation-cases.mjs
+++ b/e2e/binding/validation-cases.mjs
@@ -49,6 +49,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(':')
@@ -154,6 +159,6 @@ export const cases = positions.flatMap((position) =>
.map((good, index) => (index === position.index ? value : good)),
})),
)
-assert.equal(positions.length, 46)
-assert.equal(new Set(positions.map((p) => p.fn)).size, 19)
+assert.equal(positions.length, 47)
+assert.equal(new Set(positions.map((p) => p.fn)).size, 20)
assert.equal(new Set(cases.map((c) => c.id)).size, cases.length)
diff --git a/e2e/binding/validation.mjs b/e2e/binding/validation.mjs
index 499bb1b34..5a94d03f1 100644
--- a/e2e/binding/validation.mjs
+++ b/e2e/binding/validation.mjs
@@ -114,7 +114,7 @@ for (const [engine, entry] of [
const summary = {
cases: cases.length,
positions: positions.length,
- functions: 18,
+ functions: 20,
engines: 2,
runs: runs.length,
failed: runs.filter((run) => run.failed).length,
diff --git a/libs/binding/src/lib.rs b/libs/binding/src/lib.rs
index a7d7a4c23..91d3e1ca5 100644
--- a/libs/binding/src/lib.rs
+++ b/libs/binding/src/lib.rs
@@ -7,6 +7,7 @@ mod resolver_state;
pub use css::debug::{is_debug, set_debug};
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 css_cache::{SheetCell, SheetGuard};
pub use extractor::{has_devup_ui, has_devup_ui_with};
diff --git a/libs/css/src/lib.rs b/libs/css/src/lib.rs
index 43e2509a6..615bd3fdb 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 e7261cbb1..8bcbd63b1 100644
--- a/libs/extractor/src/lib.rs
+++ b/libs/extractor/src/lib.rs
@@ -141,6 +141,9 @@ mod stylesheet_regression_tests;
#[cfg(test)]
mod stylesheet_stack_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