Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

test: the test runtime keeps every StyleX rule its dev runtime keys by an at-rule prelude (#8695)

Christopher Chedeau1b2bfe2bd4b5
diff --git a/internal/test-utils/package.json b/internal/test-utils/package.json
index 5391ad96ca..66d264cf95 100644
--- a/internal/test-utils/package.json
+++ b/internal/test-utils/package.json
@@ -6,6 +6,7 @@
"main": "./src/index.ts",
"scripts": {},
"dependencies": {
+ "@stylexjs/stylex": "catalog:",
"@testing-library/jest-dom": "catalog:",
"@testing-library/react": "catalog:",
"@testing-library/user-event": "^14.5.0"
diff --git a/internal/test-utils/src/README.md b/internal/test-utils/src/README.md
index dffd8f8964..25c4821c3f 100644
--- a/internal/test-utils/src/README.md
+++ b/internal/test-utils/src/README.md
@@ -4,7 +4,9 @@ Source code for shared testing utilities.
<!-- SYNC: When files in this directory change, update this document. -->
-| File | Role | Purpose |
-| ---------- | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `index.ts` | Entry | Re-exports testing utilities from @testing-library/react |
-| `setup.ts` | Setup | Vitest setup file; extends matchers with jest-dom, adds jsdom polyfills, and keeps the group last-member rule (`:nth-last-child(1 of …)`) out of jsdom's stylesheet |
+| File | Role | Purpose |
+| ---------------------- | ----- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `index.ts` | Entry | Re-exports testing utilities from @testing-library/react |
+| `jsdomRefusedRules.ts` | Setup | The marker of the rule the test setup keeps out of jsdom's stylesheet, shared by `setup.ts` and `stylexInject.ts` |
+| `setup.ts` | Setup | Vitest setup file; extends matchers with jest-dom, adds jsdom polyfills, and keeps the group last-member rule (`:nth-last-child(1 of …)`) out of jsdom's stylesheet |
+| `stylexInject.ts` | Setup | The StyleX runtime injection vitest.config.ts names: StyleX's own, plus each rule its 0.19.0 dev runtime drops because it keys the rule by an at-rule's prelude alone |
diff --git a/internal/test-utils/src/jsdomRefusedRules.ts b/internal/test-utils/src/jsdomRefusedRules.ts
new file mode 100644
index 0000000000..54d6997e47
--- /dev/null
+++ b/internal/test-utils/src/jsdomRefusedRules.ts
@@ -0,0 +1,20 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file jsdomRefusedRules.ts
+ * @input A CSS rule's text
+ * @output The marker of the one rule the test setup keeps out of jsdom's
+ * stylesheet
+ * @position Test setup only: setup.ts refuses a rule carrying it when it is
+ * inserted, and stylexInject.ts skips one before inserting it
+ *
+ * SYNC: When modified, update this header and
+ * /internal/test-utils/src/README.md
+ */
+
+/**
+ * The group last-member rule, `:nth-last-child(1 of S)` (ButtonGroup FR3),
+ * which jsdom's selector engine evaluates far too slowly and differently from
+ * browsers (see setup.ts).
+ */
+export const GROUP_LAST_MEMBER = ':nth-last-child(1 of ';
diff --git a/internal/test-utils/src/setup.ts b/internal/test-utils/src/setup.ts
index d35f7bdc53..e46481882d 100644
--- a/internal/test-utils/src/setup.ts
+++ b/internal/test-utils/src/setup.ts
@@ -16,6 +16,7 @@ import '@testing-library/jest-dom/vitest';
import {configure} from '@testing-library/react';
import {afterEach} from 'vitest';
import {__resetClickGuardForTest} from '../../../packages/core/src/utils/clickGuard';
+import {GROUP_LAST_MEMBER} from './jsdomRefusedRules';
// Text queries (getByText/findByText/…) target VISIBLE text. Astryx's
// `useAnnounce` renders a visually-hidden aria-live region
@@ -47,7 +48,6 @@ afterEach(() => {
// group corners in a real browser, and jsdom tests assert group
// membership only. Other `of S` rules, such as Table's zebra striping, still
// reach jsdom.
-const GROUP_LAST_MEMBER = ':nth-last-child(1 of ';
const insertRule = CSSStyleSheet.prototype.insertRule;
CSSStyleSheet.prototype.insertRule = function insertRuleWithoutGroupLastMember(
rule: string,
diff --git a/internal/test-utils/src/stylexInject.ts b/internal/test-utils/src/stylexInject.ts
new file mode 100644
index 0000000000..6dfe31da2c
--- /dev/null
+++ b/internal/test-utils/src/stylexInject.ts
@@ -0,0 +1,121 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file stylexInject.ts
+ * @input Each CSS rule the StyleX babel plugin injects at runtime in tests
+ * @output The `inject` that vitest.config.ts names as the plugin's
+ * `runtimeInjection`: StyleX's own, plus every rule StyleX's dev runtime
+ * drops because it keys the rule by an at-rule's prelude alone, inserted
+ * into a sheet of its own
+ * @position Test setup only; production CSS comes from the build
+ * (`processStylexRules`), which keeps every rule
+ *
+ * StyleX 0.19.0's dev runtime keys each rule it has inserted
+ * (`getSeenRuleKey` in `lib/es/inject.mjs`, which it does not export; copied
+ * below as `seenRuleKey`) and inserts a rule only once per key. A conditional
+ * rule whose prelude has one parenthesized condition,
+ * `@media (min-width: 100px)`, is keyed by its prelude plus the key of the
+ * rule inside it. Any other at-rule is keyed by its prelude alone:
+ * - a prelude with more than one condition, such as
+ * `@media (prefers-reduced-motion: reduce) and (pointer: coarse)`, at the
+ * top level or inside a one-condition prelude;
+ * - a named container query;
+ * - `@starting-style`.
+ *
+ * jsdom then gets only the first rule written under such a key, and a test
+ * that reads a later one reads nothing. This module inserts each of those
+ * later rules itself, once, after StyleX's own sheet. The one exception is the
+ * group last-member rule, which the test setup keeps out of jsdom
+ * (jsdomRefusedRules.ts).
+ *
+ * facebook/stylex#1991 keys every conditional prelude by the rule inside it;
+ * `@starting-style` rules still share one key there. Remove this module once
+ * StyleX keys every rule by its own selector.
+ *
+ * SYNC: When modified, update this header, /vitest.config.ts and
+ * /internal/test-utils/src/README.md
+ */
+
+import inject from '@stylexjs/stylex/lib/stylex-inject';
+import {GROUP_LAST_MEMBER} from './jsdomRefusedRules';
+
+type InjectArgs = Parameters<typeof inject>[0];
+
+// StyleX 0.19.0's `getSeenRuleKey`, as written in `lib/es/inject.mjs`.
+const SELECTOR = /\s*([,])\s*/g;
+const ONE_CONDITION = /^@(media|supports|container)\s*\([^)]+\)\s*{/;
+function seenRuleKey(cssText: string): string | null {
+ if (ONE_CONDITION.test(cssText)) {
+ const index = cssText.indexOf('{');
+ const query = cssText.substring(0, index).trim();
+ const next = seenRuleKey(cssText.substring(index + 1).trim());
+ const inner =
+ next != null && next !== '' ? next.replace(SELECTOR, '$1') : '';
+ return `${query} { ${inner}`;
+ }
+ const selector = cssText.split('{')[0].trim();
+ return selector !== '' ? selector.replace(SELECTOR, '$1') : null;
+}
+
+/** Whether StyleX keys `cssText` by an at-rule's prelude, not a selector. */
+function keyedByPrelude(cssText: string): boolean {
+ let rest = cssText;
+ while (ONE_CONDITION.test(rest)) {
+ rest = rest.slice(rest.indexOf('{') + 1).trim();
+ }
+ return rest.startsWith('@');
+}
+
+// The keys StyleX has inserted a rule under, every rule under such a key that
+// is in the page (the first, which StyleX inserted, and this module's), and
+// this module's sheet. They live on globalThis: `vi.resetModules()` loads this
+// module again, but StyleX's injector keeps its keys, so a record kept in
+// module state would insert restored rules again and lose a later rule
+// imported first after a reset.
+interface InjectRecord {
+ readonly keys: Set<string>;
+ readonly present: Set<string>;
+ sheet: CSSStyleSheet | null;
+}
+const RECORD = Symbol.for('astryx.stylexTestInject');
+const record: InjectRecord = ((
+ globalThis as unknown as Record<symbol, InjectRecord | undefined>
+)[RECORD] ??= {keys: new Set(), present: new Set(), sheet: null});
+const {keys, present} = record;
+
+function ownSheet(): CSSStyleSheet | null {
+ if (typeof document === 'undefined') {
+ return null;
+ }
+ if (record.sheet == null || !(record.sheet.ownerNode?.isConnected ?? false)) {
+ const style = document.createElement('style');
+ style.setAttribute('data-stylex-test-inject', '');
+ document.head.append(style);
+ record.sheet = style.sheet;
+ }
+ return record.sheet;
+}
+
+export default function stylexTestInject(args: InjectArgs): string {
+ const text = inject(args);
+ if (text === '' || !keyedByPrelude(text)) {
+ return text;
+ }
+ const key = seenRuleKey(text);
+ if (key == null) {
+ return text;
+ }
+ if (!keys.has(key)) {
+ // The first rule under this key: StyleX inserted it.
+ keys.add(key);
+ present.add(text);
+ return text;
+ }
+ if (present.has(text) || text.includes(GROUP_LAST_MEMBER)) {
+ return text;
+ }
+ present.add(text);
+ const target = ownSheet();
+ target?.insertRule(text, target.cssRules.length);
+ return text;
+}
diff --git a/packages/core/src/__tests__/stylexMultiConditionMedia.test.ts b/packages/core/src/__tests__/stylexMultiConditionMedia.test.ts
new file mode 100644
index 0000000000..1b50003b70
--- /dev/null
+++ b/packages/core/src/__tests__/stylexMultiConditionMedia.test.ts
@@ -0,0 +1,226 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file stylexMultiConditionMedia.test.ts
+ * @input StyleX styles under one-condition and multi-condition queries, a
+ * multi-condition query inside a one-condition one, and `@starting-style`
+ * @output Proves the test runtime holds every rule StyleX generated under an
+ * at-rule its dev runtime keys by the prelude alone, as the build does,
+ * through the runtime injection in internal/test-utils/src/stylexInject.ts
+ * @position Testing; guards that test setup, which compensates StyleX 0.19.0's
+ * dev-runtime rule key
+ */
+
+import * as stylex from '@stylexjs/stylex';
+import {expect, it, vi} from 'vitest';
+
+// Two styles, each with one declaration under the same two-condition query.
+const first = stylex.create({
+ rule: {
+ color: {
+ default: null,
+ '@media (prefers-reduced-motion: reduce) and (not (pointer: coarse))':
+ 'red',
+ },
+ },
+});
+const second = stylex.create({
+ rule: {
+ opacity: {
+ default: null,
+ '@media (prefers-reduced-motion: reduce) and (not (pointer: coarse))': 0,
+ },
+ },
+});
+// One style with two declarations under the same two-condition query.
+const both = stylex.create({
+ rule: {
+ outlineColor: {
+ default: null,
+ '@media (hover: hover) and (forced-colors: none)': 'blue',
+ },
+ outlineWidth: {
+ default: null,
+ '@media (hover: hover) and (forced-colors: none)': '3px',
+ },
+ },
+});
+// The same pair under a one-condition query, which StyleX keys by its inner
+// rule.
+const firstSimple = stylex.create({
+ rule: {color: {default: null, '@media (min-width: 100px)': 'red'}},
+});
+const secondSimple = stylex.create({
+ rule: {opacity: {default: null, '@media (min-width: 100px)': 0}},
+});
+
+// A multi-condition query inside a one-condition one, which StyleX keys by
+// the inner query alone.
+const nestedFirst = stylex.create({
+ rule: {
+ color: {
+ default: null,
+ '@supports (display: grid)': {
+ default: null,
+ '@media (hover: hover) and (pointer: fine)': 'red',
+ },
+ },
+ },
+});
+const nestedSecond = stylex.create({
+ rule: {
+ opacity: {
+ default: null,
+ '@supports (display: grid)': {
+ default: null,
+ '@media (hover: hover) and (pointer: fine)': 0.5,
+ },
+ },
+ },
+});
+// Two `@starting-style` rules, which StyleX keys by `@starting-style` alone.
+const startFirst = stylex.create({
+ rule: {color: {default: null, '@starting-style': 'blue'}},
+});
+const startSecond = stylex.create({
+ rule: {opacity: {default: null, '@starting-style': 0.25}},
+});
+// The group last-member rule (`:nth-last-child(1 of …)`, which the test setup
+// keeps out of jsdom) as a later rule under a multi-condition query: this
+// module loads only if the injection skips it.
+const groupFirst = stylex.create({
+ rule: {
+ color: {
+ default: null,
+ '@media (hover: hover) and (min-resolution: 2dppx)': 'red',
+ },
+ },
+});
+const groupLast = stylex.create({
+ rule: {
+ opacity: {
+ default: null,
+ '@media (hover: hover) and (min-resolution: 2dppx)': {
+ default: null,
+ ':nth-last-child(1 of :not([popover]))': 0,
+ },
+ },
+ },
+});
+// The same first rule under a multi-condition query, compiled twice.
+const twiceA = stylex.create({
+ rule: {
+ color: {default: null, '@media (hover: none) and (pointer: coarse)': 'red'},
+ },
+});
+const twiceB = stylex.create({
+ rule: {
+ color: {default: null, '@media (hover: none) and (pointer: coarse)': 'red'},
+ },
+});
+
+/** Every rule's text in every sheet of the document, nested rules included. */
+function allRules(): string[] {
+ const found: string[] = [];
+ const walk = (rules: CSSRuleList) => {
+ for (const rule of Array.from(rules)) {
+ found.push(rule.cssText);
+ if ('cssRules' in rule) {
+ walk((rule as CSSGroupingRule).cssRules);
+ }
+ }
+ };
+ for (const sheet of Array.from(document.styleSheets)) {
+ walk(sheet.cssRules);
+ }
+ return found;
+}
+
+/** The rules under `media` in every sheet of the document. */
+function rulesUnder(media: string): string {
+ const found: string[] = [];
+ for (const sheet of Array.from(document.styleSheets)) {
+ for (const rule of Array.from(sheet.cssRules)) {
+ if (rule instanceof CSSMediaRule && rule.media.mediaText === media) {
+ found.push(...Array.from(rule.cssRules).map(inner => inner.cssText));
+ }
+ }
+ }
+ return found.join(' ');
+}
+
+it('holds every rule written under a multi-condition media query, as the build does', () => {
+ stylex.props(
+ first.rule,
+ second.rule,
+ both.rule,
+ firstSimple.rule,
+ secondSimple.rule,
+ );
+ const simple = rulesUnder('(min-width: 100px)');
+ expect(simple).toContain('color');
+ expect(simple).toContain('opacity');
+ const motion = rulesUnder(
+ '(prefers-reduced-motion: reduce) and (not (pointer: coarse))',
+ );
+ expect(motion).toContain('color');
+ expect(motion).toContain('opacity');
+ const hover = rulesUnder('(hover: hover) and (forced-colors: none)');
+ expect(hover).toContain('outline-color');
+ expect(hover).toContain('outline-width');
+});
+
+it('holds every rule under a multi-condition query nested in a one-condition one, and every @starting-style rule', () => {
+ stylex.props(
+ nestedFirst.rule,
+ nestedSecond.rule,
+ startFirst.rule,
+ startSecond.rule,
+ );
+ const rules = allRules().join(' ');
+ const nested = allRules().filter(text =>
+ text.startsWith('@supports (display: grid)'),
+ );
+ expect(nested.join(' ')).toContain('color: red');
+ expect(nested.join(' ')).toContain('opacity: 0.5');
+ const starting = allRules().filter(text =>
+ text.startsWith('@starting-style'),
+ );
+ expect(starting.join(' ')).toContain('color: blue');
+ expect(starting.join(' ')).toContain('opacity: 0.25');
+ expect(rules).not.toBe('');
+});
+
+it('leaves the rule the test setup keeps out of jsdom out, and copies no rule StyleX already holds', () => {
+ stylex.props(groupFirst.rule, groupLast.rule, twiceA.rule, twiceB.rule);
+ const rules = allRules();
+ expect(rules.some(text => text.includes(':nth-last-child(1 of'))).toBe(false);
+ const coarse = rules.filter(text =>
+ text.startsWith('@media (hover: none) and (pointer: coarse)'),
+ );
+ expect(coarse).toHaveLength(1);
+});
+
+it('keeps its record across vi.resetModules(): no rule is restored twice, and a later rule imported first after a reset is restored', async () => {
+ // StyleX's own injector keeps its keys through a reset.
+ const a = await import('./stylexResetA.fixture');
+ const b = await import('./stylexResetB.fixture');
+ stylex.props(a.styles.rule, b.styles.rule);
+ vi.resetModules();
+ const a2 = await import('./stylexResetA.fixture');
+ const b2 = await import('./stylexResetB.fixture');
+ stylex.props(a2.styles.rule, b2.styles.rule);
+ const fast = allRules().filter(text =>
+ text.startsWith('@media (hover: hover) and (update: fast)'),
+ );
+ expect(fast.filter(text => text.includes('opacity'))).toHaveLength(1);
+
+ const c = await import('./stylexResetC.fixture');
+ stylex.props(c.styles.rule);
+ vi.resetModules();
+ const d = await import('./stylexResetD.fixture');
+ stylex.props(d.styles.rule);
+ expect(rulesUnder('(hover: none) and (update: slow)')).toContain(
+ 'opacity: 0.5',
+ );
+});
diff --git a/packages/core/src/__tests__/stylexResetA.fixture.ts b/packages/core/src/__tests__/stylexResetA.fixture.ts
new file mode 100644
index 0000000000..e43e12bc8a
--- /dev/null
+++ b/packages/core/src/__tests__/stylexResetA.fixture.ts
@@ -0,0 +1,16 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file stylexResetA.fixture.ts
+ * @input StyleX
+ * @output One rule under `@media (hover: hover) and (update: fast)`, injected when the module loads
+ * @position Fixture for stylexMultiConditionMedia.test.ts (`vi.resetModules()`)
+ */
+
+import * as stylex from '@stylexjs/stylex';
+
+export const styles = stylex.create({
+ rule: {
+ color: {default: null, '@media (hover: hover) and (update: fast)': 'red'},
+ },
+});
diff --git a/packages/core/src/__tests__/stylexResetB.fixture.ts b/packages/core/src/__tests__/stylexResetB.fixture.ts
new file mode 100644
index 0000000000..e11c486b41
--- /dev/null
+++ b/packages/core/src/__tests__/stylexResetB.fixture.ts
@@ -0,0 +1,16 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file stylexResetB.fixture.ts
+ * @input StyleX
+ * @output One rule under `@media (hover: hover) and (update: fast)`, injected when the module loads
+ * @position Fixture for stylexMultiConditionMedia.test.ts (`vi.resetModules()`)
+ */
+
+import * as stylex from '@stylexjs/stylex';
+
+export const styles = stylex.create({
+ rule: {
+ opacity: {default: null, '@media (hover: hover) and (update: fast)': 0},
+ },
+});
diff --git a/packages/core/src/__tests__/stylexResetC.fixture.ts b/packages/core/src/__tests__/stylexResetC.fixture.ts
new file mode 100644
index 0000000000..8a8dc71918
--- /dev/null
+++ b/packages/core/src/__tests__/stylexResetC.fixture.ts
@@ -0,0 +1,16 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file stylexResetC.fixture.ts
+ * @input StyleX
+ * @output One rule under `@media (hover: none) and (update: slow)`, injected when the module loads
+ * @position Fixture for stylexMultiConditionMedia.test.ts (`vi.resetModules()`)
+ */
+
+import * as stylex from '@stylexjs/stylex';
+
+export const styles = stylex.create({
+ rule: {
+ color: {default: null, '@media (hover: none) and (update: slow)': 'blue'},
+ },
+});
diff --git a/packages/core/src/__tests__/stylexResetD.fixture.ts b/packages/core/src/__tests__/stylexResetD.fixture.ts
new file mode 100644
index 0000000000..c438dcb46d
--- /dev/null
+++ b/packages/core/src/__tests__/stylexResetD.fixture.ts
@@ -0,0 +1,16 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file stylexResetD.fixture.ts
+ * @input StyleX
+ * @output One rule under `@media (hover: none) and (update: slow)`, injected when the module loads
+ * @position Fixture for stylexMultiConditionMedia.test.ts (`vi.resetModules()`)
+ */
+
+import * as stylex from '@stylexjs/stylex';
+
+export const styles = stylex.create({
+ rule: {
+ opacity: {default: null, '@media (hover: none) and (update: slow)': 0.5},
+ },
+});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 58100cb4fc..750276d0b2 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -601,6 +601,9 @@ importers:
internal/test-utils:
dependencies:
+ '@stylexjs/stylex':
+ specifier: 'catalog:'
+ version: 0.19.0
'@testing-library/jest-dom':
specifier: 'catalog:'
version: 6.9.1
diff --git a/vitest.config.ts b/vitest.config.ts
index 0770b58dd2..1c53fa3e8d 100644
--- a/vitest.config.ts
+++ b/vitest.config.ts
@@ -37,7 +37,12 @@ export default defineConfig({
{
dev: true,
enableDebugDataProp: false,
- runtimeInjection: true,
+ // StyleX's runtime injection, plus each rule its dev runtime drops
+ // under a prelude with more than one condition (StyleX 0.19.0).
+ runtimeInjection: path.join(
+ rootDir,
+ 'internal/test-utils/src/stylexInject.ts',
+ ),
genConditionalClasses: true,
treeshakeCompensation: true,
aliases: {