Skip to content

Commit 1b2bfe2

Browse files
vjeuxcixzhang
andauthored
test: the test runtime keeps every StyleX rule its dev runtime keys by an at-rule prelude (#8695)
* test: the test runtime keeps every StyleX rule under a multi-condition prelude StyleX 0.19.0's dev runtime keys a conditional rule whose prelude has more than one parenthesized condition by the prelude alone, so jsdom got only the first rule written under, say, @media (prefers-reduced-motion: reduce) and (pointer: coarse), and a test that read a later one read nothing. vitest.config.ts now names internal/test-utils/src/stylexInject.ts as the babel plugin's runtimeInjection: StyleX's own inject, plus each rule it drops, inserted once into a sheet of its own. Test-only: no StyleX code is patched, and the build keeps every rule as before. It comes out at the StyleX bump to a release that carries meta/stylex#1991, which fixes the key upstream. Red first: the new stylexMultiConditionMedia test (two styles, and one style with two declarations, under one two-condition query) failed with StyleX's own injection; on #8226 + #8682 + main, Indicator/selectionMotion.test.ts failed 2 of 6. Both pass with it, and the full ui suite on main has the same results (15,951 passing, plus the new test). * test: the StyleX test injection lets an insertRule error throw The setup caught and dropped any error from inserting a rule StyleX's dev runtime had dropped, so a rule jsdom refused would have gone missing without a trace. It never fired: the full ui suite passes with the catch removed (15,952 tests). A refused rule now throws with the rule's text. * test: the StyleX test injection restores every rule its dev runtime keys by a prelude alone Review: StyleX 0.19.0's dev runtime keys a rule by an at-rule's prelude alone not only under a top-level multi-condition query, but also under one nested in a one-condition query (`@supports (…) { @media (…) and (…) {…} }`), under a named container query, and under `@starting-style`; the injection restored only the first case, so a test that read a later rule under the others still read nothing. The injection now keys rules with a copy of StyleX's own getSeenRuleKey, which StyleX does not export, and restores every later rule whose key is an at-rule's prelude rather than a selector, once each. It also skips the group last-member rule, which the test setup refuses on purpose (its marker now lives in jsdomRefusedRules.ts, shared with setup.ts): a refusal of that rule threw out of the component's import. Other refusals still throw. And it records the first rule under a key as present, so the same rule compiled in two modules is not copied into the test sheet. * Merge remote-tracking branch 'origin/main' into vjeux/stylex-multi-condition * test: the StyleX test injection keeps its record across vi.resetModules() CodeBunny on #8695: the record of restored rules lived in module state, which vi.resetModules() resets while StyleX's injector keeps its keys, so restored rules were inserted again and a later rule imported first after a reset was lost. The record lives on globalThis; a guard case resets between fixtures under one prelude. Co-authored-by: Cindy Zhang <cindyxz@meta.com>
1 parent 7d37fb5 commit 1b2bfe2

12 files changed

Lines changed: 448 additions & 6 deletions

‎internal/test-utils/package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
"main": "./src/index.ts",
77
"scripts": {},
88
"dependencies": {
9+
"@stylexjs/stylex": "catalog:",
910
"@testing-library/jest-dom": "catalog:",
1011
"@testing-library/react": "catalog:",
1112
"@testing-library/user-event": "^14.5.0"

‎internal/test-utils/src/README.md‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,9 @@ Source code for shared testing utilities.
44

55
<!-- SYNC: When files in this directory change, update this document. -->
66

7-
| File | Role | Purpose |
8-
| ---------- | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
9-
| `index.ts` | Entry | Re-exports testing utilities from @testing-library/react |
10-
| `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 |
7+
| File | Role | Purpose |
8+
| ---------------------- | ----- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
9+
| `index.ts` | Entry | Re-exports testing utilities from @testing-library/react |
10+
| `jsdomRefusedRules.ts` | Setup | The marker of the rule the test setup keeps out of jsdom's stylesheet, shared by `setup.ts` and `stylexInject.ts` |
11+
| `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 |
12+
| `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 |
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
// Copyright (c) Meta Platforms, Inc. and affiliates.
2+
3+
/**
4+
* @file jsdomRefusedRules.ts
5+
* @input A CSS rule's text
6+
* @output The marker of the one rule the test setup keeps out of jsdom's
7+
* stylesheet
8+
* @position Test setup only: setup.ts refuses a rule carrying it when it is
9+
* inserted, and stylexInject.ts skips one before inserting it
10+
*
11+
* SYNC: When modified, update this header and
12+
* /internal/test-utils/src/README.md
13+
*/
14+
15+
/**
16+
* The group last-member rule, `:nth-last-child(1 of S)` (ButtonGroup FR3),
17+
* which jsdom's selector engine evaluates far too slowly and differently from
18+
* browsers (see setup.ts).
19+
*/
20+
export const GROUP_LAST_MEMBER = ':nth-last-child(1 of ';

‎internal/test-utils/src/setup.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import '@testing-library/jest-dom/vitest';
1616
import {configure} from '@testing-library/react';
1717
import {afterEach} from 'vitest';
1818
import {__resetClickGuardForTest} from '../../../packages/core/src/utils/clickGuard';
19+
import {GROUP_LAST_MEMBER} from './jsdomRefusedRules';
1920

2021
// Text queries (getByText/findByText/…) target VISIBLE text. Astryx's
2122
// `useAnnounce` renders a visually-hidden aria-live region
@@ -47,7 +48,6 @@ afterEach(() => {
4748
// group corners in a real browser, and jsdom tests assert group
4849
// membership only. Other `of S` rules, such as Table's zebra striping, still
4950
// reach jsdom.
50-
const GROUP_LAST_MEMBER = ':nth-last-child(1 of ';
5151
const insertRule = CSSStyleSheet.prototype.insertRule;
5252
CSSStyleSheet.prototype.insertRule = function insertRuleWithoutGroupLastMember(
5353
rule: string,
Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
// Copyright (c) Meta Platforms, Inc. and affiliates.
2+
3+
/**
4+
* @file stylexInject.ts
5+
* @input Each CSS rule the StyleX babel plugin injects at runtime in tests
6+
* @output The `inject` that vitest.config.ts names as the plugin's
7+
* `runtimeInjection`: StyleX's own, plus every rule StyleX's dev runtime
8+
* drops because it keys the rule by an at-rule's prelude alone, inserted
9+
* into a sheet of its own
10+
* @position Test setup only; production CSS comes from the build
11+
* (`processStylexRules`), which keeps every rule
12+
*
13+
* StyleX 0.19.0's dev runtime keys each rule it has inserted
14+
* (`getSeenRuleKey` in `lib/es/inject.mjs`, which it does not export; copied
15+
* below as `seenRuleKey`) and inserts a rule only once per key. A conditional
16+
* rule whose prelude has one parenthesized condition,
17+
* `@media (min-width: 100px)`, is keyed by its prelude plus the key of the
18+
* rule inside it. Any other at-rule is keyed by its prelude alone:
19+
* - a prelude with more than one condition, such as
20+
* `@media (prefers-reduced-motion: reduce) and (pointer: coarse)`, at the
21+
* top level or inside a one-condition prelude;
22+
* - a named container query;
23+
* - `@starting-style`.
24+
*
25+
* jsdom then gets only the first rule written under such a key, and a test
26+
* that reads a later one reads nothing. This module inserts each of those
27+
* later rules itself, once, after StyleX's own sheet. The one exception is the
28+
* group last-member rule, which the test setup keeps out of jsdom
29+
* (jsdomRefusedRules.ts).
30+
*
31+
* facebook/stylex#1991 keys every conditional prelude by the rule inside it;
32+
* `@starting-style` rules still share one key there. Remove this module once
33+
* StyleX keys every rule by its own selector.
34+
*
35+
* SYNC: When modified, update this header, /vitest.config.ts and
36+
* /internal/test-utils/src/README.md
37+
*/
38+
39+
import inject from '@stylexjs/stylex/lib/stylex-inject';
40+
import {GROUP_LAST_MEMBER} from './jsdomRefusedRules';
41+
42+
type InjectArgs = Parameters<typeof inject>[0];
43+
44+
// StyleX 0.19.0's `getSeenRuleKey`, as written in `lib/es/inject.mjs`.
45+
const SELECTOR = /\s*([,])\s*/g;
46+
const ONE_CONDITION = /^@(media|supports|container)\s*\([^)]+\)\s*{/;
47+
function seenRuleKey(cssText: string): string | null {
48+
if (ONE_CONDITION.test(cssText)) {
49+
const index = cssText.indexOf('{');
50+
const query = cssText.substring(0, index).trim();
51+
const next = seenRuleKey(cssText.substring(index + 1).trim());
52+
const inner =
53+
next != null && next !== '' ? next.replace(SELECTOR, '$1') : '';
54+
return `${query} { ${inner}`;
55+
}
56+
const selector = cssText.split('{')[0].trim();
57+
return selector !== '' ? selector.replace(SELECTOR, '$1') : null;
58+
}
59+
60+
/** Whether StyleX keys `cssText` by an at-rule's prelude, not a selector. */
61+
function keyedByPrelude(cssText: string): boolean {
62+
let rest = cssText;
63+
while (ONE_CONDITION.test(rest)) {
64+
rest = rest.slice(rest.indexOf('{') + 1).trim();
65+
}
66+
return rest.startsWith('@');
67+
}
68+
69+
// The keys StyleX has inserted a rule under, every rule under such a key that
70+
// is in the page (the first, which StyleX inserted, and this module's), and
71+
// this module's sheet. They live on globalThis: `vi.resetModules()` loads this
72+
// module again, but StyleX's injector keeps its keys, so a record kept in
73+
// module state would insert restored rules again and lose a later rule
74+
// imported first after a reset.
75+
interface InjectRecord {
76+
readonly keys: Set<string>;
77+
readonly present: Set<string>;
78+
sheet: CSSStyleSheet | null;
79+
}
80+
const RECORD = Symbol.for('astryx.stylexTestInject');
81+
const record: InjectRecord = ((
82+
globalThis as unknown as Record<symbol, InjectRecord | undefined>
83+
)[RECORD] ??= {keys: new Set(), present: new Set(), sheet: null});
84+
const {keys, present} = record;
85+
86+
function ownSheet(): CSSStyleSheet | null {
87+
if (typeof document === 'undefined') {
88+
return null;
89+
}
90+
if (record.sheet == null || !(record.sheet.ownerNode?.isConnected ?? false)) {
91+
const style = document.createElement('style');
92+
style.setAttribute('data-stylex-test-inject', '');
93+
document.head.append(style);
94+
record.sheet = style.sheet;
95+
}
96+
return record.sheet;
97+
}
98+
99+
export default function stylexTestInject(args: InjectArgs): string {
100+
const text = inject(args);
101+
if (text === '' || !keyedByPrelude(text)) {
102+
return text;
103+
}
104+
const key = seenRuleKey(text);
105+
if (key == null) {
106+
return text;
107+
}
108+
if (!keys.has(key)) {
109+
// The first rule under this key: StyleX inserted it.
110+
keys.add(key);
111+
present.add(text);
112+
return text;
113+
}
114+
if (present.has(text) || text.includes(GROUP_LAST_MEMBER)) {
115+
return text;
116+
}
117+
present.add(text);
118+
const target = ownSheet();
119+
target?.insertRule(text, target.cssRules.length);
120+
return text;
121+
}

0 commit comments

Comments
 (0)