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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .changepacks/changepack_log_stylex_style_resolution.json
Original file line number Diff line number Diff line change
@@ -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"
}
30 changes: 30 additions & 0 deletions apps/landing/src/app/(detail)/docs/migration/stylex/page.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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 = <div {...stylex.props(styles.top, styles.pad)} />
```

- `'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
Expand Down
1 change: 1 addition & 0 deletions bindings/argument-validation.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
4 changes: 2 additions & 2 deletions bindings/devup-ui-binding/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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.
2 changes: 2 additions & 0 deletions bindings/devup-ui-binding/adapter.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -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),
})
}
9 changes: 8 additions & 1 deletion bindings/devup-ui-binding/index.d.cts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
1 change: 1 addition & 0 deletions bindings/devup-ui-binding/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,5 @@ export const {
setDebug,
setModuleResolver,
setPrefix,
setStylexStyleResolution,
} = binding
5 changes: 5 additions & 0 deletions bindings/devup-ui-binding/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,11 @@ pub fn get_prefix() -> Either<String, Undefined> {
pub fn set_prefix(value: Option<String>) {
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<String>) -> 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<String, Undefined> {
Expand Down
6 changes: 3 additions & 3 deletions bindings/devup-ui-wasm/script.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [
Expand Down
33 changes: 33 additions & 0 deletions bindings/devup-ui-wasm/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,19 @@ pub fn set_prefix(prefix: Option<String>) {
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<String>) -> 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<String> {
Expand Down Expand Up @@ -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);
}
}
17 changes: 17 additions & 0 deletions e2e/binding/corpus/boundary.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
6 changes: 3 additions & 3 deletions e2e/binding/host.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion e2e/binding/package/consumer.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 7 additions & 2 deletions e2e/binding/validation-cases.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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(':')
Expand Down Expand Up @@ -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)
2 changes: 1 addition & 1 deletion e2e/binding/validation.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
1 change: 1 addition & 0 deletions libs/binding/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down
1 change: 1 addition & 0 deletions libs/css/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down
109 changes: 109 additions & 0 deletions libs/css/src/style_resolution.rs
Original file line number Diff line number Diff line change
@@ -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<Self, String> {
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);
}
}
Loading