Skip to content
Draft
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
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,12 @@ export const colors = stylex.defineConsts({
background: 'white',
foreground: 'black',
});

export const nestedTokens = stylex.defineConsts({
button: {
fill: {
primary: 'blue',
},
},
'button.fill.primary': 'red',
});
Original file line number Diff line number Diff line change
Expand Up @@ -617,5 +617,268 @@ describe('@stylexjs/babel-plugin', () => {
}
`);
});
test('nested constants object', () => {
const { code, metadata } = transform(`
import * as stylex from '@stylexjs/stylex';
export const tokens = stylex.defineConsts({
button: {
fill: {
primary: 'blue',
secondary: 'gray',
},
},
});
`);

expect(code).toMatchInlineSnapshot(`
"import * as stylex from '@stylexjs/stylex';
export const tokens = {
button: {
fill: {
primary: "blue",
secondary: "gray"
}
}
};"
`);
expect(metadata).toMatchInlineSnapshot(`
{
"stylex": [
[
"xreo3at",
{
"constKey": "xreo3at",
"constVal": "blue",
"ltr": "",
"rtl": null,
},
0,
],
[
"x3rbt3c",
{
"constKey": "x3rbt3c",
"constVal": "gray",
"ltr": "",
"rtl": null,
},
0,
],
],
}
`);
});

test('uses nested constants in stylex.create', () => {
const { code, metadata } = transformWithInlineConsts(`
import * as stylex from '@stylexjs/stylex';
export const tokens = stylex.defineConsts({
button: {
fill: {
primary: 'blue',
},
},
});
export const styles = stylex.create({
root: {
backgroundColor: tokens.button.fill.primary,
},
});
`);

expect(code).toMatchInlineSnapshot(`
"import * as stylex from '@stylexjs/stylex';
export const tokens = {
button: {
fill: {
primary: "blue"
}
}
};
export const styles = {
root: {
kWkggS: "x1t391ir",
$$css: true
}
};"
`);

// Verify const entry and CSS rule with inlined value
expect(metadata).toMatchInlineSnapshot(`
{
"stylex": [
[
"x1wyxh8f",
{
"constKey": "x1wyxh8f",
"constVal": "blue",
"ltr": "",
"rtl": null,
},
0,
],
[
"x1t391ir",
{
"ltr": ".x1t391ir{background-color:blue}",
"rtl": null,
},
3000,
],
],
}
`);
});

test('deeply nested constants', () => {
const { code, metadata } = transform(`
import * as stylex from '@stylexjs/stylex';
export const tokens = stylex.defineConsts({
level1: {
level2: {
level3: {
level4: 'deep-value',
},
},
},
});
`);

expect(code).toMatchInlineSnapshot(`
"import * as stylex from '@stylexjs/stylex';
export const tokens = {
level1: {
level2: {
level3: {
level4: "deep-value"
}
}
}
};"
`);

expect(metadata).toMatchInlineSnapshot(`
{
"stylex": [
[
"x67bk05",
{
"constKey": "x67bk05",
"constVal": "deep-value",
"ltr": "",
"rtl": null,
},
0,
],
],
}
`);
});

test('mixed flat and nested constants', () => {
const { code, metadata } = transform(`
import * as stylex from '@stylexjs/stylex';
export const tokens = stylex.defineConsts({
flatColor: 'red',
nested: {
color: 'blue',
},
});
`);

expect(code).toMatchInlineSnapshot(`
"import * as stylex from '@stylexjs/stylex';
export const tokens = {
flatColor: "red",
nested: {
color: "blue"
}
};"
`);
expect(metadata).toMatchInlineSnapshot(`
{
"stylex": [
[
"x19gcf6u",
{
"constKey": "x19gcf6u",
"constVal": "red",
"ltr": "",
"rtl": null,
},
0,
],
[
"x49cdii",
{
"constKey": "x49cdii",
"constVal": "blue",
"ltr": "",
"rtl": null,
},
0,
],
],
}
`);
});

test('deep chained imported constants work in stylex.create', () => {
const { code, metadata } = transformWithInlineConsts(`
import * as stylex from '@stylexjs/stylex';
import { nestedTokens } from './constants.stylex';
export const styles = stylex.create({
root: {
backgroundColor: nestedTokens.button.fill.primary,
},
});
`);

expect(code).toMatchInlineSnapshot(`
"import * as stylex from '@stylexjs/stylex';
import { nestedTokens } from './constants.stylex';
export const styles = {
root: {
kWkggS: "x13bhmi6",
$$css: true
}
};"
`);

// Should produce a style rule for backgroundColor referencing a CSS variable
// (The const entries themselves are in the metadata of constants.stylex, not this file)
expect(metadata).toMatchInlineSnapshot(`
{
"stylex": [
[
"x13bhmi6",
{
"ltr": ".x13bhmi6{background-color:var(--x529nz8)}",
"rtl": null,
},
3000,
],
],
}
`);
});

test('conflicting nested and flat constant names throws error', () => {
expect(() => {
transform(`
import * as stylex from '@stylexjs/stylex';
export const tokens = stylex.defineConsts({
button: {
fill: {
primary: 'blue',
},
},
'button.fill.primary': 'red',
});
`);
}).toThrow(
/Conflicting constant paths detected: "button\.fill\.primary"/,
);
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,10 @@
* @flow strict
*/

export type ConstsConfigValue = string | number;
export type ConstsConfigValue =
| string
| number
| { [string]: ConstsConfigValue };

export type ConstsConfig = $ReadOnly<{
[string]: ConstsConfigValue,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,43 +15,78 @@ import * as messages from './messages';

import createHash from './hash';

type ConstsOutput = string | number | { [string]: ConstsOutput };

export default function styleXDefineConsts<Vars: ConstsConfig>(
constants: Vars,
options: $ReadOnly<{ ...Partial<StyleXOptions>, exportId: string, ... }>,
): [
{ [string]: string | number }, // jsOutput JS output
{ [string]: ConstsOutput }, // jsOutput JS output
{ [string]: InjectableConstStyle }, // metadata for registerinjectableStyles
] {
const { classNamePrefix, exportId, debug, enableDebugClassNames } = {
...defaultOptions,
...options,
};

const jsOutput: { [string]: string | number } = {};
const jsOutput: { [string]: ConstsOutput } = {};
const injectableStyles: { [string]: InjectableConstStyle } = {};
const seenPaths: Set<string> = new Set();

const processEntry = (
key: string,
value: ConstsOutput,
path: Array<string>,
): ConstsOutput => {
if (typeof value === 'object' && value != null) {
const nested: { [string]: ConstsOutput } = {};
for (const [k, v] of Object.entries(value)) {
nested[k] = processEntry(k, v, [...path, k]);
}
return nested;
}

if (typeof value === 'string' || typeof value === 'number') {
const fullPath = path.join('.');

if (seenPaths.has(fullPath)) {
throw new Error(
`Conflicting constant paths detected: "${fullPath}". This can happen when you have both nested properties (e.g., {a: {b: 'value'}}) and a literal dotted key (e.g., {'a.b': 'value'}) that resolve to the same path.`,
);
Comment on lines +53 to +55
Copy link
Contributor Author

@j-malt j-malt Oct 30, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I couldn't come up with a great way to get around conflicting keys like this and it feels like a pattern to avoid anyways.

}
seenPaths.add(fullPath);

const varSafeKey = path
.map((segment) =>
segment[0] >= '0' && segment[0] <= '9' ? `_${segment}` : segment,
)
.join('_')
.replace(/[^a-zA-Z0-9]/g, '_');

const constKey =
debug && enableDebugClassNames
? `${varSafeKey}-${classNamePrefix}${createHash(`${exportId}.${fullPath}`)}`
: `${classNamePrefix}${createHash(`${exportId}.${fullPath}`)}`;

injectableStyles[constKey] = {
constKey,
constVal: value,
priority: 0,
ltr: '',
rtl: null,
};
return value;
}

return value;
};

for (const [key, value] of Object.entries(constants)) {
if (key.startsWith('--')) {
throw new Error(messages.INVALID_CONST_KEY);
}

const varSafeKey = (
key[0] >= '0' && key[0] <= '9' ? `_${key}` : key
).replace(/[^a-zA-Z0-9]/g, '_');

const constKey =
debug && enableDebugClassNames
? `${varSafeKey}-${classNamePrefix}${createHash(`${exportId}.${key}`)}`
: `${classNamePrefix}${createHash(`${exportId}.${key}`)}`;

jsOutput[key] = value;
injectableStyles[constKey] = {
constKey,
constVal: value,
priority: 0,
ltr: '',
rtl: null,
};
jsOutput[key] = processEntry(key, value, [key]);
}

return [jsOutput, injectableStyles];
Expand Down
Loading
Loading