Skip to content

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

TypeScript

fix(theme): remove bare prop and state classes (#6121)

Cindy Zhang1232b85afb48
diff --git a/.changeset/migrate-legacy-theme-selectors.md b/.changeset/migrate-legacy-theme-selectors.md
new file mode 100644
index 0000000000..30f3d4fe6d
--- /dev/null
+++ b/.changeset/migrate-legacy-theme-selectors.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[fix] Add a conservative `astryx upgrade --apply` migration for the Core bare selector-class removal. The transform parses `.css` selector syntax, rewrites exact v0.5.4 target/value pairs to behavior-preserving old-class/data-attribute unions, covers unbounded values that v0.5.4 emitted, and leaves unknown consumer classes unchanged.
+
+@cixzhang
diff --git a/.changeset/remove-legacy-theme-value-classes.md b/.changeset/remove-legacy-theme-value-classes.md
new file mode 100644
index 0000000000..0463c3e29d
--- /dev/null
+++ b/.changeset/remove-legacy-theme-value-classes.md
@@ -0,0 +1,26 @@
+---
+'@astryxdesign/core': minor
+---
+
+[breaking] Stop emitting deprecated bare prop and state classes such as `.primary`, `.sm`, and `.checked`. Components retain their stable `astryx-*` target classes and reflect visual props and runtime states through explicit `data-*` attributes; generated runtime and built theme CSS now uses that same selector contract.
+
+Run `astryx upgrade --apply` to migrate safely identifiable selectors in `.css` files when a known Astryx target and v0.5.4 value have one or more known meanings. For example:
+
+- `.astryx-button.primary` → `.astryx-button:is(.primary, [data-variant="primary"])`
+- `.astryx-button.sm` → `.astryx-button:is(.sm, [data-size="sm"])`
+- `.astryx-switch.checked` → `.astryx-switch:is(.checked, [data-checked="checked"])`
+
+The codemod parses CSS selector syntax and never rewrites declarations, comments, JavaScript/TypeScript strings, unqualified classes, or custom/unknown qualified classes. Each known value becomes a specificity-preserving `:is(...)` union containing the original class arm plus every v0.5.4 reflected data-attribute arm. The class arm keeps consumer-supplied `className` matches working; the attribute arms match v0.6 props and states. You can narrow the union later when class provenance or prop-axis intent is known. Search for unqualified old value selectors such as `.primary` or `.sm` and migrate those manually only where Astryx usage is confirmed. Migrate selectors embedded in JavaScript or TypeScript manually with the same rules.
+
+Semantic `defineTheme({components})` keys such as `variant:primary` and `checked` do not change. If you prebuild a custom theme, rerun `astryx theme build <theme-file>` after upgrading and deploy the regenerated `.css`, `.js`, `.d.ts`, and optional `.variants.d.ts` artifacts together. A built theme is marked `__built: true`, so the runtime intentionally does not regenerate stale CSS.
+
+Exported theme helpers keep their return/container shapes but intentionally return different selector bytes:
+
+- `themeProps` returns the stable target class (plus target-name compatibility aliases), without bare prop/state classes; its reflected `data-*` attributes are unchanged.
+- `parseStyleKey` returns data-attribute selector suffixes instead of `.value`, `.prop-N`, or `.state` suffixes.
+- `generateThemeRules` keeps its array contract and ordering; non-base component selectors use reflected attributes.
+- `generateThemeRulesSplit` keeps `{component, prose}`; `component` selector bytes change and `prose` is unchanged.
+- `generateOnMediaCSS` keeps its scoped string contract; component selector bytes change.
+- `generateThemeCSS` keeps `{prose, component}` and the same layers/scopes; `component` inherits the new selectors and `prose` is unchanged.
+
+@cixzhang
diff --git a/.claude/commands/create-theme.md b/.claude/commands/create-theme.md
index ddc5e7d54c..e1e69a88a0 100644
--- a/.claude/commands/create-theme.md
+++ b/.claude/commands/create-theme.md
@@ -139,10 +139,10 @@ Component overrides generate scoped CSS:
```css
@scope ([data-astryx-theme="{themeName}"]) to ([data-astryx-theme]) {
- .astryx-button.secondary {
+ .astryx-button[data-variant='secondary'] {
background-color: ...;
}
- .astryx-heading.level-1 {
+ .astryx-heading[data-level='1'] {
font-size: var(--font-size-2xl);
}
}
diff --git a/apps/docsite/src/app/globals.css b/apps/docsite/src/app/globals.css
index 1f8192d179..b3565510b6 100644
--- a/apps/docsite/src/app/globals.css
+++ b/apps/docsite/src/app/globals.css
@@ -180,7 +180,7 @@ body[data-hero-dark]:not([data-nav-mode='surface'])
/* On dark hero slides the dots render in Astryx, whose --color-accent is a
near-black ink — invisible on the dark backdrop, so the active dot and the
keyboard focus ring disappear. Repaint both with the light hero ink. */
-body[data-hero-dark] [data-home-page] .astryx-pagination-dot.active {
+body[data-hero-dark] [data-home-page] .astryx-pagination-dot[data-active="active"] {
background-color: var(--hero-on-dark);
}
body[data-hero-dark] [data-home-page] .astryx-pagination-dot:focus-visible {
diff --git a/apps/docsite/src/components/ThemePackagePage.tsx b/apps/docsite/src/components/ThemePackagePage.tsx
index d8e5eb4f94..92978cdc22 100644
--- a/apps/docsite/src/components/ThemePackagePage.tsx
+++ b/apps/docsite/src/components/ThemePackagePage.tsx
@@ -292,8 +292,7 @@ const styles = stylex.create({
// (distressed display), and themes without a display family
// override fall back to their heading font (Outfit, system,
// etc.). The Text below uses type="display-3" so the
- // .astryx-text.display-3 selector in each theme's @scope'd CSS (legacy class
- // selector; text also emits data-type="display-3")
+ // .astryx-text[data-type="display-3"] selector in each theme's @scope'd CSS
// applies the right family per card.
fontSize: 24,
lineHeight: 1.2,
diff --git a/apps/docsite/src/components/ThemeShowcaseTile.tsx b/apps/docsite/src/components/ThemeShowcaseTile.tsx
index a8d983b062..99d32ba4e6 100644
--- a/apps/docsite/src/components/ThemeShowcaseTile.tsx
+++ b/apps/docsite/src/components/ThemeShowcaseTile.tsx
@@ -222,9 +222,8 @@ const styles = stylex.create({
// Each typography sample sizes itself uniformly via a wrapper
// class. The actual font family + weight comes from the underlying
// Text / span using the theme's own typography tokens (or, for
- // Display, the theme-scoped .astryx-text.display-3 rule (legacy class selector;
- // text also emits data-type="display-3") which themes
- // like Gothic use to swap in a signature display family).
+ // Display, the theme-scoped .astryx-text[data-type="display-3"] rule, which
+ // themes like Gothic use to swap in a signature display family).
typeAa: {
display: 'inline-block',
fontSize: TYPE_SAMPLE_GLYPH_SIZE,
@@ -476,7 +475,7 @@ export function ThemeShowcaseTile({
display / heading / body / mono font with the role as
label. The Display sample uses Text type="display-3"
so themes that scope a custom display family to the
- .astryx-text.display-3 selector (legacy class selector; e.g. Gothic →
+ .astryx-text[data-type="display-3"] selector (e.g. Gothic →
Manufacturing Consent) flow through cleanly. */}
<HStack gap={3}>
<VStack gap={0.5} xstyle={styles.typeSample}>
diff --git a/apps/storybook/rtl-audit/verified-not-applicable.json b/apps/storybook/rtl-audit/verified-not-applicable.json
index 129e15eb81..b7a739a0ba 100644
--- a/apps/storybook/rtl-audit/verified-not-applicable.json
+++ b/apps/storybook/rtl-audit/verified-not-applicable.json
@@ -1,7 +1,7 @@
[
{
"component": "core/Banner",
- "reason": "Banner renders a single wrap-capable flex header row — status icon, title/description column, and an end area pushed over with `marginInlineStart: 'auto'` — above an optional content panel. Its status, close and expand glyphs (`info`, `warning`, `error`, `success`, `close`, `chevronDown`) are all radially symmetric or vertical, and the expanded state rotates the chevron 180° about the block axis. Every inset, corner radius and border it draws is a logical property, so the whole banner mirrors under RTL with nothing positioned, ordered or animated along the inline axis for the audit to assert.",
+ "reason": "Banner renders a single wrap-capable flex header row \u2014 status icon, title/description column, and an end area pushed over with `marginInlineStart: 'auto'` \u2014 above an optional content panel. Its status, close and expand glyphs (`info`, `warning`, `error`, `success`, `close`, `chevronDown`) are all radially symmetric or vertical, and the expanded state rotates the chevron 180\u00b0 about the block axis. Every inset, corner radius and border it draws is a logical property, so the whole banner mirrors under RTL with nothing positioned, ordered or animated along the inline axis for the audit to assert.",
"evidence": {
"apps/storybook/stories/Banner.stories.tsx": "sha256:15792a91bf7a7df1d6e15085cc42b9fc7f4df05135d09b6360b2a24ca2a6db5d",
"packages/core/src/Banner/Banner.tsx": "sha256:d69e58bc792b8c8802311aacd7b629c890915424f5b575d3bb3f71645db9c77f",
@@ -72,5 +72,69 @@
"packages/core/src/SelectableCard/SelectableCard.tsx": "sha256:5fa8fcf087296e33415a2696b91e478608b737506f26775715132a3a63e9218e",
"packages/core/src/SelectableCard/index.ts": "sha256:9cf677856807a09ee444ce68b21118bca9729592485f892da7e0bb64ee1d7501"
}
+ },
+ {
+ "component": "core/AspectRatio",
+ "reason": "AspectRatio only establishes a symmetric aspect-ratio box and sizes its single child to fill that box. It has no inline-axis placement, ordering, directional glyph, scrolling, dragging, overlay, or keyboard behavior."
+ },
+ {
+ "component": "core/Badge",
+ "reason": "Badge is a symmetric inline-flex pill. Its text and optional caller-owned content follow normal document direction with logical gap and padding; the component owns no directional glyph, physical inset, transform, scrolling, dragging, overlay, or keyboard behavior."
+ },
+ {
+ "component": "core/Card",
+ "reason": "Card is a block container with symmetric radius, border, shadow, and logical padding. It owns no directional glyph, inline-axis ordering, physical positioning, scrolling action, dragging, overlay, or keyboard behavior."
+ },
+ {
+ "component": "core/Code",
+ "reason": "Code is an inline typographic treatment with a monospace font, symmetric background/radius, and logical padding. The code string owns its own bidi content; the component adds no directional visual, positioning, ordering, interaction, or overlay."
+ },
+ {
+ "component": "core/Divider",
+ "reason": "Divider renders a symmetric horizontal or vertical rule. Optional label content follows normal document direction; there is no directional glyph, side-specific placement, transform, scrolling, dragging, overlay, or keyboard behavior."
+ },
+ {
+ "component": "core/FormLayout",
+ "reason": "FormLayout arranges caller-owned fields with grid/block flow, logical gaps, and responsive columns. It owns no directional glyph, physical inline placement, transform, scrolling action, dragging, overlay, or keyboard behavior."
+ },
+ {
+ "component": "core/Item",
+ "reason": "Item places start content, text, and end content in normal flex flow using logical padding, text-align:start, and margin-inline-start:auto. Those slots mirror through CSS direction without component branching; Item owns no directional glyph or directional keyboard behavior."
+ },
+ {
+ "component": "core/Link",
+ "reason": "Link is inline text in normal document flow with a logical gap for optional decoration. It owns no left/right glyph, physical inline placement, ordering algorithm, scrolling, dragging, overlay, or directional keyboard behavior."
+ },
+ {
+ "component": "core/List",
+ "reason": "List delegates marker placement and bidi ordering to semantic ol/ul elements and uses logical indentation and spacing. Item content is caller-owned; the component adds no directional controls, physical positioning, transforms, scrolling, dragging, or overlays."
+ },
+ {
+ "component": "core/Markdown",
+ "reason": "Markdown delegates bidi text, semantic list markers, links, and caller-authored content to browser semantics and shared components. Its own prose styling uses logical block/inline properties and it owns no directional control, physical placement, drag, scroll action, or overlay."
+ },
+ {
+ "component": "core/Section",
+ "reason": "Section is a block-flow surface with symmetric decoration and logical padding/insets. It owns no directional glyph, inline-axis ordering, physical transform, scrolling action, dragging, overlay, or keyboard behavior."
+ },
+ {
+ "component": "core/TextInput",
+ "reason": "TextInput composes a native input and optional start/end affordances in logical flex flow. Padding and status placement use logical properties; owned status, clear, and visibility glyphs are non-directional, and horizontal editing behavior remains native to the input."
+ },
+ {
+ "component": "core/TimeInput",
+ "reason": "TimeInput uses a native or typed text field with logical flex layout and non-directional clock/status glyphs. Its custom stepping uses only ArrowUp and ArrowDown, so it has no locale-dependent horizontal keyboard behavior, physical inline positioning, dragging, or scrolling action."
+ },
+ {
+ "component": "core/Token",
+ "reason": "Token is a symmetric inline-flex pill with logical padding/gap. Its optional remove control uses a non-directional close glyph, and the component owns no side-specific positioning, ordering algorithm, scrolling, dragging, overlay, or directional keyboard behavior."
+ },
+ {
+ "component": "core/Toolbar",
+ "reason": "Toolbar start, center, and end slots use CSS flex/grid flow, margin-inline-start, and logical container padding, so visual placement follows document direction without component branching. Its horizontal ArrowLeft/ArrowRight handling means previous/next control in the ARIA toolbar pattern rather than locale-specific content direction; owned glyphs are caller content."
+ },
+ {
+ "component": "lab/ListInput",
+ "reason": "ListInput is a vertical record editor. Keyboard reordering uses ArrowUp/ArrowDown/Home/End, pointer dragging follows the physical pointer while preserving source direction in the preview, and add/remove motion is block-axis. Its grid and controls follow CSS direction with no component-owned horizontal semantic to mirror."
}
]
diff --git a/apps/storybook/stories/Code.stories.tsx b/apps/storybook/stories/Code.stories.tsx
index 35afb53126..f419b7bf62 100644
--- a/apps/storybook/stories/Code.stories.tsx
+++ b/apps/storybook/stories/Code.stories.tsx
@@ -1,7 +1,7 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
import type {Meta, StoryObj} from '@storybook/react';
-import {Code} from '@astryxdesign/core/CodeBlock';
+import {Code} from '@astryxdesign/core/Code';
import {Text} from '@astryxdesign/core/Text';
import {Stack} from '@astryxdesign/core/Stack';
import {Link} from '@astryxdesign/core/Link';
@@ -22,6 +22,7 @@ export default meta;
type Story = StoryObj<typeof Code>;
export const Default: Story = {
+ tags: ['visual-baseline'],
args: {
children: 'const x = 1',
},
@@ -31,10 +32,9 @@ export const InParagraph: Story = {
name: 'Inline in paragraph',
render: () => (
<Text type="body">
- Use <Code>useState</Code> for local state and{' '}
- <Code>useEffect</Code> for side effects. If you need shared state
- across components, consider <Code>useContext</Code> or a state
- management library.
+ Use <Code>useState</Code> for local state and <Code>useEffect</Code> for
+ side effects. If you need shared state across components, consider{' '}
+ <Code>useContext</Code> or a state management library.
</Text>
),
};
@@ -44,13 +44,12 @@ export const InstructionalParagraph: Story = {
render: () => (
<Stack gap={3}>
<Text type="body">
- Install the package with <Code>npm install @astryxdesign/core</Code>, then
- import the component:
+ Install the package with <Code>npm install @astryxdesign/core</Code>,
+ then import the component:
</Text>
<Text type="body">
- Add <Code>{'<Button label="Save">Save</Button>'}</Code> to
- your JSX. The <Code>label</Code> prop is required for
- accessibility.
+ Add <Code>{'<Button label="Save">Save</Button>'}</Code> to your JSX. The{' '}
+ <Code>label</Code> prop is required for accessibility.
</Text>
</Stack>
),
@@ -60,13 +59,13 @@ export const MixedInline: Story = {
name: 'Mixed with links and emphasis',
render: () => (
<Text type="body">
- The <Code>ThemeProvider</Code> component wraps your app and
- supplies design tokens. See the{' '}
+ The <Code>ThemeProvider</Code> component wraps your app and supplies
+ design tokens. See the{' '}
<Link href="/docs/theme" isExternalLink={false}>
theme docs
</Link>{' '}
- for setup. Set <Code>colorScheme=&quot;dark&quot;</Code> to enable
- dark mode.
+ for setup. Set <Code>colorScheme=&quot;dark&quot;</Code> to enable dark
+ mode.
</Text>
),
};
diff --git a/apps/storybook/stories/FieldStatus.stories.tsx b/apps/storybook/stories/FieldStatus.stories.tsx
new file mode 100644
index 0000000000..d2625dee07
--- /dev/null
+++ b/apps/storybook/stories/FieldStatus.stories.tsx
@@ -0,0 +1,40 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file FieldStatus.stories.tsx
+ * @input FieldStatus from @astryxdesign/core
+ * @output Stable visual coverage for status tones and variants
+ * @position Core component stories and visual regression coverage
+ */
+
+import type {Meta, StoryObj} from '@storybook/react';
+import {FieldStatus} from '@astryxdesign/core/FieldStatus';
+import {Stack} from '@astryxdesign/core/Stack';
+
+const meta: Meta<typeof FieldStatus> = {
+ title: 'Core/FieldStatus',
+ component: FieldStatus,
+ tags: ['autodocs'],
+};
+
+export default meta;
+type Story = StoryObj<typeof FieldStatus>;
+
+export const Variants: Story = {
+ tags: ['visual-baseline'],
+ render: () => (
+ <Stack gap={3}>
+ <FieldStatus type="error" message="This field is required" />
+ <FieldStatus
+ type="warning"
+ message="This value may be visible to others"
+ variant="detached"
+ />
+ <FieldStatus
+ type="success"
+ message="Your changes were saved"
+ variant="detached"
+ />
+ </Stack>
+ ),
+};
diff --git a/packages/cli/assets/codemods/transforms/next/__tests__/migrate-astryx-theme-selectors-to-data-attrs.test.mjs b/packages/cli/assets/codemods/transforms/next/__tests__/migrate-astryx-theme-selectors-to-data-attrs.test.mjs
new file mode 100644
index 0000000000..8df0924dff
--- /dev/null
+++ b/packages/cli/assets/codemods/transforms/next/__tests__/migrate-astryx-theme-selectors-to-data-attrs.test.mjs
@@ -0,0 +1,398 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, expect, it} from 'vitest';
+import manifest from '../index.mjs';
+import transform from '../migrate-astryx-theme-selectors-to-data-attrs.mjs';
+import {
+ V054_THEME_SELECTOR_DYNAMIC_AXES,
+ V054_THEME_SELECTOR_TARGETS,
+} from '../migrate-astryx-theme-selectors-v0.5.4-data.mjs';
+
+function apply(source, path = 'styles.css') {
+ return transform({source, path}, {}) ?? source;
+}
+
+describe('migrate-astryx-theme-selectors-to-data-attrs', () => {
+ it('carries the complete frozen v0.5.4 runtime inventory', () => {
+ expect(Object.keys(V054_THEME_SELECTOR_TARGETS)).toHaveLength(186);
+ expect(
+ Object.values(V054_THEME_SELECTOR_TARGETS).reduce(
+ (count, tokens) => count + Object.keys(tokens).length,
+ 0,
+ ),
+ ).toBe(988);
+ expect(Object.keys(V054_THEME_SELECTOR_DYNAMIC_AXES).sort()).toEqual([
+ 'code-block',
+ 'code-block-header',
+ 'code-block-title',
+ 'codeblock',
+ 'codeblock-header',
+ 'codeblock-title',
+ 'grid',
+ 'metadata-list',
+ 'outline-item',
+ ]);
+ });
+
+ it('preserves the old class arm while adding unique reflected attributes', () => {
+ const input = `.astryx-button.primary.sm:hover { color: red; }
+.astryx-heading.level-2 { margin: 0; }
+.astryx-switch.checked { opacity: 1; }`;
+
+ const output = apply(input);
+ expect(output).toContain(
+ '.astryx-button:is(.primary,[data-variant="primary"]):is(.sm,[data-size="sm"]):hover',
+ );
+ expect(output).toContain(
+ '.astryx-heading:is(.level-2,[data-level="2"])',
+ );
+ expect(output).toContain(
+ '.astryx-switch:is(.checked,[data-checked="checked"])',
+ );
+ });
+
+ it('preserves nested at-rules, selector lists, combinators, and pseudo-elements', () => {
+ const input = `@media (hover: hover) {
+ @scope (.app) {
+ .astryx-card.muted > .astryx-button.ghost::before,
+ .astryx-progressbar.success { color: red; }
+ }
+}`;
+
+ const output = apply(input);
+ expect(output).toContain(
+ '.astryx-card:is(.muted,[data-variant="muted"])',
+ );
+ expect(output).toContain(
+ '.astryx-button:is(.ghost,[data-variant="ghost"])::before',
+ );
+ expect(output).toContain(
+ '.astryx-progressbar:is(.success,[data-variant="success"])',
+ );
+ expect(output).toContain('@media (hover: hover)');
+ expect(output).toContain('@scope (.app)');
+ });
+
+ it('migrates target/value relationships across functional pseudos', () => {
+ const output = apply(`:is(.astryx-button.primary, .astryx-card.muted) {}
+.astryx-button:not(.primary) {}
+.astryx-button:is(.primary) {}
+:is(.astryx-button).primary {}
+.wrapper:has(.astryx-button.primary) {}
+.astryx-button:is(.wrapper .primary) {}
+:is(.astryx-button):not(.primary) {}
+:is(.astryx-button):where(.primary) {}
+:not(.astryx-button).primary {}
+:not(:not(.astryx-button)).primary {}
+:nth-child(2n of .astryx-button).primary {}
+:is(.astryx-button, .other).primary {}
+:where(.astryx-button, .other).primary {}
+:is(.astryx-button, .other):not(.primary) {}
+:is(.astryx-button, .other):where(.primary) {}
+.astryx-button:nth-child(2n of .primary) {}
+:is(.astryx-button):nth-child(2n of .primary) {}
+.astryx-button:nth-child(2n of :is(.primary)) {}
+.astryx-button:nth-last-child(2n of .primary) {}
+.astryx-banner-icon:is(.info,[data-status="info"],.astryx-icon.accent) {}`);
+
+ expect(output).toContain(
+ '.astryx-button:is(.primary,[data-variant="primary"])',
+ );
+ expect(output).toContain(
+ '.astryx-card:is(.muted,[data-variant="muted"])',
+ );
+ expect(output).toContain(
+ '.astryx-button:not(:is(.primary,[data-variant="primary"]))',
+ );
+ expect(output).toContain(
+ '.astryx-button:is(:is(.primary,[data-variant="primary"]))',
+ );
+ expect(output).toContain(
+ ':is(.astryx-button):is(.primary,[data-variant="primary"])',
+ );
+ expect(output).toContain(
+ '.wrapper:has(.astryx-button:is(.primary,[data-variant="primary"]))',
+ );
+ expect(output).toContain(
+ '.astryx-button:is(.wrapper :is(.primary,[data-variant="primary"]))',
+ );
+ expect(output).toContain(
+ ':is(.astryx-button):not(:is(.primary,[data-variant="primary"]))',
+ );
+ expect(output).toContain(
+ ':is(.astryx-button):where(:is(.primary,[data-variant="primary"]))',
+ );
+ expect(output).toContain(
+ ':not(.astryx-button):is(.primary,:where(.astryx-button)[data-variant="primary"])',
+ );
+ expect(output).toContain(
+ ':not(:not(.astryx-button)):is(.primary,:where(.astryx-button)[data-variant="primary"])',
+ );
+ expect(output).toContain(
+ ':nth-child(2n of .astryx-button):is(.primary,[data-variant="primary"])',
+ );
+ expect(output).toContain(
+ ':is(.astryx-button, .other):is(.primary,:where(.astryx-button)[data-variant="primary"])',
+ );
+ expect(output).toContain(
+ ':where(.astryx-button, .other):is(.primary,:where(.astryx-button)[data-variant="primary"])',
+ );
+ expect(output).toContain(
+ ':is(.astryx-button, .other):not(:is(.primary,:where(.astryx-button)[data-variant="primary"]))',
+ );
+ expect(output).toContain(
+ ':is(.astryx-button, .other):where(:is(.primary,:where(.astryx-button)[data-variant="primary"]))',
+ );
+ expect(output).toContain(
+ '.astryx-button:nth-child(2n of :is(.primary,:where(.astryx-button)[data-variant="primary"]))',
+ );
+ expect(output).toContain(
+ ':is(.astryx-button):nth-child(2n of :is(.primary,:where(.astryx-button)[data-variant="primary"]))',
+ );
+ expect(output).toContain(
+ '.astryx-button:nth-child(2n of :is(:is(.primary,:where(.astryx-button)[data-variant="primary"])))',
+ );
+ expect(output).toContain(
+ '.astryx-button:nth-last-child(2n of :is(.primary,:where(.astryx-button)[data-variant="primary"]))',
+ );
+ expect(output).toContain(
+ '.astryx-banner-icon:is(.info,[data-status="info"],.astryx-icon:is(.accent,[data-color="accent"]))',
+ );
+ expect(apply(output)).toBe(output);
+ });
+
+ it('migrates selector groups in @scope preludes', () => {
+ const output = apply(
+ '@scope (.astryx-button.primary) to (.astryx-card:not(.muted)) { .child {} }',
+ );
+
+ expect(output).toContain(
+ '@scope (.astryx-button:is(.primary,[data-variant="primary"]))',
+ );
+ expect(output).toContain(
+ 'to (.astryx-card:not(:is(.muted,[data-variant="muted"])))',
+ );
+ });
+
+ it('inherits parent targets for same-element native CSS nesting', () => {
+ const output = apply(`.astryx-button {
+ &.primary { color: red; }
+ & .primary { color: blue; }
+}
+:is(.astryx-button, .other) {
+ &.primary { color: green; }
+}`);
+
+ expect(output).toContain(
+ '&:is(.primary,[data-variant="primary"]) { color: red; }',
+ );
+ expect(output).toContain('& .primary { color: blue; }');
+ expect(output).toContain(
+ '&:is(.primary,:where(.astryx-button)[data-variant="primary"]) { color: green; }',
+ );
+ expect(apply(output)).toBe(output);
+ });
+
+ it('handles reversed, attribute-separated, and pseudo-separated classes', () => {
+ const output = apply(`.primary.astryx-button,
+.astryx-button[data-test].primary,
+.astryx-button:hover.primary { color: red; }`);
+
+ expect(output).toContain(
+ ':is(.primary,[data-variant="primary"]).astryx-button',
+ );
+ expect(output).toContain(
+ '.astryx-button[data-test]:is(.primary,[data-variant="primary"])',
+ );
+ expect(output).toContain(
+ '.astryx-button:hover:is(.primary,[data-variant="primary"])',
+ );
+ });
+
+ it('migrates escaped fractional class tokens without corrupting the value', () => {
+ expect(apply('.astryx-grid.gap-0\\.5 { gap: 2px; }')).toContain(
+ '.astryx-grid:is(.gap-0\\.5,[data-gap="0.5"])',
+ );
+ });
+
+ it('never rewrites comments or declaration string values', () => {
+ const input = `/* Old example: .astryx-button.primary */
+.example { content: ".astryx-button.primary"; }
+.astryx-button.primary { color: red; }`;
+ const output = apply(input);
+
+ expect(output).toContain('/* Old example: .astryx-button.primary */');
+ expect(output).toContain('content: ".astryx-button.primary"');
+ expect(output).toContain(
+ '.astryx-button:is(.primary,[data-variant="primary"])',
+ );
+ });
+
+ it('keeps consumer className matching while adding the prop attribute arm', () => {
+ const output = apply(
+ '.astryx-button.primary.my-consumer-class { color: red; }',
+ );
+
+ expect(output).toContain(
+ '.astryx-button:is(.primary,[data-variant="primary"]).my-consumer-class',
+ );
+ expect(output).toContain('.primary');
+ expect(output).not.toContain('TODO(astryx upgrade)');
+ });
+
+ it('preserves every old match for a value shared by multiple prop axes', () => {
+ const output = apply('.astryx-grid.center { place-content: center; }');
+
+ expect(output).toContain(
+ '.astryx-grid:is(.center,[data-align="center"],[data-justify="center"])',
+ );
+ expect(output).toContain('.center');
+ expect(output).not.toContain('TODO(astryx upgrade)');
+ });
+
+ it('leaves unknown custom values and unqualified classes unchanged', () => {
+ const output = apply(
+ '.astryx-button.brand { color: red; }\n.primary { color: blue; }',
+ );
+
+ expect(output).toContain('.astryx-button.brand');
+ expect(output).toContain('.primary { color: blue; }');
+ expect(output).not.toContain('TODO(astryx upgrade)');
+ });
+
+ it('ignores JavaScript and TypeScript rather than rewriting quoted strings', () => {
+ const source = 'const selector = ".astryx-button.primary";';
+ expect(apply(source, 'selectors.ts')).toBe(source);
+ expect(apply(source, 'selectors.js')).toBe(source);
+ });
+
+ it('leaves repeated target classes unchanged for specificity', () => {
+ const input =
+ '.astryx-app-shell-sidenav.astryx-app-shell-sidenav { width: 20rem; }';
+ expect(apply(input)).toBe(input);
+ });
+
+ it.each([
+ [
+ '.astryx-avatar-group.lg',
+ '.astryx-avatar-group:is(.lg,[data-size="lg"])',
+ ],
+ [
+ '.astryx-chat-message-bubble.assistant',
+ '.astryx-chat-message-bubble:is(.assistant,[data-sender="assistant"])',
+ ],
+ [
+ '.astryx-toolbar.md',
+ '.astryx-toolbar:is(.md,[data-size="md"])',
+ ],
+ [
+ '.astryx-code-block.javascript',
+ '.astryx-code-block:is(.javascript,[data-language="javascript"])',
+ ],
+ [
+ '.astryx-grid.columns-3',
+ '.astryx-grid:is(.columns-3,[data-columns="3"])',
+ ],
+ [
+ '.astryx-outline-item.level-9',
+ '.astryx-outline-item:is(.level-9,[data-level="9"])',
+ ],
+ [
+ '.astryx-metadata-list.columns-5',
+ '.astryx-metadata-list:is(.columns-5,[data-columns="5"])',
+ ],
+ [
+ '.astryx-alert-dialog.standard',
+ '.astryx-alert-dialog:is(.standard,[data-variant="standard"])',
+ ],
+ [
+ '.astryx-chat-send-button.primary',
+ '.astryx-chat-send-button:is(.primary,[data-variant="primary"])',
+ ],
+ [
+ '.astryx-input-clear-icon.secondary',
+ '.astryx-input-clear-icon:is(.secondary,[data-color="secondary"])',
+ ],
+ [
+ '.astryx-dropdown-menu-divider.horizontal',
+ '.astryx-dropdown-menu-divider:is(.horizontal,[data-orientation="horizontal"])',
+ ],
+ [
+ '.astryx-list-item.spacious',
+ '.astryx-list-item:is(.spacious,[data-density="spacious"])',
+ ],
+ [
+ '.astryx-selectable-card.false',
+ '.astryx-selectable-card:is(.false,[data-selected="false"])',
+ ],
+ [
+ '.astryx-selector-check.disabled',
+ '.astryx-selector-check:is(.disabled,[data-color="disabled"],[data-disabled="disabled"])',
+ ],
+ ])('covers the exact v0.5.4 callsite mapping %s', (input, expected) => {
+ expect(apply(`${input} { color: red; }`)).toContain(expected);
+ });
+
+ it('combines static and dynamic candidates from the same v0.5.4 token', () => {
+ expect(apply('.astryx-code-block.sm {}')).toContain(
+ '.astryx-code-block:is(.sm,[data-size="sm"],[data-language="sm"])',
+ );
+ });
+
+ it('preserves both possible language values for digit-prefixed legacy tokens', () => {
+ expect(apply('.astryx-code-block.language-123 {}')).toContain(
+ '.astryx-code-block:is(.language-123,[data-language="language-123"],[data-language="123"])',
+ );
+ });
+
+ it('does not invent attributes for classes v0.5.4 never emitted', () => {
+ const input = `.astryx-toolbar.size {}
+.astryx-resize-handle.horizontal {}`;
+ expect(apply(input)).toBe(input);
+ });
+
+ it.each([
+ [
+ '.astryx-text.code',
+ '.astryx-text:is(.code,[data-type="code"])',
+ ],
+ [
+ '.astryx-layout.fill',
+ '.astryx-layout:is(.fill,[data-height="fill"])',
+ ],
+ [
+ '.astryx-side-nav-item.selected',
+ '.astryx-side-nav-item:is(.selected,[data-selected="selected"])',
+ ],
+ [
+ '.astryx-radio-list.horizontal',
+ '.astryx-radio-list:is(.horizontal,[data-orientation="horizontal"])',
+ ],
+ [
+ '.astryx-top-nav-item.selected',
+ '.astryx-top-nav-item:is(.selected,[data-selected="selected"])',
+ ],
+ [
+ '.astryx-segmented-control-item.selected',
+ '.astryx-segmented-control-item:is(.selected,[data-selected="selected"])',
+ ],
+ ])('rewrites the real-world mapping %s', (input, expected) => {
+ expect(apply(`${input} { color: red; }`)).toContain(expected);
+ });
+
+ it('is byte-idempotent after behavior-preserving migrations', () => {
+ const input = `.astryx-button.primary.my-class { color: red; }
+.astryx-grid.center { place-content: center; }`;
+ const once = apply(input);
+ expect(apply(once)).toBe(once);
+ });
+
+ it('is a normal, non-optional next-release transform', () => {
+ const entry = manifest.find(
+ candidate =>
+ candidate.name === 'migrate-astryx-theme-selectors-to-data-attrs',
+ );
+ expect(entry).toBeDefined();
+ expect(entry?.optional).not.toBe(true);
+ });
+});
diff --git a/packages/cli/assets/codemods/transforms/next/index.mjs b/packages/cli/assets/codemods/transforms/next/index.mjs
index 7d85271908..e50f01525d 100644
--- a/packages/cli/assets/codemods/transforms/next/index.mjs
+++ b/packages/cli/assets/codemods/transforms/next/index.mjs
@@ -10,6 +10,9 @@
import moveImeHelperImport, {
meta as moveImeHelperImportMeta,
} from './move-ime-helper-import.mjs';
+import migrateAstryxThemeSelectorsToDataAttrs, {
+ meta as migrateAstryxThemeSelectorsToDataAttrsMeta,
+} from './migrate-astryx-theme-selectors-to-data-attrs.mjs';
import removeFocusIsrtlOption, {
meta as removeFocusIsrtlOptionMeta,
} from './remove-focus-isrtl-option.mjs';
@@ -18,6 +21,11 @@ import renameResizablePixelBounds, {
} from './rename-resizable-pixel-bounds.mjs';
export default [
+ {
+ name: 'migrate-astryx-theme-selectors-to-data-attrs',
+ transform: migrateAstryxThemeSelectorsToDataAttrs,
+ meta: migrateAstryxThemeSelectorsToDataAttrsMeta,
+ },
{
name: 'move-ime-helper-import',
transform: moveImeHelperImport,
diff --git a/packages/cli/assets/codemods/transforms/next/migrate-astryx-theme-selectors-to-data-attrs.mjs b/packages/cli/assets/codemods/transforms/next/migrate-astryx-theme-selectors-to-data-attrs.mjs
new file mode 100644
index 0000000000..bd8086d74a
--- /dev/null
+++ b/packages/cli/assets/codemods/transforms/next/migrate-astryx-theme-selectors-to-data-attrs.mjs
@@ -0,0 +1,721 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Codemod: migrate v0.5.4 Astryx theme selectors to data attributes.
+ *
+ * This transform parses CSS and rewrites only class nodes inside selector
+ * preludes. It never searches arbitrary source text, declarations, comments,
+ * or JavaScript strings. A known old class becomes a specificity-preserving
+ * `:is(.old-class, [data-*])` union: the class arm preserves consumer-supplied
+ * className matches, while the attribute arm matches the v0.6 prop/state
+ * reflection. Values shared by several old prop axes include every attribute
+ * arm. Unknown/custom classes stay intact.
+ */
+
+import path from 'node:path';
+import postcss from 'postcss';
+import selectorParser from 'postcss-selector-parser';
+import {
+ V054_THEME_SELECTOR_DYNAMIC_AXES,
+ V054_THEME_SELECTOR_TARGETS,
+} from './migrate-astryx-theme-selectors-v0.5.4-data.mjs';
+
+export const meta = {
+ title: 'Migrate Astryx theme selectors to data attributes',
+ description:
+ 'Rewrites known v0.5.4 `.astryx-<target>.<value>` selectors to behavior-preserving class/data-attribute unions.',
+ fileExtensions: ['.css'],
+};
+
+/** @typedef {[string, string]} AttributeCandidate */
+/** @typedef {AttributeCandidate | AttributeCandidate[]} CandidateEntry */
+
+/** @type {Record<string, Record<string, CandidateEntry>>} */
+const TARGETS = V054_THEME_SELECTOR_TARGETS;
+/** @type {Record<string, Array<{axis: string, token: 'class-value' | 'prefixed', prefix?: string}>>} */
+const DYNAMIC_AXES = V054_THEME_SELECTOR_DYNAMIC_AXES;
+const SAME_ELEMENT_FUNCTIONAL_PSEUDOS = new Set([':is', ':where', ':not']);
+
+/** @param {string} axis */
+function dataAttributeName(axis) {
+ return axis.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();
+}
+
+/** @param {string} value */
+function escapeAttributeValue(value) {
+ let escaped = '';
+ for (const char of value) {
+ const codePoint = char.codePointAt(0) ?? 0;
+ if (
+ char === '"' ||
+ char === '\\' ||
+ codePoint < 0x20 ||
+ codePoint === 0x7f
+ ) {
+ escaped += `\\${(codePoint === 0 ? 0xfffd : codePoint).toString(16)} `;
+ } else {
+ escaped += char;
+ }
+ }
+ return escaped;
+}
+
+/** @param {AttributeCandidate} candidate */
+function attributeNode([axis, value]) {
+ const escaped = escapeAttributeValue(value);
+ return selectorParser.attribute({
+ attribute: `data-${dataAttributeName(axis)}`,
+ operator: '=',
+ value,
+ quoteMark: '"',
+ raws: {value: `"${escaped}"`},
+ });
+}
+
+/**
+ * @param {CandidateEntry | undefined} entry
+ * @returns {AttributeCandidate[]}
+ */
+function normalizeCandidates(entry) {
+ if (!Array.isArray(entry)) return [];
+ return typeof entry[0] === 'string'
+ ? [/** @type {AttributeCandidate} */ (entry)]
+ : /** @type {AttributeCandidate[]} */ (entry);
+}
+
+/** @param {string} target @param {string} token */
+function candidatesFor(target, token) {
+ const candidates = normalizeCandidates(TARGETS[target]?.[token]);
+ for (const rule of DYNAMIC_AXES[target] ?? []) {
+ if (rule.token === 'class-value') {
+ candidates.push([rule.axis, token]);
+ const numericPrefix = `${rule.axis}-`;
+ if (token.startsWith(numericPrefix)) {
+ const unprefixed = token.slice(numericPrefix.length);
+ if (/^\d/.test(unprefixed)) {
+ candidates.push([rule.axis, unprefixed]);
+ }
+ }
+ } else if (rule.prefix && token.startsWith(rule.prefix)) {
+ const value = token.slice(rule.prefix.length);
+ if (/^\d/.test(value)) candidates.push([rule.axis, value]);
+ }
+ }
+ return candidates;
+}
+
+/** @param {AttributeCandidate[]} candidates */
+function dedupeCandidates(candidates) {
+ return [
+ ...new Map(
+ candidates.map(candidate => [`${candidate[0]}\0${candidate[1]}`, candidate]),
+ ).values(),
+ ];
+}
+
+/** @typedef {{target: string, candidate: AttributeCandidate}} GatedCandidate */
+
+/** @param {string} target @param {AttributeCandidate} candidate */
+function gatedAttributeSelector(target, candidate) {
+ const targetGate = selectorParser.pseudo({
+ value: ':where',
+ nodes: [
+ selectorParser.selector({
+ value: '',
+ nodes: [selectorParser.className({value: `astryx-${target}`})],
+ }),
+ ],
+ });
+ return selectorParser.selector({
+ value: '',
+ nodes: [targetGate, attributeNode(candidate)],
+ });
+}
+
+/**
+ * @param {any} oldClass
+ * @param {AttributeCandidate[]} candidates
+ * @param {GatedCandidate[]} [gatedCandidates]
+ */
+function behaviorPreservingUnionNode(
+ oldClass,
+ candidates,
+ gatedCandidates = [],
+) {
+ return selectorParser.pseudo({
+ value: ':is',
+ nodes: [
+ selectorParser.selector({value: '', nodes: [oldClass.clone()]}),
+ ...candidates.map(candidate =>
+ selectorParser.selector({value: '', nodes: [attributeNode(candidate)]}),
+ ),
+ ...gatedCandidates.map(({target, candidate}) =>
+ gatedAttributeSelector(target, candidate),
+ ),
+ ],
+ });
+}
+
+/** @param {AttributeCandidate} candidate */
+function candidateKey([axis, value]) {
+ return `${dataAttributeName(axis)}\0${value}`;
+}
+
+/**
+ * Return the selector arms that already form complete generated old-class /
+ * data-attribute pairs. A larger author-written :is() may contain both complete
+ * pairs and unrelated arms; callers skip only the complete arms and keep
+ * traversing the rest.
+ *
+ * @param {any} pseudo
+ * @param {string[]} targetNames
+ * @param {string[]} [conditionalTargets]
+ * @returns {Set<any>}
+ */
+function completedBehaviorPreservingUnionArms(
+ pseudo,
+ targetNames,
+ conditionalTargets = [],
+) {
+ const completed = new Set();
+ if (
+ (targetNames.length === 0 && conditionalTargets.length === 0) ||
+ !Array.isArray(pseudo.nodes)
+ ) {
+ return completed;
+ }
+ const classArms = [];
+ const attributeArms = new Map();
+ const gatedAttributeArms = new Map();
+
+ for (const selector of pseudo.nodes) {
+ if (selector.type !== 'selector') continue;
+ if (selector.nodes.length === 1) {
+ const node = selector.nodes[0];
+ if (node.type === 'class' && !node.value.startsWith('astryx-')) {
+ classArms.push({selector, token: node.value});
+ } else if (
+ node.type === 'attribute' &&
+ node.attribute.startsWith('data-')
+ ) {
+ attributeArms.set(
+ `${node.attribute.slice('data-'.length)}\0${node.value ?? ''}`,
+ selector,
+ );
+ }
+ continue;
+ }
+ if (selector.nodes.length !== 2) continue;
+ const [gate, attribute] = selector.nodes;
+ if (
+ gate.type !== 'pseudo' ||
+ gate.value !== ':where' ||
+ !Array.isArray(gate.nodes) ||
+ gate.nodes.length !== 1 ||
+ gate.nodes[0]?.type !== 'selector' ||
+ gate.nodes[0].nodes.length !== 1 ||
+ gate.nodes[0].nodes[0]?.type !== 'class' ||
+ !gate.nodes[0].nodes[0].value.startsWith('astryx-') ||
+ attribute.type !== 'attribute' ||
+ !attribute.attribute.startsWith('data-')
+ ) {
+ continue;
+ }
+ const target = gate.nodes[0].nodes[0].value.slice('astryx-'.length);
+ gatedAttributeArms.set(
+ `${target}\0${attribute.attribute.slice('data-'.length)}\0${attribute.value ?? ''}`,
+ selector,
+ );
+ }
+
+ for (const {selector, token} of classArms) {
+ const candidates = dedupeCandidates(
+ targetNames.flatMap(target => candidatesFor(target, token)),
+ );
+ const gatedCandidates = conditionalTargets.flatMap(target =>
+ candidatesFor(target, token).map(candidate => ({target, candidate})),
+ );
+ if (candidates.length === 0 && gatedCandidates.length === 0) continue;
+ const directArms = candidates.map(candidate =>
+ attributeArms.get(candidateKey(candidate)),
+ );
+ const gatedArms = gatedCandidates.map(({target, candidate}) =>
+ gatedAttributeArms.get(`${target}\0${candidateKey(candidate)}`),
+ );
+ if ([...directArms, ...gatedArms].some(arm => arm == null)) continue;
+ completed.add(selector);
+ for (const arm of [...directArms, ...gatedArms]) completed.add(arm);
+ }
+ return completed;
+}
+
+/** @param {any} selector */
+function selectorCompounds(selector) {
+ /** @type {any[][]} */
+ const compounds = [[]];
+ for (const node of selector.nodes) {
+ if (node.type === 'combinator') compounds.push([]);
+ else {
+ const current = compounds.at(-1);
+ if (current) current.push(node);
+ }
+ }
+ return compounds;
+}
+
+/** @param {any[]} nodes */
+function directTargetNames(nodes) {
+ return nodes
+ .filter(node => node.type === 'class' && node.value.startsWith('astryx-'))
+ .map(node => node.value.slice('astryx-'.length))
+ .filter(target => TARGETS[target] != null || DYNAMIC_AXES[target] != null);
+}
+
+/** @param {any} pseudo @returns {any[]} */
+function nthFilterSelectors(pseudo) {
+ if (!Array.isArray(pseudo.nodes)) return [];
+ const filters = [];
+ let foundOf = false;
+ for (const selector of pseudo.nodes) {
+ if (selector.type !== 'selector') continue;
+ if (!foundOf) {
+ const ofIndex = selector.nodes.findIndex(
+ (/** @type {any} */ node) => node.type === 'tag' && node.value === 'of',
+ );
+ if (ofIndex === -1) continue;
+ foundOf = true;
+ filters.push({nodes: selector.nodes.slice(ofIndex + 1)});
+ continue;
+ }
+ filters.push(selector);
+ }
+ return filters;
+}
+
+/** @param {any} selector @returns {{guaranteed: string[], possible: string[]}} */
+function selectorSubjectTargetContext(selector) {
+ const compounds = selectorCompounds(selector);
+ const subject = compounds.at(-1) ?? [];
+ const nested = sameElementPseudoTargetContext(subject);
+ const direct = directTargetNames(subject);
+ return {
+ guaranteed: [...new Set([...direct, ...nested.guaranteed])],
+ possible: [...new Set([...direct, ...nested.possible])],
+ };
+}
+
+/**
+ * Targets exposed by selector-bearing pseudos on the same subject. A target is
+ * guaranteed only when every positive branch has it; otherwise it is merely
+ * possible and any added attribute arm must carry its own target gate. :not()
+ * exports possible context only, because its argument identifies what the
+ * subject is not. nth `of` lists behave like positive selector lists because
+ * the matched child must satisfy one filter branch.
+ *
+ * @param {any[]} nodes
+ * @returns {{guaranteed: string[], possible: string[]}}
+ */
+function sameElementPseudoTargetContext(nodes) {
+ const guaranteed = [];
+ const possible = [];
+ for (const node of nodes) {
+ if (node.type !== 'pseudo' || !Array.isArray(node.nodes)) continue;
+
+ const isPositiveList =
+ node.value === ':is' ||
+ node.value === ':where' ||
+ node.value === ':nth-child' ||
+ node.value === ':nth-last-child';
+ const isNegativeList = node.value === ':not';
+ if (!isPositiveList && !isNegativeList) continue;
+
+ const selectors =
+ node.value === ':nth-child' || node.value === ':nth-last-child'
+ ? nthFilterSelectors(node)
+ : node.nodes.filter(
+ /** @param {any} selector */ selector =>
+ selector.type === 'selector',
+ );
+ const branchContexts = selectors.map(selectorSubjectTargetContext);
+ if (branchContexts.length === 0) continue;
+
+ if (isPositiveList) {
+ for (const target of branchContexts[0].guaranteed) {
+ if (
+ branchContexts.every(
+ /** @param {{guaranteed: string[]}} branch */ branch =>
+ branch.guaranteed.includes(target),
+ )
+ ) {
+ guaranteed.push(target);
+ }
+ }
+ }
+ for (const branch of branchContexts) {
+ possible.push(...branch.possible);
+ }
+ }
+ return {
+ guaranteed: [...new Set(guaranteed)],
+ possible: [...new Set([...guaranteed, ...possible])],
+ };
+}
+
+/** @param {any} pseudo @param {string[]} possibleTargets */
+function migrateNthSelectorPseudo(pseudo, possibleTargets) {
+ for (const selector of nthFilterSelectors(pseudo)) {
+ migrateSelectorNode(selector, [], possibleTargets);
+ }
+}
+
+/**
+ * @param {any[]} nodes
+ * @param {string[]} inheritedTargets
+ * @param {string[]} inheritedConditionalTargets
+ */
+function migrateCompound(
+ nodes,
+ inheritedTargets = [],
+ inheritedConditionalTargets = [],
+) {
+ const directTargets = [
+ ...new Set([...inheritedTargets, ...directTargetNames(nodes)]),
+ ];
+ const pseudoContext = sameElementPseudoTargetContext(nodes);
+ const guaranteedTargets = [
+ ...new Set([...directTargets, ...pseudoContext.guaranteed]),
+ ];
+ const possibleTargets = [
+ ...new Set([
+ ...guaranteedTargets,
+ ...inheritedConditionalTargets,
+ ...pseudoContext.possible,
+ ]),
+ ];
+ const conditionalTargets = possibleTargets.filter(
+ target => !guaranteedTargets.includes(target),
+ );
+
+ // Recurse into every selector-bearing pseudo. :is(), :where(), and :not()
+ // constrain the same subject as the surrounding compound, so their rightmost
+ // compound inherits only the target context guaranteed outside the pseudo.
+ // Relational pseudos such as :has() traverse their own targets independently.
+ for (const node of [...nodes]) {
+ if (node.type !== 'pseudo' || !Array.isArray(node.nodes)) continue;
+ const completedArms = completedBehaviorPreservingUnionArms(
+ node,
+ guaranteedTargets,
+ conditionalTargets,
+ );
+ const selectorArms = node.nodes.filter(
+ (/** @type {any} */ selector) => selector.type === 'selector',
+ );
+ if (
+ completedArms.size > 0 &&
+ completedArms.size === selectorArms.length
+ ) {
+ continue;
+ }
+ if (node.value === ':nth-child' || node.value === ':nth-last-child') {
+ migrateNthSelectorPseudo(node, possibleTargets);
+ continue;
+ }
+ const isSameElementPseudo = SAME_ELEMENT_FUNCTIONAL_PSEUDOS.has(node.value);
+ const nestedTargets = isSameElementPseudo ? guaranteedTargets : [];
+ const nestedConditionalTargets = isSameElementPseudo
+ ? conditionalTargets
+ : [];
+ for (const selector of selectorArms) {
+ if (completedArms.has(selector)) continue;
+ migrateSelectorNode(
+ selector,
+ nestedTargets,
+ nestedConditionalTargets,
+ );
+ }
+ }
+
+ if (guaranteedTargets.length === 0 && conditionalTargets.length === 0) return;
+ for (const node of [...nodes]) {
+ if (node.type !== 'class' || node.value.startsWith('astryx-')) continue;
+ const candidates = dedupeCandidates(
+ guaranteedTargets.flatMap(target => candidatesFor(target, node.value)),
+ );
+ /** @type {GatedCandidate[]} */
+ const gatedCandidates = [];
+ const seenGated = new Set();
+ for (const target of conditionalTargets) {
+ for (const candidate of candidatesFor(target, node.value)) {
+ const key = `${target}\0${candidateKey(candidate)}`;
+ if (seenGated.has(key)) continue;
+ seenGated.add(key);
+ gatedCandidates.push({target, candidate});
+ }
+ }
+ if (candidates.length === 0 && gatedCandidates.length === 0) continue;
+ node.replaceWith(
+ behaviorPreservingUnionNode(node, candidates, gatedCandidates),
+ );
+ }
+}
+
+/**
+ * @param {any} selector
+ * @param {string[]} [inheritedTargets]
+ * @param {string[]} [inheritedConditionalTargets]
+ */
+function migrateSelectorNode(
+ selector,
+ inheritedTargets = [],
+ inheritedConditionalTargets = [],
+) {
+ const compounds = selectorCompounds(selector);
+ const subjectIndex = compounds.length - 1;
+ compounds.forEach((compound, index) => {
+ migrateCompound(
+ compound,
+ index === subjectIndex ? inheritedTargets : [],
+ index === subjectIndex ? inheritedConditionalTargets : [],
+ );
+ });
+}
+
+/** @typedef {{guaranteed: string[], possible: string[]}} TargetContext */
+
+/** @param {TargetContext[]} contexts @returns {TargetContext} */
+function combineSelectorListContexts(contexts) {
+ if (contexts.length === 0) return {guaranteed: [], possible: []};
+ const guaranteed = contexts[0].guaranteed.filter(target =>
+ contexts.every(context => context.guaranteed.includes(target)),
+ );
+ return {
+ guaranteed,
+ possible: [
+ ...new Set(contexts.flatMap(context => context.possible)),
+ ],
+ };
+}
+
+/** @param {any} selector @returns {{guaranteed: boolean, possible: boolean}} */
+function selectorSubjectNestingContext(selector) {
+ const compounds = selectorCompounds(selector);
+ return sameElementPseudoNestingContext(compounds.at(-1) ?? []);
+}
+
+/** @param {any[]} nodes @returns {{guaranteed: boolean, possible: boolean}} */
+function sameElementPseudoNestingContext(nodes) {
+ let guaranteed = nodes.some(node => node.type === 'nesting');
+ let possible = guaranteed;
+ for (const node of nodes) {
+ if (node.type !== 'pseudo' || !Array.isArray(node.nodes)) continue;
+ const isPositiveList =
+ node.value === ':is' ||
+ node.value === ':where' ||
+ node.value === ':nth-child' ||
+ node.value === ':nth-last-child';
+ const isNegativeList = node.value === ':not';
+ if (!isPositiveList && !isNegativeList) continue;
+ const selectors =
+ node.value === ':nth-child' || node.value === ':nth-last-child'
+ ? nthFilterSelectors(node)
+ : node.nodes.filter(
+ /** @param {any} selector */ selector =>
+ selector.type === 'selector',
+ );
+ const branches = selectors.map(selectorSubjectNestingContext);
+ if (branches.length === 0) continue;
+ if (
+ isPositiveList &&
+ branches.every(
+ /** @param {{guaranteed: boolean}} branch */ branch =>
+ branch.guaranteed,
+ )
+ ) {
+ guaranteed = true;
+ }
+ if (
+ branches.some(
+ /** @param {{possible: boolean}} branch */ branch => branch.possible,
+ )
+ ) {
+ possible = true;
+ }
+ }
+ return {guaranteed, possible};
+}
+
+/**
+ * @param {string} selector
+ * @param {TargetContext} [parentContext]
+ * @returns {{text: string, context: TargetContext}}
+ */
+function migrateSelectorTextWithContext(
+ selector,
+ parentContext = {guaranteed: [], possible: []},
+) {
+ /** @type {TargetContext} */
+ let context = {guaranteed: [], possible: []};
+ const text = selectorParser(selectors => {
+ /** @type {TargetContext[]} */
+ const branchContexts = [];
+ selectors.each(selectorNode => {
+ const nesting = selectorSubjectNestingContext(selectorNode);
+ const inheritedTargets = nesting.guaranteed
+ ? parentContext.guaranteed
+ : [];
+ const inheritedConditionalTargets = nesting.guaranteed
+ ? parentContext.possible.filter(
+ target => !parentContext.guaranteed.includes(target),
+ )
+ : nesting.possible
+ ? parentContext.possible
+ : [];
+ migrateSelectorNode(
+ selectorNode,
+ inheritedTargets,
+ inheritedConditionalTargets,
+ );
+
+ const own = selectorSubjectTargetContext(selectorNode);
+ branchContexts.push({
+ guaranteed: [
+ ...new Set([
+ ...own.guaranteed,
+ ...(nesting.guaranteed ? parentContext.guaranteed : []),
+ ]),
+ ],
+ possible: [
+ ...new Set([
+ ...own.possible,
+ ...(nesting.possible ? parentContext.possible : []),
+ ]),
+ ],
+ });
+ });
+ context = combineSelectorListContexts(branchContexts);
+ }).processSync(selector, {lossless: true});
+ return {text, context};
+}
+
+/** @param {string} selector */
+function migrateSelectorText(selector) {
+ return migrateSelectorTextWithContext(selector).text;
+}
+
+/**
+ * Transform the outer parenthesized selector groups in an @scope prelude while
+ * preserving nested functional-pseudo parentheses inside each selector.
+ *
+ * @param {string} params
+ */
+function migrateScopeParams(params) {
+ let result = '';
+ let last = 0;
+ let depth = 0;
+ let groupStart = -1;
+ let quote = '';
+ let escaped = false;
+
+ for (let index = 0; index < params.length; index++) {
+ const char = params[index];
+ if (escaped) {
+ escaped = false;
+ continue;
+ }
+ if (char === '\\') {
+ escaped = true;
+ continue;
+ }
+ if (quote) {
+ if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'") {
+ quote = char;
+ continue;
+ }
+ if (char === '(') {
+ if (depth === 0) {
+ result += params.slice(last, index + 1);
+ groupStart = index + 1;
+ }
+ depth++;
+ continue;
+ }
+ if (char === ')' && depth > 0) {
+ depth--;
+ if (depth === 0 && groupStart >= 0) {
+ result += migrateSelectorText(params.slice(groupStart, index));
+ result += ')';
+ last = index + 1;
+ groupStart = -1;
+ }
+ }
+ }
+ return result + params.slice(last);
+}
+
+/** @param {string} source @param {string} from @returns {string} */
+export function migrateAstryxThemeSelectors(source, from = 'styles.css') {
+ const root = postcss.parse(source, {from});
+ const existingComments = new Set();
+ root.walkComments(comment => {
+ existingComments.add(comment.text.trim());
+ });
+
+ /** @param {any} node @param {string} original */
+ const addParseTodo = (node, original) => {
+ const text = `TODO(astryx upgrade): verify selector ${original}; the CSS selector parser could not migrate it safely.`;
+ if (!existingComments.has(text)) {
+ node.before(postcss.comment({text}));
+ existingComments.add(text);
+ }
+ };
+
+ /** @type {WeakMap<object, TargetContext>} */
+ const ruleContexts = new WeakMap();
+ root.walkRules(rule => {
+ const originalSelector = rule.selector;
+ /** @type {any} */
+ let parent = rule.parent;
+ while (parent && parent.type !== 'rule' && parent.type !== 'root') {
+ parent = parent.parent;
+ }
+ const parentContext =
+ parent?.type === 'rule'
+ ? ruleContexts.get(parent) ?? {guaranteed: [], possible: []}
+ : {guaranteed: [], possible: []};
+ try {
+ const migrated = migrateSelectorTextWithContext(
+ originalSelector,
+ parentContext,
+ );
+ rule.selector = migrated.text;
+ ruleContexts.set(rule, migrated.context);
+ } catch {
+ ruleContexts.set(rule, {guaranteed: [], possible: []});
+ addParseTodo(rule, originalSelector);
+ }
+ });
+
+ root.walkAtRules('scope', atRule => {
+ const originalParams = atRule.params;
+ try {
+ atRule.params = migrateScopeParams(originalParams);
+ } catch {
+ addParseTodo(atRule, `@scope ${originalParams}`);
+ }
+ });
+
+ return root.toString();
+}
+
+/**
+ * @param {import('../../../../authoring/codemod/type').AstryxCodemodFile} file
+ * @returns {string | null | undefined}
+ */
+export default function transformer(file) {
+ if (path.extname(file.path).toLowerCase() !== '.css') return undefined;
+ const result = migrateAstryxThemeSelectors(file.source, file.path);
+ return result === file.source ? undefined : result;
+}
diff --git a/packages/cli/assets/codemods/transforms/next/migrate-astryx-theme-selectors-v0.5.4-data.mjs b/packages/cli/assets/codemods/transforms/next/migrate-astryx-theme-selectors-v0.5.4-data.mjs
new file mode 100644
index 0000000000..e87a91b522
--- /dev/null
+++ b/packages/cli/assets/codemods/transforms/next/migrate-astryx-theme-selectors-v0.5.4-data.mjs
@@ -0,0 +1,216 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * Frozen selector migration data extracted from every public v0.5.4
+ * themeProps(target, props) callsite, the literal-union types flowing into it,
+ * and same-element primitive composition through mergeProps. Each emitted bare
+ * class token maps to its exact [axis, value].
+ *
+ * Unbounded v0.5.4 values are represented separately below. Keep both tables
+ * release-specific: later source may add values that v0.5.4 never emitted.
+ */
+// Keep one target per line so reviewers can compare the frozen release snapshot.
+/** @type {Record<string, Record<string, [string, string] | Array<[string, string]>>>} */
+// prettier-ignore
+export const V054_THEME_SELECTOR_TARGETS = {
+ "alert-dialog": {"standard":["variant","standard"]},
+ "app-shell": {"elevated":["variant","elevated"],"section":["variant","section"],"surface":["variant","surface"],"wash":["variant","wash"]},
+ "app-shell-header": {"elevated":["variant","elevated"],"section":["variant","section"],"surface":["variant","surface"],"wash":["variant","wash"]},
+ "app-shell-sidenav": {"elevated":["variant","elevated"],"section":["variant","section"],"surface":["variant","surface"],"wash":["variant","wash"]},
+ "aspect-ratio": {"ellipse":["shape","ellipse"],"rectangle":["shape","rectangle"]},
+ "avatar": {"circle":["shape","circle"],"lg":["size","lg"],"md":["size","md"],"rounded":["shape","rounded"],"size-128":["size","128"],"size-144":["size","144"],"size-16":["size","16"],"size-180":["size","180"],"size-20":["size","20"],"size-24":["size","24"],"size-32":["size","32"],"size-36":["size","36"],"size-40":["size","40"],"size-48":["size","48"],"size-60":["size","60"],"size-64":["size","64"],"size-72":["size","72"],"size-96":["size","96"],"sm":["size","sm"],"square":["shape","square"],"xl":["size","xl"],"xsm":["size","xsm"]},
+ "avatar-fallback": {"lg":["size","lg"],"md":["size","md"],"size-128":["size","128"],"size-144":["size","144"],"size-16":["size","16"],"size-180":["size","180"],"size-20":["size","20"],"size-24":["size","24"],"size-32":["size","32"],"size-36":["size","36"],"size-40":["size","40"],"size-48":["size","48"],"size-60":["size","60"],"size-64":["size","64"],"size-72":["size","72"],"size-96":["size","96"],"sm":["size","sm"],"xl":["size","xl"],"xsm":["size","xsm"]},
+ "avatar-group": {"circle":["shape","circle"],"lg":["size","lg"],"md":["size","md"],"rounded":["shape","rounded"],"size-128":["size","128"],"size-144":["size","144"],"size-16":["size","16"],"size-180":["size","180"],"size-20":["size","20"],"size-24":["size","24"],"size-32":["size","32"],"size-36":["size","36"],"size-40":["size","40"],"size-48":["size","48"],"size-60":["size","60"],"size-64":["size","64"],"size-72":["size","72"],"size-96":["size","96"],"sm":["size","sm"],"square":["shape","square"],"xl":["size","xl"],"xsm":["size","xsm"]},
+ "avatar-group-overflow": {"circle":["shape","circle"],"lg":["size","lg"],"md":["size","md"],"rounded":["shape","rounded"],"size-128":["size","128"],"size-144":["size","144"],"size-16":["size","16"],"size-180":["size","180"],"size-20":["size","20"],"size-24":["size","24"],"size-32":["size","32"],"size-36":["size","36"],"size-40":["size","40"],"size-48":["size","48"],"size-60":["size","60"],"size-64":["size","64"],"size-72":["size","72"],"size-96":["size","96"],"sm":["size","sm"],"square":["shape","square"],"xl":["size","xl"],"xsm":["size","xsm"]},
+ "avatar-status-dot": {"error":["variant","error"],"neutral":["variant","neutral"],"success":["variant","success"]},
+ "avatar-status-dot-glyph": {"minus":["shape","minus"],"ring":["shape","ring"]},
+ "badge": {"blue":["variant","blue"],"cyan":["variant","cyan"],"error":["variant","error"],"green":["variant","green"],"info":["variant","info"],"neutral":["variant","neutral"],"orange":["variant","orange"],"pink":["variant","pink"],"purple":["variant","purple"],"red":["variant","red"],"success":["variant","success"],"teal":["variant","teal"],"warning":["variant","warning"],"yellow":["variant","yellow"]},
+ "banner": {"card":["container","card"],"error":["status","error"],"info":["status","info"],"section":["container","section"],"success":["status","success"],"warning":["status","warning"]},
+ "banner-content": {"card":["container","card"],"error":["status","error"],"info":["status","info"],"section":["container","section"],"success":["status","success"],"warning":["status","warning"]},
+ "banner-icon": {"accent":["color","accent"],"error":[["color","error"],["status","error"]],"info":["status","info"],"md":["size","md"],"success":[["color","success"],["status","success"]],"warning":[["color","warning"],["status","warning"]]},
+ "breadcrumb-item": {"default":["variant","default"],"supporting":["variant","supporting"]},
+ "breadcrumb-item-menu-trigger": {"default":["variant","default"],"supporting":["variant","supporting"]},
+ "breadcrumbs": {"default":["variant","default"],"supporting":["variant","supporting"]},
+ "button": {"destructive":["variant","destructive"],"ghost":["variant","ghost"],"high":["elevation","high"],"lg":["size","lg"],"low":["elevation","low"],"md":["size","md"],"med":["elevation","med"],"none":["elevation","none"],"primary":["variant","primary"],"secondary":["variant","secondary"],"sm":["size","sm"]},
+ "button-group": {"high":["elevation","high"],"horizontal":["orientation","horizontal"],"lg":["size","lg"],"low":["elevation","low"],"md":["size","md"],"med":["elevation","med"],"none":["elevation","none"],"sm":["size","sm"],"vertical":["orientation","vertical"]},
+ "calendar": {"range":["mode","range"],"single":["mode","single"]},
+ "calendar-day": {"disabled":["disabled","disabled"],"in-range":["in-range","in-range"],"selected":["selected","selected"],"today":["today","today"],"today-in-range":["marker","today-in-range"],"today-only":["marker","today-only"]},
+ "calendar-nav": {"disabled":["disabled","disabled"],"ghost":["variant","ghost"],"lg":["size","lg"],"md":["size","md"],"next":["nav","next"],"none":["elevation","none"],"prev":["nav","prev"],"sm":["size","sm"]},
+ "card": {"blue":["variant","blue"],"cyan":["variant","cyan"],"default":["variant","default"],"gray":["variant","gray"],"green":["variant","green"],"high":["elevation","high"],"low":["elevation","low"],"med":["elevation","med"],"muted":["variant","muted"],"none":["elevation","none"],"orange":["variant","orange"],"pink":["variant","pink"],"purple":["variant","purple"],"red":["variant","red"],"teal":["variant","teal"],"transparent":["variant","transparent"],"yellow":["variant","yellow"]},
+ "carousel-scroller": {"edge-fade":["edgeFade","edge-fade"],"gap-0":["gap","0"],"gap-0.5":["gap","0.5"],"gap-1":["gap","1"],"gap-1.5":["gap","1.5"],"gap-2":["gap","2"],"gap-3":["gap","3"],"gap-4":["gap","4"],"padding-0":["padding","0"],"padding-0.5":["padding","0.5"],"padding-1":["padding","1"],"padding-1.5":["padding","1.5"],"padding-10":["padding","10"],"padding-2":["padding","2"],"padding-3":["padding","3"],"padding-4":["padding","4"],"padding-5":["padding","5"],"padding-6":["padding","6"],"padding-8":["padding","8"],"snap":["snap","snap"]},
+ "center": {"both":["axis","both"],"horizontal":["axis","horizontal"],"vertical":["axis","vertical"]},
+ "chat-composer": {"balanced":["density","balanced"],"compact":["density","compact"],"spacious":["density","spacious"]},
+ "chat-composer-drawer": {"collapsed":["collapsed","collapsed"]},
+ "chat-layout": {"balanced":["density","balanced"],"compact":["density","compact"],"spacious":["density","spacious"]},
+ "chat-message": {"assistant":["sender","assistant"],"balanced":["density","balanced"],"compact":["density","compact"],"spacious":["density","spacious"],"system":["sender","system"],"user":["sender","user"]},
+ "chat-message-bubble": {"assistant":["sender","assistant"],"balanced":["density","balanced"],"compact":["density","compact"],"filled":["variant","filled"],"ghost":["variant","ghost"],"spacious":["density","spacious"],"system":["sender","system"],"user":["sender","user"]},
+ "chat-message-list": {"balanced":["density","balanced"],"compact":["density","compact"],"spacious":["density","spacious"]},
+ "chat-send-button": {"md":["size","md"],"none":["elevation","none"],"primary":["variant","primary"],"secondary":["variant","secondary"],"sm":["size","sm"]},
+ "chat-system-message": {"default":["variant","default"],"divider":["variant","divider"]},
+ "checkbox": {"checked":["checked","checked"],"disabled":["disabled","disabled"],"indeterminate":["checked","indeterminate"],"md":["size","md"],"sm":["size","sm"]},
+ "checkbox-indicator": {"checked":["checked","checked"],"disabled":["disabled","disabled"],"indeterminate":["checked","indeterminate"],"md":["size","md"],"sm":["size","sm"]},
+ "checkbox-indicator-check": {"md":["size","md"],"sm":["size","sm"]},
+ "checkbox-indicator-dash": {"md":["size","md"],"sm":["size","sm"]},
+ "checkbox-input": {"md":["size","md"],"sm":["size","sm"]},
+ "citation": {"label":["variant","label"],"number":["variant","number"]},
+ "clickable-card": {"blue":["variant","blue"],"cyan":["variant","cyan"],"default":["variant","default"],"gray":["variant","gray"],"green":["variant","green"],"high":["elevation","high"],"low":["elevation","low"],"med":["elevation","med"],"muted":["variant","muted"],"none":["elevation","none"],"orange":["variant","orange"],"pink":["variant","pink"],"purple":["variant","purple"],"red":["variant","red"],"teal":["variant","teal"],"transparent":["variant","transparent"],"yellow":["variant","yellow"]},
+ "code": {"inherit":["color","inherit"],"primary":["color","primary"],"secondary":["color","secondary"]},
+ "code-block": {"card":["container","card"],"md":["size","md"],"section":["container","section"],"sm":["size","sm"]},
+ "code-block-copy-button": {"ghost":["variant","ghost"],"none":["elevation","none"],"sm":["size","sm"]},
+ "code-block-header": {"card":["container","card"],"md":["size","md"],"section":["container","section"],"sm":["size","sm"]},
+ "code-block-title": {"md":["size","md"],"sm":["size","sm"]},
+ "codeblock": {"card":["container","card"],"md":["size","md"],"section":["container","section"],"sm":["size","sm"]},
+ "codeblock-copy-button": {"ghost":["variant","ghost"],"none":["elevation","none"],"sm":["size","sm"]},
+ "codeblock-header": {"card":["container","card"],"md":["size","md"],"section":["container","section"],"sm":["size","sm"]},
+ "codeblock-title": {"md":["size","md"],"sm":["size","sm"]},
+ "collapsible": {"balanced":["density","balanced"],"compact":["density","compact"],"spacious":["density","spacious"]},
+ "collapsible-content": {"balanced":["density","balanced"],"compact":["density","compact"],"spacious":["density","spacious"]},
+ "collapsible-group": {"balanced":["density","balanced"],"compact":["density","compact"],"spacious":["density","spacious"]},
+ "collapsible-trigger": {"balanced":["density","balanced"],"compact":["density","compact"],"spacious":["density","spacious"]},
+ "complex-selector": {"error":["status","error"],"ghost":["variant","ghost"],"input":["variant","input"],"lg":["size","lg"],"md":["size","md"],"sm":["size","sm"],"success":["status","success"],"warning":["status","warning"]},
+ "complex-selector-indicator-icon": {"collapsed":["state","collapsed"],"expanded":["state","expanded"],"secondary":["color","secondary"],"sm":["size","sm"]},
+ "date-input": {"disabled":["disabled","disabled"],"error":["status","error"],"lg":["size","lg"],"md":["size","md"],"sm":["size","sm"],"success":["status","success"],"warning":["status","warning"]},
+ "date-input-clear-icon": {"secondary":["color","secondary"],"sm":["size","sm"]},
+ "date-input-toggle-icon": {"collapsed":["state","collapsed"],"expanded":["state","expanded"],"secondary":["color","secondary"],"sm":["size","sm"]},
+ "date-range-input": {"disabled":["disabled","disabled"],"error":["status","error"],"lg":["size","lg"],"md":["size","md"],"sm":["size","sm"],"success":["status","success"],"warning":["status","warning"]},
+ "date-range-input-clear-icon": {"secondary":["color","secondary"],"sm":["size","sm"]},
+ "date-range-input-toggle-icon": {"collapsed":["state","collapsed"],"expanded":["state","expanded"],"secondary":["color","secondary"],"sm":["size","sm"]},
+ "date-time-input": {"disabled":["disabled","disabled"],"error":["status","error"],"lg":["size","lg"],"md":["size","md"],"sm":["size","sm"],"success":["status","success"],"warning":["status","warning"]},
+ "date-time-input-clock-icon": {"secondary":["color","secondary"],"sm":["size","sm"]},
+ "date-time-input-date-segment": {"error":["status","error"],"lg":["size","lg"],"md":["size","md"],"sm":["size","sm"],"success":["status","success"],"warning":["status","warning"]},
+ "date-time-input-time-segment": {"error":["status","error"],"lg":["size","lg"],"md":["size","md"],"sm":["size","sm"],"success":["status","success"],"warning":["status","warning"]},
+ "date-time-input-toggle-icon": {"collapsed":["state","collapsed"],"expanded":["state","expanded"],"secondary":["color","secondary"],"sm":["size","sm"]},
+ "dialog": {"fullscreen":["variant","fullscreen"],"standard":["variant","standard"]},
+ "divider": {"horizontal":["orientation","horizontal"],"strong":["variant","strong"],"subtle":["variant","subtle"],"vertical":["orientation","vertical"]},
+ "dropdown-menu": {"bottom-sheet":["presentation","bottom-sheet"]},
+ "dropdown-menu-divider": {"horizontal":["orientation","horizontal"],"subtle":["variant","subtle"]},
+ "dropdown-menu-indicator-icon": {"secondary":["color","secondary"],"sm":["size","sm"]},
+ "dropdown-menu-item": {"balanced":["density","balanced"],"center":["align","center"],"destructive":["variant","destructive"],"lg":["size","lg"],"md":["size","md"],"sm":["size","sm"]},
+ "dropdown-menu-radio": {"checked":["checked","checked"],"disabled":["disabled","disabled"],"md":["size","md"],"sm":["size","sm"]},
+ "empty-state": {"compact":["variant","compact"]},
+ "empty-state-description": {"compact":["variant","compact"]},
+ "empty-state-title": {"compact":["variant","compact"]},
+ "field": {"horizontal-labels":["layout","horizontal-labels"]},
+ "field-status": {"attached":["variant","attached"],"detached":["variant","detached"],"error":["type","error"],"success":["type","success"],"tooltip":["variant","tooltip"],"warning":["type","warning"]},
+ "field-status-icon": {"error":["type","error"],"inherit":["color","inherit"],"sm":["size","sm"],"success":["type","success"],"warning":["type","warning"]},
+ "file-input": {"dropzone":["mode","dropzone"],"error":["status","error"],"input":["mode","input"],"success":["status","success"],"warning":["status","warning"]},
+ "form-layout": {"horizontal":["direction","horizontal"],"horizontal-labels":["direction","horizontal-labels"],"vertical":["direction","vertical"]},
+ "grid": {"center":[["align","center"],["justify","center"]],"end":[["align","end"],["justify","end"]],"gap-0":["gap","0"],"gap-0.5":["gap","0.5"],"gap-1":["gap","1"],"gap-1.5":["gap","1.5"],"gap-10":["gap","10"],"gap-2":["gap","2"],"gap-3":["gap","3"],"gap-4":["gap","4"],"gap-5":["gap","5"],"gap-6":["gap","6"],"gap-8":["gap","8"],"start":[["align","start"],["justify","start"]],"stretch":[["align","stretch"],["justify","stretch"]]},
+ "heading": {"accent":["color","accent"],"disabled":["color","disabled"],"display-1":["type","display-1"],"display-2":["type","display-2"],"display-3":["type","display-3"],"hero":["type","hero"],"inherit":["color","inherit"],"level-1":["level","1"],"level-2":["level","2"],"level-3":["level","3"],"level-4":["level","4"],"level-5":["level","5"],"level-6":["level","6"],"placeholder":["color","placeholder"],"primary":["color","primary"],"secondary":["color","secondary"]},
+ "icon": {"accent":["color","accent"],"blue":["color","blue"],"cyan":["color","cyan"],"disabled":["color","disabled"],"error":["color","error"],"gray":["color","gray"],"green":["color","green"],"inherit":["color","inherit"],"lg":["size","lg"],"md":["size","md"],"orange":["color","orange"],"pink":["color","pink"],"primary":["color","primary"],"purple":["color","purple"],"red":["color","red"],"secondary":["color","secondary"],"sm":["size","sm"],"success":["color","success"],"teal":["color","teal"],"tertiary":["color","tertiary"],"warning":["color","warning"],"xsm":["size","xsm"],"yellow":["color","yellow"]},
+ "input-clear-button": {"ghost":["variant","ghost"],"none":["elevation","none"],"sm":["size","sm"]},
+ "input-clear-icon": {"secondary":["color","secondary"],"sm":["size","sm"]},
+ "input-group": {"error":["status","error"],"lg":["size","lg"],"md":["size","md"],"sm":["size","sm"],"success":["status","success"],"warning":["status","warning"]},
+ "input-status-icon": {"error":[["color","error"],["status","error"]],"lg":["size","lg"],"md":["size","md"],"sm":["size","sm"],"success":[["color","success"],["status","success"]],"warning":[["color","warning"],["status","warning"]],"xsm":["size","xsm"]},
+ "item": {"balanced":["density","balanced"],"center":["align","center"],"compact":["density","compact"],"spacious":["density","spacious"],"start":["align","start"]},
+ "layout": {"auto":["height","auto"],"fill":["height","fill"]},
+ "link": {"accent":["color","accent"],"disabled":["color","disabled"],"inherit":["color","inherit"],"placeholder":["color","placeholder"],"primary":["color","primary"],"secondary":["color","secondary"]},
+ "list": {"balanced":["density","balanced"],"circle":["listStyle","circle"],"compact":["density","compact"],"decimal":["listStyle","decimal"],"disc":["listStyle","disc"],"none":["listStyle","none"],"spacious":["density","spacious"]},
+ "list-item": {"balanced":["density","balanced"],"center":["align","center"],"compact":["density","compact"],"spacious":["density","spacious"]},
+ "markdown": {"compact":["density","compact"],"default":["density","default"]},
+ "markdown-blockquote": {"compact":["density","compact"],"default":["density","default"]},
+ "markdown-codeblock": {"compact":["density","compact"],"default":["density","default"]},
+ "markdown-heading": {"compact":["density","compact"],"default":["density","default"],"level-1":["level","1"],"level-2":["level","2"],"level-3":["level","3"],"level-4":["level","4"],"level-5":["level","5"],"level-6":["level","6"]},
+ "markdown-hr": {"compact":["density","compact"],"default":["density","default"]},
+ "markdown-image": {"compact":["density","compact"],"default":["density","default"]},
+ "markdown-list": {"compact":["density","compact"],"default":["density","default"]},
+ "markdown-paragraph": {"compact":["density","compact"],"default":["density","default"]},
+ "markdown-table": {"compact":["density","compact"],"default":["density","default"]},
+ "metadata-list": {"horizontal":["orientation","horizontal"],"multi":["columns","multi"],"single":["columns","single"],"vertical":["orientation","vertical"]},
+ "mobile-nav": {"end":["side","end"],"start":["side","start"]},
+ "more-menu": {"bottom-sheet":["presentation","bottom-sheet"]},
+ "multi-selector": {"disabled":["disabled","disabled"],"error":["status","error"],"ghost":["variant","ghost"],"input":["variant","input"],"lg":["size","lg"],"md":["size","md"],"readonly":["readonly","readonly"],"sm":["size","sm"],"success":["status","success"],"warning":["status","warning"]},
+ "multi-selector-clear-icon": {"secondary":["color","secondary"],"sm":["size","sm"]},
+ "multi-selector-indicator-icon": {"collapsed":["state","collapsed"],"expanded":["state","expanded"]},
+ "multi-selector-option": {"disabled":["disabled","disabled"],"lg":["size","lg"],"md":["size","md"],"select-all":["select-all","select-all"],"selected":["selected","selected"],"sm":["size","sm"]},
+ "nav-heading-menu": {"lg":["size","lg"],"md":["size","md"],"sm":["size","sm"]},
+ "nav-heading-menu-item": {"lg":["size","lg"],"md":["size","md"],"sm":["size","sm"]},
+ "number-input": {"disabled":["disabled","disabled"],"error":["status","error"],"lg":["size","lg"],"md":["size","md"],"readonly":["readonly","readonly"],"sm":["size","sm"],"success":["status","success"],"warning":["status","warning"]},
+ "outline": {"compact":["density","compact"],"default":["density","default"]},
+ "outline-item": {"active":["active","active"]},
+ "overlay-scrim": {"bottom":["position","bottom"],"fill":["position","fill"],"top":["position","top"]},
+ "pagination": {"compact":["variant","compact"],"count":["variant","count"],"dots":["variant","dots"],"input":["variant","input"],"md":["size","md"],"none":["variant","none"],"pages":["variant","pages"],"sm":["size","sm"]},
+ "pagination-dot": {"active":["active","active"],"md":["size","md"],"sm":["size","sm"]},
+ "pagination-input-label": {"md":["size","md"],"sm":["size","sm"]},
+ "pagination-input-total": {"md":["size","md"],"sm":["size","sm"]},
+ "progress-bar": {"accent":["variant","accent"],"error":["variant","error"],"neutral":["variant","neutral"],"success":["variant","success"],"warning":["variant","warning"]},
+ "progress-bar-fill": {"accent":["variant","accent"],"disabled":["variant","disabled"],"error":["variant","error"],"neutral":["variant","neutral"],"success":["variant","success"],"warning":["variant","warning"]},
+ "progress-bar-mark": {"accent":["variant","accent"],"disabled":["variant","disabled"],"error":["variant","error"],"fill":["placement","fill"],"neutral":["variant","neutral"],"success":["variant","success"],"track":["placement","track"],"warning":["variant","warning"]},
+ "progressbar": {"accent":["variant","accent"],"error":["variant","error"],"neutral":["variant","neutral"],"success":["variant","success"],"warning":["variant","warning"]},
+ "progressbar-fill": {"accent":["variant","accent"],"disabled":["variant","disabled"],"error":["variant","error"],"neutral":["variant","neutral"],"success":["variant","success"],"warning":["variant","warning"]},
+ "progressbar-mark": {"accent":["variant","accent"],"disabled":["variant","disabled"],"error":["variant","error"],"fill":["placement","fill"],"neutral":["variant","neutral"],"success":["variant","success"],"track":["placement","track"],"warning":["variant","warning"]},
+ "radio": {"checked":["checked","checked"],"disabled":["disabled","disabled"],"md":["size","md"],"sm":["size","sm"]},
+ "radio-dot": {"md":["size","md"],"sm":["size","sm"]},
+ "radio-indicator": {"checked":["checked","checked"],"disabled":["disabled","disabled"],"md":["size","md"],"sm":["size","sm"]},
+ "radio-indicator-dot": {"md":["size","md"],"sm":["size","sm"]},
+ "radio-list": {"horizontal":["orientation","horizontal"],"md":["size","md"],"sm":["size","sm"],"vertical":["orientation","vertical"]},
+ "radio-list-item": {"balanced":["density","balanced"],"center":["align","center"],"disabled":["disabled","disabled"],"md":["size","md"],"selected":["selected","selected"],"sm":["size","sm"]},
+ "section": {"muted":["variant","muted"],"section":["variant","section"],"transparent":["variant","transparent"]},
+ "segmented-control": {"lg":["size","lg"],"md":["size","md"],"sm":["size","sm"]},
+ "segmented-control-item": {"disabled":["disabled","disabled"],"lg":["size","lg"],"md":["size","md"],"selected":["selected","selected"],"sm":["size","sm"]},
+ "selectable-card": {"blue":["variant","blue"],"cyan":["variant","cyan"],"default":["variant","default"],"false":["selected","false"],"gray":["variant","gray"],"green":["variant","green"],"high":["elevation","high"],"low":["elevation","low"],"med":["elevation","med"],"muted":["variant","muted"],"none":["elevation","none"],"orange":["variant","orange"],"pink":["variant","pink"],"purple":["variant","purple"],"red":["variant","red"],"teal":["variant","teal"],"transparent":["variant","transparent"],"true":["selected","true"],"yellow":["variant","yellow"]},
+ "selector": {"disabled":["disabled","disabled"],"error":["status","error"],"ghost":["variant","ghost"],"input":["variant","input"],"lg":["size","lg"],"md":["size","md"],"readonly":["readonly","readonly"],"sm":["size","sm"],"success":["status","success"],"warning":["status","warning"]},
+ "selector-check": {"accent":["color","accent"],"checked":["checked","checked"],"disabled":[["color","disabled"],["disabled","disabled"]],"sm":["size","sm"]},
+ "selector-clear-icon": {"secondary":["color","secondary"],"sm":["size","sm"]},
+ "selector-indicator-icon": {"collapsed":["state","collapsed"],"expanded":["state","expanded"]},
+ "selector-option": {"balanced":["density","balanced"],"center":["align","center"]},
+ "selector-option-row": {"disabled":["disabled","disabled"],"lg":["size","lg"],"md":["size","md"],"selected":["selected","selected"],"sm":["size","sm"]},
+ "side-nav": {"topbar":["mode","topbar"]},
+ "side-nav-item": {"disabled":["disabled","disabled"],"lg":["size","lg"],"md":["size","md"],"selected":["selected","selected"],"sm":["size","sm"]},
+ "slider": {"disabled":["disabled","disabled"],"horizontal":["orientation","horizontal"],"vertical":["orientation","vertical"]},
+ "slider-thumb": {"disabled":["disabled","disabled"],"horizontal":["orientation","horizontal"],"vertical":["orientation","vertical"]},
+ "slider-track": {"horizontal":["orientation","horizontal"],"vertical":["orientation","vertical"]},
+ "spinner": {"default":["shade","default"],"inherit":["shade","inherit"],"lg":["size","lg"],"md":["size","md"],"onMedia":["shade","onMedia"],"sm":["size","sm"],"subtle":["shade","subtle"],"xl":["size","xl"]},
+ "stack": {"gap-0":["gap","0"],"gap-0.5":["gap","0.5"],"gap-1":["gap","1"],"gap-1.5":["gap","1.5"],"gap-10":["gap","10"],"gap-2":["gap","2"],"gap-3":["gap","3"],"gap-4":["gap","4"],"gap-5":["gap","5"],"gap-6":["gap","6"],"gap-8":["gap","8"],"horizontal":["direction","horizontal"],"nowrap":["wrap","nowrap"],"vertical":["direction","vertical"],"wrap":["wrap","wrap"],"wrap-reverse":["wrap","wrap-reverse"]},
+ "stack-item": {"fill":["size","fill"],"static":["size","static"]},
+ "status-dot": {"accent":["variant","accent"],"error":["variant","error"],"neutral":["variant","neutral"],"success":["variant","success"],"warning":["variant","warning"]},
+ "statusdot": {"accent":["variant","accent"],"error":["variant","error"],"neutral":["variant","neutral"],"success":["variant","success"],"warning":["variant","warning"]},
+ "step": {"accent":["status","accent"],"completed":["progress","completed"],"error":["status","error"],"in-progress":["progress","in-progress"],"not-started":["progress","not-started"],"success":["status","success"],"warning":["status","warning"]},
+ "step-description": {"accent":["status","accent"],"completed":["progress","completed"],"error":["status","error"],"in-progress":["progress","in-progress"],"not-started":["progress","not-started"],"success":["status","success"],"warning":["status","warning"]},
+ "step-indicator": {"accent":["status","accent"],"completed":["progress","completed"],"error":["status","error"],"in-progress":["progress","in-progress"],"not-started":["progress","not-started"],"success":["status","success"],"warning":["status","warning"]},
+ "step-label": {"accent":["status","accent"],"completed":["progress","completed"],"disabled":["disabled","disabled"],"error":["status","error"],"in-progress":["progress","in-progress"],"not-started":["progress","not-started"],"success":["status","success"],"warning":["status","warning"]},
+ "stepper": {"horizontal":["orientation","horizontal"],"on-track":["indicatorPosition","on-track"],"separated":["indicatorPosition","separated"],"vertical":["orientation","vertical"]},
+ "switch": {"checked":["checked","checked"],"disabled":["disabled","disabled"],"md":["size","md"],"sm":["size","sm"]},
+ "switch-field": {"spread":["labelSpacing","spread"],"start":["labelPosition","start"]},
+ "switch-thumb": {"checked":["checked","checked"],"md":["size","md"],"sm":["size","sm"]},
+ "tab": {"selected":["selected","selected"]},
+ "tab-indicator": {"selected":["selected","selected"]},
+ "tab-list": {"lg":["size","lg"],"md":["size","md"],"sm":["size","sm"]},
+ "table-cell": {"balanced":["density","balanced"],"compact":["density","compact"],"spacious":["density","spacious"]},
+ "table-header-cell": {"balanced":["density","balanced"],"compact":["density","compact"],"spacious":["density","spacious"]},
+ "text": {"accent":["color","accent"],"base":["size","base"],"body":["type","body"],"code":["type","code"],"disabled":["color","disabled"],"display-1":["type","display-1"],"display-2":["type","display-2"],"display-3":["type","display-3"],"inherit":[["color","inherit"],["type","inherit"]],"label":["type","label"],"large":["type","large"],"lg":["size","lg"],"placeholder":["color","placeholder"],"primary":["color","primary"],"secondary":["color","secondary"],"size-2xl":["size","2xl"],"size-2xs":["size","2xs"],"size-3xl":["size","3xl"],"size-3xs":["size","3xs"],"size-4xl":["size","4xl"],"size-4xs":["size","4xs"],"sm":["size","sm"],"supporting":["type","supporting"],"xl":["size","xl"],"xsm":["size","xsm"]},
+ "text-area": {"disabled":["disabled","disabled"],"error":["status","error"],"lg":["size","lg"],"md":["size","md"],"readonly":["readonly","readonly"],"sm":["size","sm"],"success":["status","success"],"warning":["status","warning"]},
+ "text-input": {"disabled":["disabled","disabled"],"error":["status","error"],"lg":["size","lg"],"md":["size","md"],"readonly":["readonly","readonly"],"sm":["size","sm"],"success":["status","success"],"warning":["status","warning"]},
+ "textarea": {"disabled":["disabled","disabled"],"error":["status","error"],"lg":["size","lg"],"md":["size","md"],"readonly":["readonly","readonly"],"sm":["size","sm"],"success":["status","success"],"warning":["status","warning"]},
+ "time-input": {"disabled":["disabled","disabled"],"error":["status","error"],"lg":["size","lg"],"md":["size","md"],"sm":["size","sm"],"success":["status","success"],"warning":["status","warning"]},
+ "timestamp": {"accent":["color","accent"],"base":["size","base"],"body":["type","body"],"code":["type","code"],"date":["format","date"],"date_long":["format","date_long"],"date_time":["format","date_time"],"date_weekday":["format","date_weekday"],"disabled":["color","disabled"],"display-1":["type","display-1"],"display-2":["type","display-2"],"display-3":["type","display-3"],"inherit":[["color","inherit"],["type","inherit"]],"label":["type","label"],"large":["type","large"],"lg":["size","lg"],"placeholder":["color","placeholder"],"primary":["color","primary"],"relative":["format","relative"],"relative_short":["format","relative_short"],"secondary":["color","secondary"],"size-2xl":["size","2xl"],"size-2xs":["size","2xs"],"size-3xl":["size","3xl"],"size-3xs":["size","3xs"],"size-4xl":["size","4xl"],"size-4xs":["size","4xs"],"sm":["size","sm"],"supporting":["type","supporting"],"system_date":["format","system_date"],"system_date_time":["format","system_date_time"],"system_time":["format","system_time"],"time":["format","time"],"unix_seconds":["format","unix_seconds"],"xl":["size","xl"],"xsm":["size","xsm"]},
+ "timestamp-copy-button": {"ghost":["variant","ghost"],"none":["elevation","none"],"sm":["size","sm"]},
+ "toast": {"error":["type","error"],"info":["type","info"]},
+ "toggle-button": {"false":["isPressed","false"],"ghost":["variant","ghost"],"high":["elevation","high"],"lg":["size","lg"],"low":["elevation","low"],"md":["size","md"],"med":["elevation","med"],"none":["elevation","none"],"sm":["size","sm"],"true":["isPressed","true"]},
+ "token": {"blue":["color","blue"],"cyan":["color","cyan"],"default":["color","default"],"gray":["color","gray"],"green":["color","green"],"lg":["size","lg"],"md":["size","md"],"orange":["color","orange"],"pink":["color","pink"],"purple":["color","purple"],"red":["color","red"],"sm":["size","sm"],"teal":["color","teal"],"yellow":["color","yellow"]},
+ "tokenizer": {"disabled":["disabled","disabled"],"error":["status","error"],"lg":["size","lg"],"md":["size","md"],"sm":["size","sm"],"success":["status","success"],"warning":["status","warning"]},
+ "toolbar": {"lg":["size","lg"],"md":["size","md"],"sm":["size","sm"]},
+ "top-nav": {"mobile-bar":["mode","mobile-bar"]},
+ "top-nav-item": {"drawer":["mode","drawer"],"selected":["selected","selected"]},
+ "top-nav-mega-menu": {"drawer":["mode","drawer"]},
+ "top-nav-mega-menu-item": {"drawer":["mode","drawer"]},
+ "tree-list": {"balanced":["density","balanced"],"compact":["density","compact"],"lineGuides":["variant","lineGuides"],"noGuides":["variant","noGuides"],"spacious":["density","spacious"]},
+ "tree-list-chevron": {"collapsed":["state","collapsed"],"expanded":["state","expanded"]},
+ "tree-list-item": {"balanced":["density","balanced"],"compact":["density","compact"],"disabled":["disabled","disabled"],"selected":["selected","selected"],"spacious":["density","spacious"]},
+ "tree-list-item-label": {"selected":["selected","selected"]},
+ "typeahead": {"error":["status","error"],"lg":["size","lg"],"md":["size","md"],"sm":["size","sm"],"success":["status","success"],"warning":["status","warning"]},
+};
+
+/** @type {Record<string, Array<{axis: string, token: 'class-value' | 'prefixed', prefix?: string}>>} */
+// prettier-ignore
+export const V054_THEME_SELECTOR_DYNAMIC_AXES = {
+ "code-block": [{"axis":"language","token":"class-value"}],
+ "code-block-header": [{"axis":"language","token":"class-value"}],
+ "code-block-title": [{"axis":"language","token":"class-value"}],
+ "codeblock": [{"axis":"language","token":"class-value"}],
+ "codeblock-header": [{"axis":"language","token":"class-value"}],
+ "codeblock-title": [{"axis":"language","token":"class-value"}],
+ "grid": [{"axis":"columns","token":"prefixed","prefix":"columns-"}],
+ "metadata-list": [{"axis":"columns","token":"prefixed","prefix":"columns-"}],
+ "outline-item": [{"axis":"level","token":"prefixed","prefix":"level-"}],
+};
diff --git a/packages/cli/assets/docs/styling.doc.mjs b/packages/cli/assets/docs/styling.doc.mjs
index 2eb1c1b7fb..1a3638ac12 100644
--- a/packages/cli/assets/docs/styling.doc.mjs
+++ b/packages/cli/assets/docs/styling.doc.mjs
@@ -268,26 +268,30 @@ const overrides = stylex.create({
],
},
{
- title: 'Deprecated: Bare Prop and State Classes',
+ title: 'Removed: Bare Prop and State Classes',
category: 'guide',
content: [
{
type: 'prose',
- text: 'Astryx still emits legacy bare prop/state classes such as `.primary`, `.sm`, `.level-2`, and `.checked` for compatibility with existing apps and built themes. Do not write new CSS against these bare classes. The stable base component classes (`.astryx-button`, `.astryx-card`, etc.) are not deprecated; only the unprefixed prop/state classes are the legacy surface.',
+ text: 'Astryx no longer emits bare prop/state classes such as `.primary`, `.sm`, `.level-2`, and `.checked`. Run `astryx upgrade --apply` to parse `.css` files and rewrite selectors qualified by a known Astryx target when the 0.5.4 target/value pair has one or more known meanings. Declarations, comments, JavaScript/TypeScript strings, and unqualified classes are never rewritten. Stable base target classes (`.astryx-button`, `.astryx-card`, etc.) remain unchanged.',
},
{
type: 'code',
lang: 'css',
- code: `/* Deprecated compatibility selector — avoid in new CSS */
-.my-app .astryx-button.primary {
- /* use .astryx-button[data-variant="primary"] instead */
+ code: `/* The upgrade preserves old consumer classes and adds the v0.6 prop match */
+.my-app .astryx-button:is(.primary, [data-variant="primary"]) {
+ /* primary buttons or a consumer-supplied .primary class */
}
-/* Deprecated compatibility selector — avoid in new CSS */
-.my-app .astryx-heading.level-2 {
- /* use .astryx-heading[data-level="2"] instead */
+/* Numeric values stay literal in data attributes */
+.my-app .astryx-heading:is(.level-2, [data-level="2"]) {
+ /* level 2 headings or a consumer-supplied .level-2 class */
}`,
},
+ {
+ type: 'prose',
+ text: 'Each known old value becomes a specificity-preserving `:is(...)` union containing the original class arm plus every v0.5.4 data-attribute arm. The class arm preserves consumer-supplied `className` matches; the attribute arms match v0.6 props and states. Narrow the union later only when class provenance or prop-axis intent is known. Custom/unknown qualified classes and unqualified classes stay unchanged. Search for unqualified old values such as `.primary` or `.sm` and migrate only confirmed Astryx uses manually. Migrate selectors embedded in JavaScript or TypeScript manually with the same rules.',
+ },
],
},
{
diff --git a/packages/cli/assets/docs/theme.doc.mjs b/packages/cli/assets/docs/theme.doc.mjs
index 62be7d16f6..c4bdc5357f 100644
--- a/packages/cli/assets/docs/theme.doc.mjs
+++ b/packages/cli/assets/docs/theme.doc.mjs
@@ -522,6 +522,10 @@ const brandTheme = defineTheme({
type: 'prose',
text: 'The `__built: true` flag tells Theme to skip runtime `<style>` injection; the CSS file handles it.',
},
+ {
+ type: 'prose',
+ text: 'After upgrading Astryx across a selector-contract change, rerun `astryx theme build <theme-file>` for every custom prebuilt theme. Deploy the regenerated `.css`, `.js`, `.d.ts`, and optional `.variants.d.ts` together. The runtime intentionally trusts `__built: true` and will not repair stale CSS from an older build.',
+ },
{
type: 'code',
lang: 'tsx',
diff --git a/packages/cli/authoring/doctypes/base/type.ts b/packages/cli/authoring/doctypes/base/type.ts
index edba89792c..ecbacef40a 100644
--- a/packages/cli/authoring/doctypes/base/type.ts
+++ b/packages/cli/authoring/doctypes/base/type.ts
@@ -431,17 +431,16 @@ export interface ComponentThemingTarget {
className: string;
/** Visual prop names reflected on this element.
* These are the props passed to `themeProps()` as the second argument.
- * Use these names to derive preferred data selectors: `variant` →
- * `[data-variant="secondary"]`, `level` → `[data-level="2"]`. Legacy bare
- * classes are still emitted for compatibility but should not be the primary
- * documentation surface. Omit if the component has no visual props (class
- * name only). */
+ * Use these names to derive selectors: `variant` →
+ * `[data-variant="secondary"]`, `level` → `[data-level="2"]`. Values are
+ * reflected only as data attributes; the stable target class identifies the
+ * component or part. Omit if the component has no visual props. */
visualProps?: string[];
- /** State names that appear on this element based on component state.
+ /** State names reflected on this element based on component state.
* Unlike visualProps (driven by props), these reflect runtime state
- * (checked, selected, today, on, expanded, etc.). Use these names to derive preferred data selectors such as
- * `[data-checked="checked"]`. Legacy state classes are still emitted for
- * compatibility. Omit if the element has no state-driven selectors. */
+ * (checked, selected, today, on, expanded, etc.). Use these names to derive
+ * selectors such as `[data-checked="checked"]`. Omit if the element has no
+ * state-driven selectors. */
states?: string[];
/** Set when this target has been RENAMED and this entry is the old name.
* The component still emits the class (via `themeProps`'s `legacyNames`),
diff --git a/packages/cli/clients/cli/commands/build-theme.registry.test.mjs b/packages/cli/clients/cli/commands/build-theme.registry.test.mjs
index e46ed8e54a..d1c9045890 100644
--- a/packages/cli/clients/cli/commands/build-theme.registry.test.mjs
+++ b/packages/cli/clients/cli/commands/build-theme.registry.test.mjs
@@ -143,7 +143,7 @@ describe('theme build emits a live TextInput selector (#4109)', () => {
expect(result.stderr).not.toContain('Unknown component');
expect(css).toContain('.astryx-side-nav-item');
expect(css).toContain('.astryx-chat-composer');
- expect(css).toContain('.astryx-chat-message-bubble.ghost');
+ expect(css).toContain('.astryx-chat-message-bubble[data-variant="ghost"]');
});
it('emits .astryx-text-input (the rendered class), not the dead .astryx-textinput', async () => {
diff --git a/packages/cli/clients/cli/commands/build-theme.variants.test.mjs b/packages/cli/clients/cli/commands/build-theme.variants.test.mjs
index 1be0495d38..6650c2eab1 100644
--- a/packages/cli/clients/cli/commands/build-theme.variants.test.mjs
+++ b/packages/cli/clients/cli/commands/build-theme.variants.test.mjs
@@ -143,12 +143,26 @@ describe('theme build custom-variant augmentations', () => {
path.join(tmpDir, 'variants-theme.css'),
'utf-8',
);
- const mainTypeIndex = css.indexOf('.astryx-heading.hero');
- const mainWeightIndex = css.indexOf('font-weight: 900;', mainTypeIndex);
- const mediaTypeIndex = css.lastIndexOf('.astryx-heading.hero');
- const mediaWeightIndex = css.indexOf('font-weight: 800;', mediaTypeIndex);
- expect(mainWeightIndex).toBeGreaterThan(mainTypeIndex);
- expect(mediaWeightIndex).toBeGreaterThan(mediaTypeIndex);
+ const mainTypeIndex = css.indexOf(
+ '.astryx-heading[data-type="hero"]',
+ );
+ const mainTypeWeightIndex = css.indexOf('font-weight: 300;', mainTypeIndex);
+ const mainWeightIndex = css.indexOf(
+ '.astryx-heading[data-weight="bold"]',
+ );
+ const mainWeightValueIndex = css.indexOf('font-weight: 900;', mainWeightIndex);
+ const mediaTypeIndex = css.lastIndexOf(
+ '.astryx-heading[data-type="hero"]',
+ );
+ const mediaTypeWeightIndex = css.indexOf('font-weight: 350;', mediaTypeIndex);
+ const mediaWeightIndex = css.lastIndexOf(
+ '.astryx-heading[data-weight="bold"]',
+ );
+ const mediaWeightValueIndex = css.indexOf('font-weight: 800;', mediaWeightIndex);
+ expect(mainTypeWeightIndex).toBeGreaterThan(mainTypeIndex);
+ expect(mainWeightValueIndex).toBeGreaterThan(mainWeightIndex);
+ expect(mediaTypeWeightIndex).toBeGreaterThan(mediaTypeIndex);
+ expect(mediaWeightValueIndex).toBeGreaterThan(mediaWeightIndex);
});
it('unions custom Heading types from onDark and onLight into the public type contract', async () => {
diff --git a/packages/cli/package.json b/packages/cli/package.json
index 9ef76d4275..182b892627 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -102,6 +102,8 @@
"commander": "^12.1.0",
"jiti": "^2.7.0",
"jscodeshift": "^17.3.0",
+ "postcss": "^8.5.23",
+ "postcss-selector-parser": "^7.1.5",
"zod": "^4.4.3"
},
"peerDependencies": {
diff --git a/packages/core/src/AspectRatio/AspectRatio.test.tsx b/packages/core/src/AspectRatio/AspectRatio.test.tsx
index 3a25d24e6b..fe3fcdce3c 100644
--- a/packages/core/src/AspectRatio/AspectRatio.test.tsx
+++ b/packages/core/src/AspectRatio/AspectRatio.test.tsx
@@ -104,7 +104,7 @@ describe('AspectRatio', () => {
);
const element = screen.getByTestId('aspect-ratio');
expect(ratioVar(element)).toBe(ratioValue(1));
- expect(element.className).toContain('ellipse');
+ expect(element).toHaveAttribute('data-shape', 'ellipse');
});
it('ellipse respects a non-square ratio (oval)', () => {
@@ -116,7 +116,7 @@ describe('AspectRatio', () => {
const element = screen.getByTestId('aspect-ratio');
// Ratio is preserved — the ellipse does not force 1:1.
expect(ratioVar(element)).toBe(ratioValue(16 / 9));
- expect(element.className).toContain('ellipse');
+ expect(element).toHaveAttribute('data-shape', 'ellipse');
});
it('defaults to the rectangle shape', () => {
@@ -127,7 +127,7 @@ describe('AspectRatio', () => {
);
const element = screen.getByTestId('aspect-ratio');
expect(ratioVar(element)).toBe(ratioValue(1));
- expect(element.className).toContain('rectangle');
+ expect(element).toHaveAttribute('data-shape', 'rectangle');
// No ellipse border-radius when shape is the default rectangle
expect(element.style.borderRadius).toBe('');
});
diff --git a/packages/core/src/AvatarGroup/AvatarGroup.test.tsx b/packages/core/src/AvatarGroup/AvatarGroup.test.tsx
index 282eb580e5..93d5ce6f2c 100644
--- a/packages/core/src/AvatarGroup/AvatarGroup.test.tsx
+++ b/packages/core/src/AvatarGroup/AvatarGroup.test.tsx
@@ -69,7 +69,7 @@ describe('AvatarGroup', () => {
expect(screen.getByTestId('avatar-group')).toBeInTheDocument();
});
- it('applies size class to the group', () => {
+ it('reflects size on the group', () => {
render(
<AvatarGroup size="lg">
<Avatar name="Alice" />
@@ -78,7 +78,7 @@ describe('AvatarGroup', () => {
const group = screen.getByRole('group');
expect(group.className).toContain('astryx-avatar-group');
- expect(group.className).toContain('lg');
+ expect(group).toHaveAttribute('data-size', 'lg');
});
it('renders empty group when no children', () => {
@@ -215,8 +215,6 @@ describe('AvatarGroup — roving focus + keyboard hint', () => {
});
describe('AvatarGroup — size cascade', () => {
- const sizeClasses = (el: HTMLElement) => el.className.split(/\s+/);
-
it("the group's size overrides a child's own size prop", () => {
render(
<AvatarGroup size="lg">
@@ -224,9 +222,7 @@ describe('AvatarGroup — size cascade', () => {
</AvatarGroup>,
);
- const classes = sizeClasses(screen.getByTestId('alice'));
- expect(classes).toContain('lg');
- expect(classes).not.toContain('xsm');
+ expect(screen.getByTestId('alice')).toHaveAttribute('data-size', 'lg');
});
it("the group's default size also overrides a child's own size prop", () => {
@@ -239,14 +235,12 @@ describe('AvatarGroup — size cascade', () => {
</AvatarGroup>,
);
- const classes = sizeClasses(screen.getByTestId('alice'));
- expect(classes).toContain('md');
- expect(classes).not.toContain('xl');
+ expect(screen.getByTestId('alice')).toHaveAttribute('data-size', 'md');
});
it("outside a group the avatar's own size applies", () => {
render(<Avatar name="Alice" size="xl" data-testid="alice" />);
- expect(sizeClasses(screen.getByTestId('alice'))).toContain('xl');
+ expect(screen.getByTestId('alice')).toHaveAttribute('data-size', 'xl');
});
});
diff --git a/packages/core/src/AvatarGroup/AvatarGroupOverflow.test.tsx b/packages/core/src/AvatarGroup/AvatarGroupOverflow.test.tsx
index 206779bccb..9a80e24ea6 100644
--- a/packages/core/src/AvatarGroup/AvatarGroupOverflow.test.tsx
+++ b/packages/core/src/AvatarGroup/AvatarGroupOverflow.test.tsx
@@ -21,7 +21,7 @@ describe('AvatarGroupOverflow', () => {
expect(overflow).toHaveTextContent('+5');
});
- it('applies the group size class to the overflow chip', () => {
+ it('reflects the group size on the overflow chip', () => {
render(
<AvatarGroup size="lg">
<Avatar name="Alice" />
@@ -31,7 +31,6 @@ describe('AvatarGroupOverflow', () => {
const overflow = screen.getByLabelText('5 more');
expect(overflow.className).toContain('astryx-avatar-group-overflow');
- expect(overflow.className).toContain('lg');
expect(overflow).toHaveAttribute('data-size', 'lg');
});
diff --git a/packages/core/src/Badge/Badge.test.tsx b/packages/core/src/Badge/Badge.test.tsx
index 8e0b549000..f851a1bbd3 100644
--- a/packages/core/src/Badge/Badge.test.tsx
+++ b/packages/core/src/Badge/Badge.test.tsx
@@ -50,7 +50,7 @@ describe('Badge', () => {
const {container} = render(<Badge variant="purple" label="Tag" />);
const root = container.firstElementChild!;
expect(root.className).toContain('astryx-badge');
- expect(root.className).toContain('purple');
+ expect(root).toHaveAttribute('data-variant', 'purple');
});
it('renders with icon', () => {
@@ -107,6 +107,6 @@ describe('Badge', () => {
const {container} = render(<Badge variant="success" label="Active" />);
const root = container.firstElementChild!;
expect(root.className).toContain('astryx-badge');
- expect(root.className).toContain('success');
+ expect(root).toHaveAttribute('data-variant', 'success');
});
});
diff --git a/packages/core/src/Banner/Banner.test.tsx b/packages/core/src/Banner/Banner.test.tsx
index 98d19b2592..0f0aa4db00 100644
--- a/packages/core/src/Banner/Banner.test.tsx
+++ b/packages/core/src/Banner/Banner.test.tsx
@@ -430,7 +430,7 @@ describe('Banner', () => {
it("carries the 'banner-icon' theme target on the default status icon glyph", () => {
// Theme overrides for 'banner-icon' + 'status:X' compile to
- // '.astryx-banner-icon.<status>' (parseStyleKey). The target must sit on
+ // '.astryx-banner-icon[data-status="<status>"]' (parseStyleKey). The target must sit on
// the <Icon> span itself so those same-element rules in
// @layer astryx-theme beat the Icon's own color variant.
const statuses = ['info', 'warning', 'error', 'success'] as const;
@@ -439,7 +439,7 @@ describe('Banner', () => {
<Banner status={status} title={`${status} banner`} />,
);
const glyph = container.querySelector(
- `.astryx-icon.astryx-banner-icon.${status}`,
+ `.astryx-icon.astryx-banner-icon[data-status="${status}"]`,
);
expect(glyph).not.toBeNull();
expect(glyph).toHaveAttribute('data-status', status);
@@ -451,12 +451,14 @@ describe('Banner', () => {
});
it('keeps the color variant on the theme-target element (regression pin for #4166)', () => {
- // Pre-fix, '.astryx-banner-icon.info' matched the layout wrapper while
+ // Pre-fix, '.astryx-banner-icon[data-status="info"]' matched the layout wrapper while
// the color variant (data-color="accent") sat on an inner span that a
// theme override could never reach. Target and paint now share one
// element.
const {container} = render(<Banner status="info" title="Info" />);
- const target = container.querySelector('.astryx-banner-icon.info');
+ const target = container.querySelector(
+ '.astryx-banner-icon[data-status="info"]',
+ );
expect(target).toHaveAttribute('data-color', 'accent');
});
@@ -528,11 +530,8 @@ describe('Banner', () => {
/>,
);
const frame = container.firstElementChild;
- expect(frame).toHaveClass(
- 'astryx-banner-frame',
- containerType,
- elevation,
- );
+ expect(frame).toHaveClass('astryx-banner-frame');
+ expect(frame).not.toHaveClass(containerType, elevation);
expect(frame).toHaveAttribute('data-container', containerType);
expect(frame).toHaveAttribute('data-elevation', elevation);
expect(frame?.firstElementChild).toHaveClass('astryx-banner');
@@ -558,7 +557,9 @@ describe('Banner', () => {
});
const {component: css} = generateThemeCSS(theme);
- expect(css).toContain('.astryx-banner-frame.card.high');
+ expect(css).toContain(
+ '.astryx-banner-frame[data-container="card"][data-elevation="high"]',
+ );
expect(css).toContain('box-shadow: var(--shadow-high)');
expect(css).toContain('border-radius: var(--radius-element)');
expect(css).not.toContain(':has(');
diff --git a/packages/core/src/Button/Button.test.tsx b/packages/core/src/Button/Button.test.tsx
index e5bc78267b..a334c8a57e 100644
--- a/packages/core/src/Button/Button.test.tsx
+++ b/packages/core/src/Button/Button.test.tsx
@@ -271,8 +271,6 @@ describe('Button', () => {
render(<Button label="Test" variant="secondary" size="sm" />);
const button = screen.getByRole('button');
expect(button.className).toContain('astryx-button');
- expect(button.className).toContain('secondary');
- expect(button.className).toContain('sm');
expect(button).toHaveAttribute('data-variant', 'secondary');
expect(button).toHaveAttribute('data-size', 'sm');
});
diff --git a/packages/core/src/Calendar/Calendar.test.tsx b/packages/core/src/Calendar/Calendar.test.tsx
index ce2965270d..ddb40e035e 100644
--- a/packages/core/src/Calendar/Calendar.test.tsx
+++ b/packages/core/src/Calendar/Calendar.test.tsx
@@ -1434,8 +1434,10 @@ describe('Calendar', () => {
},
});
const css = generateThemeTestCSS(theme);
- expect(css).toContain('.astryx-calendar-day.today-only');
- expect(css).toContain('.astryx-calendar-day.today-in-range');
+ expect(css).toContain('.astryx-calendar-day[data-marker="today-only"]');
+ expect(css).toContain(
+ '.astryx-calendar-day[data-marker="today-in-range"]',
+ );
expect(css).toContain('box-shadow: inset 0 0 0 2px var(--color-accent)');
expect(css).toContain(
'box-shadow: inset 0 0 0 2px var(--color-text-primary)',
@@ -1481,7 +1483,7 @@ describe('Calendar', () => {
// classes, so default appearance is preserved.
const prev = getButton('Previous month');
expect(prev).toHaveClass('astryx-button');
- expect(prev).toHaveClass('ghost');
+ expect(prev).toHaveAttribute('data-variant', 'ghost');
expect(prev.tagName).toBe('BUTTON');
});
@@ -1517,7 +1519,7 @@ describe('Calendar', () => {
const css = generateThemeTestCSS(theme);
expect(css).toContain('.astryx-calendar-nav {');
expect(css).toContain('color: var(--color-accent)');
- expect(css).toContain('.astryx-calendar-nav.next');
+ expect(css).toContain('.astryx-calendar-nav[data-nav="next"]');
expect(css).toContain('background-color: var(--color-accent-muted)');
});
});
diff --git a/packages/core/src/Card/Card.test.tsx b/packages/core/src/Card/Card.test.tsx
index 30e9476c53..8338725cfc 100644
--- a/packages/core/src/Card/Card.test.tsx
+++ b/packages/core/src/Card/Card.test.tsx
@@ -117,7 +117,7 @@ describe('Card', () => {
const root = container.firstElementChild!;
expect(root).toHaveAttribute('data-variant', 'brand');
expect(root.className).toContain('astryx-card');
- expect(root.className).toContain('brand');
+ expect(root).toHaveAttribute('data-variant', 'brand');
});
it('falls through to base styles instead of another variant', () => {
diff --git a/packages/core/src/Chat/ChatLayout.test.tsx b/packages/core/src/Chat/ChatLayout.test.tsx
index abd5a75a85..6202bf7a3e 100644
--- a/packages/core/src/Chat/ChatLayout.test.tsx
+++ b/packages/core/src/Chat/ChatLayout.test.tsx
@@ -59,7 +59,7 @@ describe('ChatLayout', () => {
</ChatLayout>,
);
const root = screen.getByTestId('layout');
- expect(root.className).toContain('compact');
+ expect(root).toHaveAttribute('data-density', 'compact');
rerender(
<ChatLayout
@@ -69,7 +69,7 @@ describe('ChatLayout', () => {
<div>msg</div>
</ChatLayout>,
);
- expect(root.className).toContain('spacious');
+ expect(root).toHaveAttribute('data-density', 'spacious');
});
it('defaults density to balanced', () => {
@@ -79,7 +79,7 @@ describe('ChatLayout', () => {
</ChatLayout>,
);
const root = screen.getByTestId('layout');
- expect(root.className).toContain('balanced');
+ expect(root).toHaveAttribute('data-density', 'balanced');
});
it('renders custom scrollButton slot', () => {
diff --git a/packages/core/src/Chat/ChatMessage.test.tsx b/packages/core/src/Chat/ChatMessage.test.tsx
index d54518dfac..87348dbd6e 100644
--- a/packages/core/src/Chat/ChatMessage.test.tsx
+++ b/packages/core/src/Chat/ChatMessage.test.tsx
@@ -46,9 +46,7 @@ describe('ChatMessage', () => {
it('hides avatar for system', () => {
render(
- <ChatMessage
- sender="system"
- avatar={<div data-testid="avatar">S</div>}>
+ <ChatMessage sender="system" avatar={<div data-testid="avatar">S</div>}>
<span>Notice</span>
</ChatMessage>,
);
@@ -62,7 +60,7 @@ describe('ChatMessage', () => {
</ChatMessage>,
);
const el = screen.getByTestId('msg');
- expect(el.className).toContain('user');
+ expect(el).toHaveAttribute('data-sender', 'user');
});
it('sets accessible aria-labelledby with name', () => {
@@ -74,7 +72,9 @@ describe('ChatMessage', () => {
const el = screen.getByTestId('msg');
const labelId = el.getAttribute('aria-labelledby');
expect(labelId).toBeTruthy();
- expect(el.querySelector(`#${CSS.escape(labelId!)}`)?.textContent).toBe('Navi');
+ expect(el.querySelector(`#${CSS.escape(labelId!)}`)?.textContent).toBe(
+ 'Navi',
+ );
});
it('sets accessible aria-label without name', () => {
diff --git a/packages/core/src/Chat/ChatMessageBubble.test.tsx b/packages/core/src/Chat/ChatMessageBubble.test.tsx
index 741b046966..8104b40331 100644
--- a/packages/core/src/Chat/ChatMessageBubble.test.tsx
+++ b/packages/core/src/Chat/ChatMessageBubble.test.tsx
@@ -34,7 +34,7 @@ describe('ChatMessageBubble', () => {
</ChatMessage>,
);
const el = screen.getByTestId('bubble');
- expect(el.className).toContain('user');
+ expect(el).toHaveAttribute('data-sender', 'user');
});
it('defaults to assistant when no context', () => {
@@ -42,7 +42,7 @@ describe('ChatMessageBubble', () => {
<ChatMessageBubble data-testid="bubble">Standalone</ChatMessageBubble>,
);
const el = screen.getByTestId('bubble');
- expect(el.className).toContain('assistant');
+ expect(el).toHaveAttribute('data-sender', 'assistant');
});
it('applies inherited compact density class', () => {
@@ -54,7 +54,7 @@ describe('ChatMessageBubble', () => {
</ChatMessageList>,
);
const el = screen.getByTestId('bubble');
- expect(el.className).toContain('compact');
+ expect(el).toHaveAttribute('data-density', 'compact');
});
it('applies data-testid', () => {
diff --git a/packages/core/src/Chat/ChatMessageList.test.tsx b/packages/core/src/Chat/ChatMessageList.test.tsx
index 1322757d2e..213f075fd7 100644
--- a/packages/core/src/Chat/ChatMessageList.test.tsx
+++ b/packages/core/src/Chat/ChatMessageList.test.tsx
@@ -62,7 +62,7 @@ describe('ChatMessageList', () => {
</ChatMessageList>,
);
const el = screen.getByTestId('list');
- expect(el.className).toContain('compact');
+ expect(el).toHaveAttribute('data-density', 'compact');
});
it('accepts gap independently from density', () => {
@@ -72,7 +72,7 @@ describe('ChatMessageList', () => {
</ChatMessageList>,
);
const el = screen.getByTestId('list');
- expect(el.className).toContain('compact');
+ expect(el).toHaveAttribute('data-density', 'compact');
});
it('applies data-testid', () => {
diff --git a/packages/core/src/Chat/ChatSystemMessage.test.tsx b/packages/core/src/Chat/ChatSystemMessage.test.tsx
index aaef01d72f..a9665e2a6a 100644
--- a/packages/core/src/Chat/ChatSystemMessage.test.tsx
+++ b/packages/core/src/Chat/ChatSystemMessage.test.tsx
@@ -49,7 +49,7 @@ describe('ChatSystemMessage', () => {
</ChatSystemMessage>,
);
const el = screen.getByTestId('sys');
- expect(el.className).toContain('divider');
+ expect(el).toHaveAttribute('data-variant', 'divider');
});
it('applies data-testid', () => {
diff --git a/packages/core/src/CheckboxList/CheckboxList.test.tsx b/packages/core/src/CheckboxList/CheckboxList.test.tsx
index 4eedab57ae..16433316bd 100644
--- a/packages/core/src/CheckboxList/CheckboxList.test.tsx
+++ b/packages/core/src/CheckboxList/CheckboxList.test.tsx
@@ -420,7 +420,10 @@ describe('CheckboxList', () => {
<CheckboxListItem label="Option A" value="a" />
</CheckboxList>,
);
- expect(screen.getByRole('listitem').className).toContain('spacious');
+ expect(screen.getByRole('listitem')).toHaveAttribute(
+ 'data-density',
+ 'spacious',
+ );
});
it('supports data-testid on CheckboxListItem', () => {
diff --git a/packages/core/src/Code/Code.test.tsx b/packages/core/src/Code/Code.test.tsx
index 3e751f7e54..b0d714d9e7 100644
--- a/packages/core/src/Code/Code.test.tsx
+++ b/packages/core/src/Code/Code.test.tsx
@@ -28,17 +28,20 @@ describe('Code', () => {
it('defaults color to primary', () => {
render(<Code>code</Code>);
- expect(screen.getByText('code')).toHaveClass('astryx-code', 'primary');
+ expect(screen.getByText('code')).toHaveClass('astryx-code');
+ expect(screen.getByText('code')).toHaveAttribute('data-color', 'primary');
});
it('applies the secondary color', () => {
render(<Code color="secondary">code</Code>);
- expect(screen.getByText('code')).toHaveClass('astryx-code', 'secondary');
+ expect(screen.getByText('code')).toHaveClass('astryx-code');
+ expect(screen.getByText('code')).toHaveAttribute('data-color', 'secondary');
});
it('applies the inherit color', () => {
render(<Code color="inherit">code</Code>);
- expect(screen.getByText('code')).toHaveClass('astryx-code', 'inherit');
+ expect(screen.getByText('code')).toHaveClass('astryx-code');
+ expect(screen.getByText('code')).toHaveAttribute('data-color', 'inherit');
});
it('adds a size class when size="inherit" (font-size + line-height inherit)', () => {
diff --git a/packages/core/src/DateInput/DateInput.test.tsx b/packages/core/src/DateInput/DateInput.test.tsx
index 76b9508695..fd50a8913a 100644
--- a/packages/core/src/DateInput/DateInput.test.tsx
+++ b/packages/core/src/DateInput/DateInput.test.tsx
@@ -1299,7 +1299,9 @@ describe('DateInput calendar-toggle icon theme target', () => {
expect(css).toContain('.astryx-date-input-toggle-icon {');
expect(css).toContain('width: 14px');
expect(css).toContain('height: 14px');
- expect(css).toContain('.astryx-date-input-toggle-icon.expanded');
+ expect(css).toContain(
+ '.astryx-date-input-toggle-icon[data-state="expanded"]',
+ );
expect(css).toContain('color: var(--color-icon-primary)');
});
});
@@ -1311,7 +1313,6 @@ describe('DateInput disabled theme state', () => {
);
const root = container.querySelector('.astryx-date-input');
expect(root).toHaveAttribute('data-disabled', 'disabled');
- expect(root).toHaveClass('disabled');
});
it('omits data-disabled when enabled, like status does', () => {
diff --git a/packages/core/src/DateRangeInput/DateRangeInput.test.tsx b/packages/core/src/DateRangeInput/DateRangeInput.test.tsx
index 96407726f9..98612ef137 100644
--- a/packages/core/src/DateRangeInput/DateRangeInput.test.tsx
+++ b/packages/core/src/DateRangeInput/DateRangeInput.test.tsx
@@ -725,7 +725,6 @@ describe('DateRangeInput disabled theme state', () => {
);
const root = container.querySelector('.astryx-date-range-input');
expect(root).toHaveAttribute('data-disabled', 'disabled');
- expect(root).toHaveClass('disabled');
});
it('omits data-disabled when enabled, like status does', () => {
diff --git a/packages/core/src/DateTimeInput/DateTimeInput.test.tsx b/packages/core/src/DateTimeInput/DateTimeInput.test.tsx
index 732217ba1a..1e6e13efc2 100644
--- a/packages/core/src/DateTimeInput/DateTimeInput.test.tsx
+++ b/packages/core/src/DateTimeInput/DateTimeInput.test.tsx
@@ -2204,9 +2204,7 @@ describe('DateTimeInput', () => {
.closest('.astryx-date-time-input-time-segment');
expect(date).toHaveAttribute('data-size', 'lg');
- expect(date).toHaveClass('lg');
expect(time).toHaveAttribute('data-size', 'lg');
- expect(time).toHaveClass('lg');
});
it('reflects status on both segments, mirroring the root', () => {
@@ -2255,7 +2253,7 @@ describe('DateTimeInput', () => {
components: {
'date-time-input-date-segment': {
base: {blockSize: 'var(--size-element-lg)'},
- lg: {paddingInline: 'var(--spacing-4)'},
+ 'size:lg': {paddingInline: 'var(--spacing-4)'},
},
'date-time-input-time-segment': {
base: {blockSize: 'var(--size-element-lg)'},
@@ -2265,7 +2263,9 @@ describe('DateTimeInput', () => {
const css = generateThemeTestCSS(theme);
expect(css).toContain('.astryx-date-time-input-date-segment {');
- expect(css).toContain('.astryx-date-time-input-date-segment.lg');
+ expect(css).toContain(
+ '.astryx-date-time-input-date-segment[data-size="lg"]',
+ );
expect(css).toContain('.astryx-date-time-input-time-segment {');
expect(css).toContain('block-size: var(--size-element-lg)');
expect(css).toContain('padding-inline: var(--spacing-4)');
@@ -2327,7 +2327,6 @@ describe('DateTimeInput', () => {
const themeTargetClasses = new Set([
'astryx-date-time-input-toggle-icon',
'astryx-date-time-input-clock-icon',
- 'collapsed',
'expanded',
]);
const styleClasses = (el: HTMLElement) =>
@@ -2359,7 +2358,9 @@ describe('DateTimeInput', () => {
const css = generateThemeTestCSS(theme);
expect(css).toContain('.astryx-date-time-input-toggle-icon {');
- expect(css).toContain('.astryx-date-time-input-toggle-icon.expanded');
+ expect(css).toContain(
+ '.astryx-date-time-input-toggle-icon[data-state="expanded"]',
+ );
expect(css).toContain('.astryx-date-time-input-clock-icon {');
expect(css).toContain('width: 14px');
expect(css).toContain('color: var(--color-icon-primary)');
@@ -2374,7 +2375,6 @@ describe('DateTimeInput disabled theme state', () => {
);
const root = container.querySelector('.astryx-date-time-input');
expect(root).toHaveAttribute('data-disabled', 'disabled');
- expect(root).toHaveClass('disabled');
});
it('omits data-disabled when enabled, like status does', () => {
diff --git a/packages/core/src/Divider/Divider.test.tsx b/packages/core/src/Divider/Divider.test.tsx
index d9d66c45e3..7c47adeb1a 100644
--- a/packages/core/src/Divider/Divider.test.tsx
+++ b/packages/core/src/Divider/Divider.test.tsx
@@ -134,7 +134,7 @@ describe('Divider', () => {
);
const root = screen.getByTestId('divider');
expect(root.className).toContain('astryx-divider');
- expect(root.className).toContain('strong');
- expect(root.className).toContain('vertical');
+ expect(root).toHaveAttribute('data-variant', 'strong');
+ expect(root).toHaveAttribute('data-orientation', 'vertical');
});
});
diff --git a/packages/core/src/FieldStatus/FieldStatus.test.tsx b/packages/core/src/FieldStatus/FieldStatus.test.tsx
index b7f3fcd085..a7994fa908 100644
--- a/packages/core/src/FieldStatus/FieldStatus.test.tsx
+++ b/packages/core/src/FieldStatus/FieldStatus.test.tsx
@@ -116,20 +116,18 @@ describe('FieldStatus', () => {
});
});
- describe('theme class + data attribute reflection', () => {
+ describe('theme target and data-attribute reflection', () => {
it('renders the stable astryx-field-status class', () => {
render(<FieldStatus type="error" message="msg" data-testid="fs" />);
expect(screen.getByTestId('fs')).toHaveClass('astryx-field-status');
});
- it('reflects the type as a class token and data-type attribute', () => {
+ it('reflects the type as a data-type attribute', () => {
render(<FieldStatus type="warning" message="msg" data-testid="fs" />);
- const el = screen.getByTestId('fs');
- expect(el).toHaveClass('warning');
- expect(el).toHaveAttribute('data-type', 'warning');
+ expect(screen.getByTestId('fs')).toHaveAttribute('data-type', 'warning');
});
- it('reflects the variant as a class token and data-variant attribute', () => {
+ it('reflects the variant as a data-variant attribute', () => {
render(
<FieldStatus
type="error"
@@ -139,15 +137,15 @@ describe('FieldStatus', () => {
/>,
);
const el = screen.getByTestId('fs');
- expect(el).toHaveClass('detached');
expect(el).toHaveAttribute('data-variant', 'detached');
});
it('defaults data-variant to "attached"', () => {
render(<FieldStatus type="error" message="msg" data-testid="fs" />);
- const el = screen.getByTestId('fs');
- expect(el).toHaveAttribute('data-variant', 'attached');
- expect(el).toHaveClass('attached');
+ expect(screen.getByTestId('fs')).toHaveAttribute(
+ 'data-variant',
+ 'attached',
+ );
});
it('extends the attached background by the field-provided overlap', () => {
diff --git a/packages/core/src/FormLayout/__snapshots__/FormLayout.test.tsx.snap b/packages/core/src/FormLayout/__snapshots__/FormLayout.test.tsx.snap
index 4e55cedf22..49649ffba3 100644
--- a/packages/core/src/FormLayout/__snapshots__/FormLayout.test.tsx.snap
+++ b/packages/core/src/FormLayout/__snapshots__/FormLayout.test.tsx.snap
@@ -2,7 +2,7 @@
exports[`FormLayout > matches snapshot for horizontal direction 1`] = `
<div
- class="astryx-form-layout horizontal FormLayout__styles.base xdt5ytf x18g69wz FormLayout__styles.horizontal xrvj5dj x1mt1orb xu6a5m6"
+ class="astryx-form-layout FormLayout__styles.base xdt5ytf x18g69wz FormLayout__styles.horizontal xrvj5dj x1mt1orb xu6a5m6"
data-direction="horizontal"
data-testid="layout"
>
@@ -17,7 +17,7 @@ exports[`FormLayout > matches snapshot for horizontal direction 1`] = `
exports[`FormLayout > matches snapshot for horizontal-labels direction 1`] = `
<div
- class="astryx-form-layout horizontal-labels FormLayout__styles.base xdt5ytf FormLayout__styles.horizontalLabels xrvj5dj x1pmbctz xlaq8a2 x7a106z xedohl4 x1rpgqan x1a1jff"
+ class="astryx-form-layout FormLayout__styles.base xdt5ytf FormLayout__styles.horizontalLabels xrvj5dj x1pmbctz xlaq8a2 x7a106z xedohl4 x1rpgqan x1a1jff"
data-direction="horizontal-labels"
data-testid="layout"
>
@@ -32,7 +32,7 @@ exports[`FormLayout > matches snapshot for horizontal-labels direction 1`] = `
exports[`FormLayout > matches snapshot for vertical direction 1`] = `
<div
- class="astryx-form-layout vertical FormLayout__styles.base x78zum5 xdt5ytf x18g69wz"
+ class="astryx-form-layout FormLayout__styles.base x78zum5 xdt5ytf x18g69wz"
data-direction="vertical"
data-testid="layout"
>
diff --git a/packages/core/src/Heading/Heading.test.tsx b/packages/core/src/Heading/Heading.test.tsx
index 5d23f7c11a..78b4aa8a68 100644
--- a/packages/core/src/Heading/Heading.test.tsx
+++ b/packages/core/src/Heading/Heading.test.tsx
@@ -206,14 +206,14 @@ describe('Heading', () => {
expect(element.tagName).toBe('H2');
});
- it('includes display type in class names', () => {
+ it('reflects a display type as a data attribute', () => {
render(
<Heading level={1} type="display-1">
Display Heading
</Heading>,
);
const element = screen.getByText('Display Heading');
- expect(element.className).toContain('display-1');
+ expect(element).toHaveAttribute('data-type', 'display-1');
});
it('reflects a theme-augmented visual type and keeps the level baseline', () => {
@@ -232,7 +232,6 @@ describe('Heading', () => {
const element = screen.getByText('Custom visual role');
expect(element).toHaveAttribute('data-type', 'hero');
- expect(element.className).toContain('hero');
for (const className of baselineClasses) {
expect(element.className).toContain(className);
}
@@ -247,7 +246,6 @@ describe('Heading', () => {
const element = screen.getByText('Bold custom visual role');
expect(element).toHaveAttribute('data-weight', 'bold');
- expect(element.className).toContain('bold');
expect(element.tagName).toBe('H2');
});
});
@@ -260,16 +258,14 @@ describe('Heading', () => {
);
const element = screen.getByText('Themed Heading');
expect(element.className).toContain('astryx-heading');
- expect(element.className).toContain('level-2');
- expect(element.className).toContain('secondary');
expect(element).toHaveAttribute('data-level', '2');
expect(element).toHaveAttribute('data-color', 'secondary');
});
- it('does not include variant in class names', () => {
+ it('does not reflect an omitted visual type', () => {
render(<Heading level={1}>No Variant</Heading>);
const element = screen.getByText('No Variant');
- expect(element.className).not.toContain('default');
- expect(element.className).not.toContain('editorial');
+ expect(element).not.toHaveAttribute('data-type', 'default');
+ expect(element).not.toHaveAttribute('data-type', 'editorial');
});
});
diff --git a/packages/core/src/Item/Item.test.tsx b/packages/core/src/Item/Item.test.tsx
index 248826d0d8..19073919b3 100644
--- a/packages/core/src/Item/Item.test.tsx
+++ b/packages/core/src/Item/Item.test.tsx
@@ -442,7 +442,10 @@ describe('Item', () => {
it('renders with balanced density by default', () => {
render(<Item label="Item" data-testid="item" />);
expect(screen.getByTestId('item')).toBeInTheDocument();
- expect(screen.getByTestId('item').className).toContain('balanced');
+ expect(screen.getByTestId('item')).toHaveAttribute(
+ 'data-density',
+ 'balanced',
+ );
});
it('renders with compact density', () => {
@@ -453,7 +456,10 @@ describe('Item', () => {
it('renders with spacious density', () => {
render(<Item label="Item" density="spacious" data-testid="item" />);
expect(screen.getByTestId('item')).toBeInTheDocument();
- expect(screen.getByTestId('item').className).toContain('spacious');
+ expect(screen.getByTestId('item')).toHaveAttribute(
+ 'data-density',
+ 'spacious',
+ );
});
// ===========================================================================
diff --git a/packages/core/src/Link/Link.test.tsx b/packages/core/src/Link/Link.test.tsx
index fafaf5c561..5cefec2574 100644
--- a/packages/core/src/Link/Link.test.tsx
+++ b/packages/core/src/Link/Link.test.tsx
@@ -122,7 +122,8 @@ describe('Link', () => {
it('defaults the inner text type to body', () => {
render(<Link href="/test">Body link</Link>);
- expect(screen.getByText('Body link')).toHaveClass('astryx-text', 'body');
+ expect(screen.getByText('Body link')).toHaveClass('astryx-text');
+ expect(screen.getByText('Body link')).toHaveAttribute('data-type', 'body');
});
it('forwards type="inherit" so the link adopts the surrounding text type', () => {
@@ -134,8 +135,9 @@ describe('Link', () => {
// The inner Text renders with the `inherit` type, so font-size/line-height
// inherit from the surrounding text rather than imposing the body type.
const text = screen.getByText('Inline link');
- expect(text).toHaveClass('astryx-text', 'inherit');
- expect(text).not.toHaveClass('body');
+ expect(text).toHaveClass('astryx-text');
+ expect(text).toHaveAttribute('data-type', 'inherit');
+ expect(text).not.toHaveAttribute('data-type', 'body');
});
it('applies hasUnderline style when true', () => {
@@ -412,6 +414,6 @@ describe('Link', () => {
);
const link = screen.getByRole('link', {name: 'Themed Link'});
expect(link.className).toContain('astryx-link');
- expect(link.className).toContain('secondary');
+ expect(link).toHaveAttribute('data-color', 'secondary');
});
});
diff --git a/packages/core/src/List/List.test.tsx b/packages/core/src/List/List.test.tsx
index a1a124aa7d..dc501eb4cc 100644
--- a/packages/core/src/List/List.test.tsx
+++ b/packages/core/src/List/List.test.tsx
@@ -229,7 +229,7 @@ describe('List', () => {
);
const item = container.querySelector('li');
expect(item).toBeInTheDocument();
- expect(item?.className).toContain('compact');
+ expect(item).toHaveAttribute('data-density', 'compact');
});
it('renders with balanced density (default)', () => {
@@ -240,8 +240,8 @@ describe('List', () => {
);
const item = container.querySelector('li');
expect(item).toBeInTheDocument();
- expect(item?.className).toContain('balanced');
- expect(item?.className).not.toContain('spacious');
+ expect(item).toHaveAttribute('data-density', 'balanced');
+ expect(item).not.toHaveAttribute('data-density', 'spacious');
});
it('renders with spacious density', () => {
@@ -252,7 +252,7 @@ describe('List', () => {
);
const item = container.querySelector('li');
expect(item).toBeInTheDocument();
- expect(item?.className).toContain('spacious');
+ expect(item).toHaveAttribute('data-density', 'spacious');
});
// ===========================================================================
diff --git a/packages/core/src/Markdown/Markdown.test.tsx b/packages/core/src/Markdown/Markdown.test.tsx
index 66587f76ab..21a0a8438d 100644
--- a/packages/core/src/Markdown/Markdown.test.tsx
+++ b/packages/core/src/Markdown/Markdown.test.tsx
@@ -570,7 +570,10 @@ describe('Markdown', () => {
const {container} = render(
<Markdown density="compact">{'Hello'}</Markdown>,
);
- expect(container.firstElementChild!.className).toContain('compact');
+ expect(container.firstElementChild).toHaveAttribute(
+ 'data-density',
+ 'compact',
+ );
});
it('supports data-testid', () => {
diff --git a/packages/core/src/MultiSelector/MultiSelector.test.tsx b/packages/core/src/MultiSelector/MultiSelector.test.tsx
index 15fc130ced..f232d8c4db 100644
--- a/packages/core/src/MultiSelector/MultiSelector.test.tsx
+++ b/packages/core/src/MultiSelector/MultiSelector.test.tsx
@@ -2599,7 +2599,9 @@ describe('MultiSelector indicator (chevron) icon theme target', () => {
expect(css).toContain('.astryx-multi-selector-indicator-icon {');
expect(css).toContain('width: 14px');
expect(css).toContain('height: 14px');
- expect(css).toContain('.astryx-multi-selector-indicator-icon.expanded');
+ expect(css).toContain(
+ '.astryx-multi-selector-indicator-icon[data-state="expanded"]',
+ );
expect(css).toContain('color: var(--color-icon-primary)');
});
});
@@ -2928,7 +2930,7 @@ describe('MultiSelector disabled state theme target', () => {
);
const root = getSelectorRoot(container);
expect(root).not.toHaveAttribute('data-disabled');
- expect(root).not.toHaveClass('disabled');
+ expect(root).not.toHaveAttribute('data-disabled');
});
it('exposes the disabled state so a theme can key on it', () => {
@@ -2941,7 +2943,7 @@ describe('MultiSelector disabled state theme target', () => {
},
});
const css = generateThemeTestCSS(theme);
- expect(css).toContain('.astryx-multi-selector.disabled');
+ expect(css).toContain('.astryx-multi-selector[data-disabled="disabled"]');
expect(css).toContain('opacity: 0.4');
});
});
@@ -2965,7 +2967,7 @@ describe('MultiSelector dropdown option theme target', () => {
expect(options).toHaveLength(3);
for (const option of options) {
expect(option).toHaveClass('astryx-multi-selector-option');
- expect(option).toHaveClass('lg');
+ expect(option).toHaveAttribute('data-size', 'lg');
expect(option).toHaveAttribute('data-size', 'lg');
}
});
@@ -2987,12 +2989,12 @@ describe('MultiSelector dropdown option theme target', () => {
await user.click(screen.getByRole('combobox'));
const [selected, plain, disabled] = screen.getAllByRole('option', h);
- expect(selected).toHaveClass('selected');
expect(selected).toHaveAttribute('data-selected', 'selected');
- expect(plain).not.toHaveClass('selected');
+ expect(selected).toHaveAttribute('data-selected', 'selected');
+ expect(plain).not.toHaveAttribute('data-selected');
expect(plain).not.toHaveAttribute('data-selected');
- expect(disabled).toHaveClass('disabled');
+ expect(disabled).toHaveAttribute('data-disabled', 'disabled');
expect(disabled).toHaveAttribute('data-disabled', 'disabled');
expect(plain).not.toHaveAttribute('data-disabled');
});
@@ -3013,7 +3015,7 @@ describe('MultiSelector dropdown option theme target', () => {
const [selectAllRow, ...regularRows] = screen.getAllByRole('option', h);
expect(selectAllRow).toHaveTextContent('Select all');
expect(selectAllRow).toHaveClass('astryx-multi-selector-option');
- expect(selectAllRow).toHaveClass('select-all');
+ expect(selectAllRow).toHaveAttribute('data-select-all', 'select-all');
expect(selectAllRow).toHaveAttribute('data-select-all', 'select-all');
for (const row of regularRows) {
@@ -3058,9 +3060,13 @@ describe('MultiSelector dropdown option theme target', () => {
});
const css = generateThemeTestCSS(theme);
expect(css).toContain('.astryx-multi-selector-option {');
- expect(css).toContain('.astryx-multi-selector-option.selected');
- expect(css).toContain('.astryx-multi-selector-option.select-all');
- expect(css).toContain('.astryx-multi-selector-option.lg');
+ expect(css).toContain(
+ '.astryx-multi-selector-option[data-selected="selected"]',
+ );
+ expect(css).toContain(
+ '.astryx-multi-selector-option[data-select-all="select-all"]',
+ );
+ expect(css).toContain('.astryx-multi-selector-option[data-size="lg"]');
});
});
diff --git a/packages/core/src/NumberInput/NumberInput.test.tsx b/packages/core/src/NumberInput/NumberInput.test.tsx
index e1e72d1062..78c1839f0e 100644
--- a/packages/core/src/NumberInput/NumberInput.test.tsx
+++ b/packages/core/src/NumberInput/NumberInput.test.tsx
@@ -2273,7 +2273,6 @@ describe('NumberInput disabled theme state', () => {
);
const root = container.querySelector('.astryx-number-input');
expect(root).toHaveAttribute('data-disabled', 'disabled');
- expect(root).toHaveClass('disabled');
});
it('omits data-disabled when enabled, like status does', () => {
diff --git a/packages/core/src/Outline/Outline.test.tsx b/packages/core/src/Outline/Outline.test.tsx
index 18f9ece672..2ef3a9af2f 100644
--- a/packages/core/src/Outline/Outline.test.tsx
+++ b/packages/core/src/Outline/Outline.test.tsx
@@ -162,8 +162,9 @@ describe('Outline', () => {
expect(screen.getByRole('link', {name: 'API'}).className).toContain(
'active',
);
- expect(screen.getByRole('link', {name: 'API'}).className).toContain(
- 'level-3',
+ expect(screen.getByRole('link', {name: 'API'})).toHaveAttribute(
+ 'data-level',
+ '3',
);
});
@@ -171,14 +172,16 @@ describe('Outline', () => {
render(
<Outline items={items} density="compact" data-testid="outline-compact" />,
);
- expect(screen.getByTestId('outline-compact').className).toContain(
+ expect(screen.getByTestId('outline-compact')).toHaveAttribute(
+ 'data-density',
'compact',
);
});
it('renders with density="default" by default', () => {
render(<Outline items={items} data-testid="outline-default" />);
- expect(screen.getByTestId('outline-default').className).toContain(
+ expect(screen.getByTestId('outline-default')).toHaveAttribute(
+ 'data-density',
'default',
);
});
diff --git a/packages/core/src/RadioList/RadioList.test.tsx b/packages/core/src/RadioList/RadioList.test.tsx
index 882eee2b2d..6cd84f7505 100644
--- a/packages/core/src/RadioList/RadioList.test.tsx
+++ b/packages/core/src/RadioList/RadioList.test.tsx
@@ -15,29 +15,6 @@ import userEvent from '@testing-library/user-event';
import {RadioList} from './RadioList';
import {RadioListItem} from './RadioListItem';
import {getForcedColorsRules} from '../__tests__/forcedColors';
-interface InjectedRule {
- selector: string;
- text: string;
- media: string | null;
-}
-
-function injectedRules(): InjectedRule[] {
- const walk = (rules: CSSRuleList, condition: string | null): InjectedRule[] =>
- [...rules].flatMap((rule): InjectedRule[] => {
- const {selectorText} = rule as CSSStyleRule;
- if (typeof selectorText === 'string') {
- return [{selector: selectorText, text: rule.cssText, media: condition}];
- }
- const nested = (rule as CSSGroupingRule).cssRules;
- if (nested == null) {
- return [];
- }
- const own = (rule as CSSMediaRule).media?.mediaText;
- return walk(nested, own != null && own !== '' ? own : condition);
- });
-
- return [...document.styleSheets].flatMap(sheet => walk(sheet.cssRules, null));
-}
// Mock showPopover/hidePopover (not implemented in jsdom) so the tooltip layer
// reflects its open state via a `popover-open` attribute the tests can assert.
@@ -844,7 +821,7 @@ describe('RadioList', () => {
for (const testid of ['row-a', 'row-b']) {
const row = screen.getByTestId(testid);
expect(row).toHaveClass('astryx-radio-list-item');
- expect(row).toHaveClass('sm');
+ expect(row).toHaveAttribute('data-size', 'sm');
expect(row).toHaveAttribute('data-size', 'sm');
}
});
@@ -866,12 +843,12 @@ describe('RadioList', () => {
const plain = screen.getByTestId('plain');
const disabled = screen.getByTestId('disabled');
- expect(selected).toHaveClass('selected');
expect(selected).toHaveAttribute('data-selected', 'selected');
- expect(plain).not.toHaveClass('selected');
+ expect(selected).toHaveAttribute('data-selected', 'selected');
+ expect(plain).not.toHaveAttribute('data-selected');
expect(plain).not.toHaveAttribute('data-selected');
- expect(disabled).toHaveClass('disabled');
+ expect(disabled).toHaveAttribute('data-disabled', 'disabled');
expect(disabled).toHaveAttribute('data-disabled', 'disabled');
expect(plain).not.toHaveAttribute('data-disabled');
});
diff --git a/packages/core/src/Section/Section.test.tsx b/packages/core/src/Section/Section.test.tsx
index d03706af75..75b108e9d9 100644
--- a/packages/core/src/Section/Section.test.tsx
+++ b/packages/core/src/Section/Section.test.tsx
@@ -41,7 +41,7 @@ describe('Section', () => {
const {container} = render(<Section>Content</Section>);
const inner = container.firstElementChild!.firstElementChild!;
expect(inner.className).toContain('astryx-section');
- expect(inner.className).toContain('section');
+ expect(inner).toHaveAttribute('data-variant', 'section');
});
it('renders with variant="transparent"', () => {
@@ -50,14 +50,14 @@ describe('Section', () => {
);
const inner = container.firstElementChild!.firstElementChild!;
expect(inner.className).toContain('astryx-section');
- expect(inner.className).toContain('transparent');
+ expect(inner).toHaveAttribute('data-variant', 'transparent');
});
it('renders with variant="muted"', () => {
const {container} = render(<Section variant="muted">Content</Section>);
const inner = container.firstElementChild!.firstElementChild!;
expect(inner.className).toContain('astryx-section');
- expect(inner.className).toContain('muted');
+ expect(inner).toHaveAttribute('data-variant', 'muted');
});
it('renders with dividers', () => {
@@ -126,7 +126,7 @@ describe('Section', () => {
const {container} = render(<Section variant="muted">Content</Section>);
const inner = container.firstElementChild!.firstElementChild!;
expect(inner.className).toContain('astryx-section');
- expect(inner.className).toContain('muted');
+ expect(inner).toHaveAttribute('data-variant', 'muted');
});
it('accepts xstyle prop without error', () => {
diff --git a/packages/core/src/Selector/Selector.test.tsx b/packages/core/src/Selector/Selector.test.tsx
index b49029226b..ae09607234 100644
--- a/packages/core/src/Selector/Selector.test.tsx
+++ b/packages/core/src/Selector/Selector.test.tsx
@@ -3185,7 +3185,9 @@ describe('Selector indicator (chevron) icon theme target', () => {
expect(css).toContain('.astryx-selector-indicator-icon {');
expect(css).toContain('width: 14px');
expect(css).toContain('height: 14px');
- expect(css).toContain('.astryx-selector-indicator-icon.expanded');
+ expect(css).toContain(
+ '.astryx-selector-indicator-icon[data-state="expanded"]',
+ );
expect(css).toContain('color: var(--color-icon-primary)');
});
});
@@ -3599,7 +3601,7 @@ describe('Selector disabled state theme target', () => {
);
const root = getSelectorRoot(container);
expect(root).not.toHaveAttribute('data-disabled');
- expect(root).not.toHaveClass('disabled');
+ expect(root).not.toHaveAttribute('data-disabled');
});
it('exposes the disabled state so a theme can key on it', () => {
@@ -3612,7 +3614,7 @@ describe('Selector disabled state theme target', () => {
},
});
const css = generateThemeTestCSS(theme);
- expect(css).toContain('.astryx-selector.disabled');
+ expect(css).toContain('.astryx-selector[data-disabled="disabled"]');
expect(css).toContain('opacity: 0.4');
});
});
@@ -3816,7 +3818,7 @@ describe('Selector option-row theme target', () => {
expect(options).toHaveLength(3);
for (const option of options) {
expect(option).toHaveClass('astryx-selector-option-row');
- expect(option).toHaveClass('lg');
+ expect(option).toHaveAttribute('data-size', 'lg');
expect(option).toHaveAttribute('data-size', 'lg');
}
});
@@ -3909,9 +3911,13 @@ describe('Selector option-row theme target', () => {
});
const css = generateThemeTestCSS(theme);
expect(css).toContain('.astryx-selector-option-row {');
- expect(css).toContain('.astryx-selector-option-row.selected');
- expect(css).toContain('.astryx-selector-option-row.disabled');
- expect(css).toContain('.astryx-selector-option-row.md');
+ expect(css).toContain(
+ '.astryx-selector-option-row[data-selected="selected"]',
+ );
+ expect(css).toContain(
+ '.astryx-selector-option-row[data-disabled="disabled"]',
+ );
+ expect(css).toContain('.astryx-selector-option-row[data-size="md"]');
});
});
diff --git a/packages/core/src/Spinner/Spinner.test.tsx b/packages/core/src/Spinner/Spinner.test.tsx
index 40066bd657..e088a54e7e 100644
--- a/packages/core/src/Spinner/Spinner.test.tsx
+++ b/packages/core/src/Spinner/Spinner.test.tsx
@@ -200,7 +200,9 @@ describe('Spinner', () => {
// the bug a size-variant key exists to avoid.
expect(
cssFor({spinner: {'size:xl': {'--spinner-diameter': '2.5rem'}}}),
- ).toContain('.astryx-spinner.xl {\n --spinner-diameter: 2.5rem;');
+ ).toContain(
+ '.astryx-spinner[data-size="xl"] {\n --spinner-diameter: 2.5rem;',
+ );
});
it('scopes a themed color to that shade variant', () => {
@@ -209,7 +211,7 @@ describe('Spinner', () => {
spinner: {'shade:subtle': {'--spinner-track-color': 'transparent'}},
}),
).toContain(
- '.astryx-spinner.subtle {\n --spinner-track-color: transparent;',
+ '.astryx-spinner[data-shade="subtle"] {\n --spinner-track-color: transparent;',
);
});
diff --git a/packages/core/src/Spinner/Spinner.tsx b/packages/core/src/Spinner/Spinner.tsx
index 34ff23f919..5468a830b3 100644
--- a/packages/core/src/Spinner/Spinner.tsx
+++ b/packages/core/src/Spinner/Spinner.tsx
@@ -333,7 +333,7 @@ const styles = stylex.create({
// What each named `size` and `shade` resolve to. Both groups DECLARE the four
// public vars, on the element that carries the `spinner` theme target, and
// everything downstream reads them — so a theme's `@layer astryx-theme` rule
-// against `.astryx-spinner.xl` overrides the default the same way it does for
+// against `.astryx-spinner[data-size="xl"]` overrides the default the same way it does for
// `--tree-list-indent` or `--button-focus-offset`, e.g.
// spinner: { 'size:xl': { '--spinner-diameter': '40px' } }.
//
diff --git a/packages/core/src/Stepper/Stepper.test.tsx b/packages/core/src/Stepper/Stepper.test.tsx
index 9b861c17eb..be17c59b9b 100644
--- a/packages/core/src/Stepper/Stepper.test.tsx
+++ b/packages/core/src/Stepper/Stepper.test.tsx
@@ -1927,9 +1927,9 @@ describe('step-label and step-description theme targets', () => {
const label = container.querySelector('.astryx-step-label');
const description = container.querySelector('.astryx-step-description');
expect(label).toHaveAttribute('data-disabled', 'disabled');
- expect(label).toHaveClass('disabled');
+ expect(label).toHaveAttribute('data-disabled', 'disabled');
+ expect(description).not.toHaveAttribute('data-disabled');
expect(description).not.toHaveAttribute('data-disabled');
- expect(description).not.toHaveClass('disabled');
// A DOM attribute alone would not prove the public defineTheme path accepts
// and emits the state. Hold both halves of the contract.
@@ -1942,7 +1942,7 @@ describe('step-label and step-description theme targets', () => {
},
});
const {component: css} = generateThemeCSS(theme);
- expect(css).toContain('.astryx-step-label.disabled');
+ expect(css).toContain('.astryx-step-label[data-disabled="disabled"]');
expect(css).toContain('opacity: 0.4');
});
diff --git a/packages/core/src/Switch/Switch.test.tsx b/packages/core/src/Switch/Switch.test.tsx
index 55652e779f..436c3e2a23 100644
--- a/packages/core/src/Switch/Switch.test.tsx
+++ b/packages/core/src/Switch/Switch.test.tsx
@@ -32,30 +32,6 @@ import {
} from '../__tests__/forcedColors';
import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';
-interface InjectedRule {
- selector: string;
- text: string;
- media: string | null;
-}
-
-function injectedRules(): InjectedRule[] {
- const walk = (rules: CSSRuleList, condition: string | null): InjectedRule[] =>
- [...rules].flatMap((rule): InjectedRule[] => {
- const {selectorText} = rule as CSSStyleRule;
- if (typeof selectorText === 'string') {
- return [{selector: selectorText, text: rule.cssText, media: condition}];
- }
- const nested = (rule as CSSGroupingRule).cssRules;
- if (nested == null) {
- return [];
- }
- const own = (rule as CSSMediaRule).media?.mediaText;
- return walk(nested, own != null && own !== '' ? own : condition);
- });
-
- return [...document.styleSheets].flatMap(sheet => walk(sheet.cssRules, null));
-}
-
afterEach(() => {
__resetLiveRegionsForTest();
});
@@ -603,7 +579,10 @@ describe('Switch', () => {
'data-label-spacing',
'spread',
);
- expect(getField(container).className).toContain('spread');
+ expect(getField(container)).toHaveAttribute(
+ 'data-label-spacing',
+ 'spread',
+ );
});
it('renders explicit hug the same as the default', () => {
diff --git a/packages/core/src/Text/Text.test.tsx b/packages/core/src/Text/Text.test.tsx
index 4361227f1d..26e1e901d8 100644
--- a/packages/core/src/Text/Text.test.tsx
+++ b/packages/core/src/Text/Text.test.tsx
@@ -145,7 +145,6 @@ describe('Text', () => {
);
const element = screen.getByText('Tiny code');
expect(element).toHaveAttribute('data-size', '2xs');
- expect(element.className).toContain('size-2xs');
});
it('accepts display prop', () => {
@@ -225,11 +224,11 @@ describe('Text', () => {
});
});
- it('renders astryx-* class names for theme targeting', () => {
+ it('renders the stable target and type data attribute for theme targeting', () => {
render(<Text type="body">Themed Text</Text>);
const element = screen.getByText('Themed Text');
expect(element.className).toContain('astryx-text');
- expect(element.className).toContain('body');
+ expect(element).toHaveAttribute('data-type', 'body');
});
});
@@ -239,12 +238,15 @@ describe('Text custom types', () => {
const el = screen.getByText('Custom');
expect(el).toBeInTheDocument();
expect(el.className).toContain('astryx-text');
- expect(el.className).toContain('hero');
+ expect(el).toHaveAttribute('data-type', 'hero');
});
it('applies primary color to custom types by default', () => {
render(<Text type={'caption' as TextType}>Caption</Text>);
- expect(screen.getByText('Caption').className).toContain('primary');
+ expect(screen.getByText('Caption')).toHaveAttribute(
+ 'data-color',
+ 'primary',
+ );
});
it('allows color override on custom types', () => {
@@ -253,20 +255,23 @@ describe('Text custom types', () => {
Muted
</Text>,
);
- expect(screen.getByText('Muted').className).toContain('secondary');
+ expect(screen.getByText('Muted')).toHaveAttribute(
+ 'data-color',
+ 'secondary',
+ );
});
});
describe('Text custom colors', () => {
- it('renders a custom color as a stable class for theme CSS to target', () => {
- // A theme adds a custom color (e.g. via TextColorMap augmentation +
- // defineTheme). The rendered element carries the color as a class
- // (astryx-text.<color>) so `.astryx-text.brand { color: ... }` from the
- // theme applies — mirroring how custom `type`s work.
+ it('reflects a custom color for theme CSS to target', () => {
+ // A theme adds a custom color through TextColorMap augmentation and
+ // defineTheme. The rendered element keeps the stable Text target and
+ // reflects the custom value as data-color so the generated theme selector
+ // can reach it without a collision-prone bare class.
render(<Text color={'brand' as TextColor}>Branded</Text>);
const el = screen.getByText('Branded');
expect(el.className).toContain('astryx-text');
- expect(el.className).toContain('brand');
+ expect(el).toHaveAttribute('data-color', 'brand');
});
it('does not crash on a custom color (falls back to the primary StyleX baseline)', () => {
@@ -282,7 +287,7 @@ describe('Text custom colors', () => {
const custom = screen.getByText('Custom');
const builtin = screen.getByText('Builtin');
// Neither throws, and the custom color reuses primary's baseline StyleX
- // class (the real color comes from theme CSS via the `brand` class).
+ // class (the real color comes from theme CSS via `data-color="brand"`).
const primaryAtomic = builtin.className
.split(/\s+/)
.filter(c => c.startsWith('x'));
@@ -294,7 +299,7 @@ describe('Text custom colors', () => {
it('still applies built-in colors directly', () => {
render(<Text color="accent">Accent</Text>);
- expect(screen.getByText('Accent').className).toContain('accent');
+ expect(screen.getByText('Accent')).toHaveAttribute('data-color', 'accent');
});
});
diff --git a/packages/core/src/Text/text.stylex.ts b/packages/core/src/Text/text.stylex.ts
index c25ad13fb6..1cfe26f993 100644
--- a/packages/core/src/Text/text.stylex.ts
+++ b/packages/core/src/Text/text.stylex.ts
@@ -101,8 +101,7 @@ export const defaultWeightByTypeStyles = stylex.create({
// Baseline Size/Leading by Type (from type-scale tokens)
//
// These ensure Text renders with correct sizing even without a theme.
-// Theme component overrides (.astryx-text.body { ... } today, plus data-type
-// reflection on rendered text elements) win when present
+// Theme component overrides (`.astryx-text[data-type="body"]`, etc.) win when
// because they have higher specificity via @scope.
// =============================================================================
diff --git a/packages/core/src/TextArea/TextArea.test.tsx b/packages/core/src/TextArea/TextArea.test.tsx
index acf7aa6811..882ee455b5 100644
--- a/packages/core/src/TextArea/TextArea.test.tsx
+++ b/packages/core/src/TextArea/TextArea.test.tsx
@@ -1126,7 +1126,6 @@ describe('TextArea disabled theme state', () => {
);
const root = container.querySelector('.astryx-textarea');
expect(root).toHaveAttribute('data-disabled', 'disabled');
- expect(root).toHaveClass('disabled');
});
it('omits data-disabled when enabled, like status does', () => {
diff --git a/packages/core/src/TextInput/TextInput.test.tsx b/packages/core/src/TextInput/TextInput.test.tsx
index 4ff1a9c1b0..9387a03d4b 100644
--- a/packages/core/src/TextInput/TextInput.test.tsx
+++ b/packages/core/src/TextInput/TextInput.test.tsx
@@ -969,7 +969,6 @@ describe('TextInput disabled theme state', () => {
);
const root = container.querySelector('.astryx-text-input');
expect(root).toHaveAttribute('data-disabled', 'disabled');
- expect(root).toHaveClass('disabled');
});
it('omits data-disabled when enabled, like status does', () => {
diff --git a/packages/core/src/TimeInput/TimeInput.test.tsx b/packages/core/src/TimeInput/TimeInput.test.tsx
index f79bf0be63..ab6af605a5 100644
--- a/packages/core/src/TimeInput/TimeInput.test.tsx
+++ b/packages/core/src/TimeInput/TimeInput.test.tsx
@@ -689,7 +689,6 @@ describe('TimeInput disabled theme state', () => {
);
const root = container.querySelector('.astryx-time-input');
expect(root).toHaveAttribute('data-disabled', 'disabled');
- expect(root).toHaveClass('disabled');
});
it('omits data-disabled when enabled, like status does', () => {
diff --git a/packages/core/src/Token/Token.test.tsx b/packages/core/src/Token/Token.test.tsx
index 758c11b8f6..c5846d003e 100644
--- a/packages/core/src/Token/Token.test.tsx
+++ b/packages/core/src/Token/Token.test.tsx
@@ -65,7 +65,7 @@ describe('Token', () => {
/>,
);
const token = screen.getByTestId('token-custom');
- expect(token).toHaveClass('astryx-token', 'brand');
+ expect(token).toHaveClass('astryx-token');
expect(token).toHaveAttribute('data-color', 'brand');
});
diff --git a/packages/core/src/Tokenizer/Tokenizer.test.tsx b/packages/core/src/Tokenizer/Tokenizer.test.tsx
index 59475f05d6..b55a203266 100644
--- a/packages/core/src/Tokenizer/Tokenizer.test.tsx
+++ b/packages/core/src/Tokenizer/Tokenizer.test.tsx
@@ -1392,7 +1392,6 @@ describe('Tokenizer disabled theme state', () => {
);
const root = container.querySelector('.astryx-tokenizer');
expect(root).toHaveAttribute('data-disabled', 'disabled');
- expect(root).toHaveClass('disabled');
});
it('omits data-disabled when enabled, like status does', () => {
diff --git a/packages/core/src/Toolbar/Toolbar.test.tsx b/packages/core/src/Toolbar/Toolbar.test.tsx
index 744035201f..4636a66b63 100644
--- a/packages/core/src/Toolbar/Toolbar.test.tsx
+++ b/packages/core/src/Toolbar/Toolbar.test.tsx
@@ -142,22 +142,22 @@ describe('Toolbar', () => {
);
});
- it('applies size class', () => {
+ it('reflects the size', () => {
render(<Toolbar label="Actions" size="sm" />);
const toolbar = screen.getByRole('toolbar');
- expect(toolbar.className).toContain('sm');
+ expect(toolbar).toHaveAttribute('data-size', 'sm');
});
it('defaults to md size', () => {
render(<Toolbar label="Actions" />);
const toolbar = screen.getByRole('toolbar');
- expect(toolbar.className).toContain('md');
+ expect(toolbar).toHaveAttribute('data-size', 'md');
});
- it('applies lg size class', () => {
+ it('reflects lg size', () => {
render(<Toolbar label="Actions" size="lg" />);
const toolbar = screen.getByRole('toolbar');
- expect(toolbar.className).toContain('lg');
+ expect(toolbar).toHaveAttribute('data-size', 'lg');
});
it('forwards ref to root element', () => {
@@ -171,14 +171,14 @@ describe('Toolbar', () => {
// Section renders with astryx-section class containing the variant
const sectionInner = container.querySelector('.astryx-section');
expect(sectionInner).toBeInTheDocument();
- expect(sectionInner?.className).toContain('muted');
+ expect(sectionInner).toHaveAttribute('data-variant', 'muted');
});
it('defaults to transparent variant', () => {
const {container} = render(<Toolbar label="Actions" />);
const sectionInner = container.querySelector('.astryx-section');
expect(sectionInner).toBeInTheDocument();
- expect(sectionInner?.className).toContain('transparent');
+ expect(sectionInner).toHaveAttribute('data-variant', 'transparent');
});
it('navigates with ArrowRight/ArrowLeft in horizontal orientation', async () => {
diff --git a/packages/core/src/TreeList/TreeList.test.tsx b/packages/core/src/TreeList/TreeList.test.tsx
index 87aad95a34..9c556c40d3 100644
--- a/packages/core/src/TreeList/TreeList.test.tsx
+++ b/packages/core/src/TreeList/TreeList.test.tsx
@@ -865,7 +865,7 @@ describe('TreeList', () => {
const css = generateThemeTestCSS(theme);
expect(css).toContain('.astryx-tree-list-chevron {');
expect(css).toContain('color: var(--color-accent)');
- expect(css).toContain('.astryx-tree-list-chevron.expanded');
+ expect(css).toContain('.astryx-tree-list-chevron[data-state="expanded"]');
expect(css).toContain('color: var(--color-text-primary)');
});
});
@@ -923,7 +923,9 @@ describe('TreeList', () => {
const css = generateThemeTestCSS(theme);
expect(css).toContain('.astryx-tree-list-item-label {');
expect(css).toContain('color: var(--color-text-primary)');
- expect(css).toContain('.astryx-tree-list-item-label.selected');
+ expect(css).toContain(
+ '.astryx-tree-list-item-label[data-selected="selected"]',
+ );
expect(css).toContain('font-weight: var(--font-weight-bold)');
});
});
diff --git a/packages/core/src/theme/Theme.tsx b/packages/core/src/theme/Theme.tsx
index 3be95080c2..e625fd0bcc 100644
--- a/packages/core/src/theme/Theme.tsx
+++ b/packages/core/src/theme/Theme.tsx
@@ -8,9 +8,8 @@
* Applies theme tokens and sets color-scheme for light-dark() to work.
* Themes are created with `defineTheme()` and applied via CSS:
* - Token overrides set as CSS custom properties on [data-astryx-theme]
- * - Component overrides scoped via @scope'd CSS selectors on the stable Astryx
- * selector surface (`.xds-*` classes today; components also emit `data-*`
- * prop reflections for the data-attribute selector migration)
+ * - Component overrides scoped via @scope'd CSS selectors on stable Astryx
+ * target classes combined with reflected `data-*` prop/state attributes
*
* Root detection: The first Theme in the tree (no parent Theme)
* automatically syncs attributes to `document.documentElement`:
diff --git a/packages/core/src/theme/defineTheme.test.ts b/packages/core/src/theme/defineTheme.test.ts
index ea9c065bf6..5920d0bcd0 100644
--- a/packages/core/src/theme/defineTheme.test.ts
+++ b/packages/core/src/theme/defineTheme.test.ts
@@ -385,7 +385,7 @@ describe('generateThemeCSS with components', () => {
},
});
const css = generateThemeTestCSS(theme);
- expect(css).toContain('.astryx-button.secondary');
+ expect(css).toContain('.astryx-button[data-variant="secondary"]');
expect(css).toContain('background-color: rgba(0,0,0,0.06)');
});
@@ -401,7 +401,9 @@ describe('generateThemeCSS with components', () => {
},
});
const css = generateThemeTestCSS(theme);
- expect(css).toContain('.astryx-button.destructive.sm');
+ expect(css).toContain(
+ '.astryx-button[data-variant="destructive"][data-size="sm"]',
+ );
expect(css).toContain('padding: 2px 6px');
});
@@ -662,8 +664,8 @@ describe('custom status via components', () => {
},
});
const css = generateThemeTestCSS(theme);
- // parseStyleKey('status:neutral') → '.neutral', so CSS should have .astryx-banner.neutral
- expect(css).toContain('.astryx-banner.neutral');
+ // The status axis remains explicit in the generated data-attribute selector.
+ expect(css).toContain('.astryx-banner[data-status="neutral"]');
expect(css).toContain('background-color: var(--color-background-muted)');
});
@@ -695,7 +697,7 @@ describe('custom status via components', () => {
},
});
const css = generateThemeTestCSS(theme);
- expect(css).toContain('.astryx-button.primary-muted');
+ expect(css).toContain('.astryx-button[data-variant="primary-muted"]');
expect(css).toContain('background-color: #ECF5FF');
});
@@ -937,13 +939,15 @@ describe('pseudo-class overrides in components', () => {
},
});
const css = generateThemeTestCSS(theme);
- expect(css).toContain('.astryx-button.primary-muted {');
+ expect(css).toContain('.astryx-button[data-variant="primary-muted"] {');
expect(css).toContain('background-color: #ECF5FF');
expect(css).toContain(
- '.astryx-button.primary-muted:hover:where(:not(:disabled,[aria-disabled="true"])) {',
+ '.astryx-button[data-variant="primary-muted"]:hover:where(:not(:disabled,[aria-disabled="true"])) {',
);
expect(css).toContain('background-color: #D6EBFF');
- expect(css).toContain('.astryx-button.primary-muted:focus-visible {');
+ expect(css).toContain(
+ '.astryx-button[data-variant="primary-muted"]:focus-visible {',
+ );
expect(css).toContain('outline: 2px solid var(--color-accent)');
});
diff --git a/packages/core/src/theme/generateThemeRules.test.ts b/packages/core/src/theme/generateThemeRules.test.ts
index 1094d2c8b7..72eb45b5c3 100644
--- a/packages/core/src/theme/generateThemeRules.test.ts
+++ b/packages/core/src/theme/generateThemeRules.test.ts
@@ -152,10 +152,10 @@ describe('generateThemeRules', () => {
// --- Component overrides ---
- it('includes .astryx-heading.level-* rules for all 6 levels', () => {
+ it('includes data-level rules on the stable heading target for all 6 levels', () => {
for (let level = 1; level <= 6; level++) {
const rule = rules.find(r =>
- r.includes(`.astryx-heading.level-${level}`),
+ r.includes(`.astryx-heading[data-level="${level}"]`),
);
expect(rule).toBeDefined();
expect(rule).toContain('font-family');
@@ -167,14 +167,18 @@ describe('generateThemeRules', () => {
it('includes .astryx-text.* rules for all 5 types', () => {
for (const type of ['body', 'large', 'label', 'code', 'supporting']) {
- const rule = rules.find(r => r.includes(`.astryx-text.${type}`));
+ const rule = rules.find(r =>
+ r.includes(`.astryx-text[data-type="${type}"]`),
+ );
expect(rule).toBeDefined();
expect(rule).toContain(`var(--text-${type}-size)`);
}
});
it('includes explicit component overrides', () => {
- const buttonRule = rules.find(r => r.includes('.astryx-button.secondary'));
+ const buttonRule = rules.find(r =>
+ r.includes('.astryx-button[data-variant="secondary"]'),
+ );
expect(buttonRule).toBeDefined();
expect(buttonRule).toContain('light-dark(rgba(5, 54, 89, 0.1)');
});
@@ -275,12 +279,24 @@ describe('generateThemeRules', () => {
// --- Prop-level color overrides ---
it('includes color prop overrides for text and heading', () => {
- expect(rules.some(r => r.includes('.astryx-text.primary'))).toBe(true);
- expect(rules.some(r => r.includes('.astryx-text.secondary'))).toBe(true);
- expect(rules.some(r => r.includes('.astryx-heading.primary'))).toBe(true);
- expect(rules.some(r => r.includes('.astryx-heading.disabled'))).toBe(true);
- expect(rules.some(r => r.includes('.astryx-text.active'))).toBe(false);
- expect(rules.some(r => r.includes('.astryx-text.accent'))).toBe(true);
+ expect(
+ rules.some(r => r.includes('.astryx-text[data-color="primary"]')),
+ ).toBe(true);
+ expect(
+ rules.some(r => r.includes('.astryx-text[data-color="secondary"]')),
+ ).toBe(true);
+ expect(
+ rules.some(r => r.includes('.astryx-heading[data-color="primary"]')),
+ ).toBe(true);
+ expect(
+ rules.some(r => r.includes('.astryx-heading[data-color="disabled"]')),
+ ).toBe(true);
+ expect(
+ rules.some(r => r.includes('.astryx-text[data-color="active"]')),
+ ).toBe(false);
+ expect(
+ rules.some(r => r.includes('.astryx-text[data-color="accent"]')),
+ ).toBe(true);
});
// --- Size-prop overrides (so `size` beats a themed `type`) ---
@@ -288,13 +304,16 @@ describe('generateThemeRules', () => {
it('emits Text size-prop font-size overrides in the same layer as type rules', () => {
// Digit-leading sizes are prefixed (size-2xs); word sizes stay bare.
const sizeRule = rules.find(
- r => r.includes('.astryx-text.size-2xs') && r.includes('font-size'),
+ r =>
+ r.includes('.astryx-text[data-size="2xs"]') && r.includes('font-size'),
);
expect(sizeRule).toBeDefined();
expect(sizeRule).toContain('var(--font-size-2xs)');
// `xsm` maps to the --font-size-xs token (matches sizeStyles).
- const xsmRule = rules.find(r => r.includes('.astryx-text.xsm'));
+ const xsmRule = rules.find(r =>
+ r.includes('.astryx-text[data-size="xsm"]'),
+ );
expect(xsmRule).toBeDefined();
expect(xsmRule).toContain('var(--font-size-xs)');
@@ -319,7 +338,10 @@ describe('generateThemeRules', () => {
for (const cls of sizes) {
expect(
rules.some(
- r => r.includes(`.astryx-text.${cls}`) && r.includes('font-size'),
+ r =>
+ r.includes(
+ `.astryx-text[data-size="${cls.replace(/^size-/, '')}"]`,
+ ) && r.includes('font-size'),
),
).toBe(true);
}
@@ -329,10 +351,13 @@ describe('generateThemeRules', () => {
// Source order breaks specificity ties within a layer, so the size
// override must come after the `.astryx-text.<type>` type rule.
const typeIdx = rules.findIndex(
- r => r.includes('.astryx-text.supporting') && r.includes('font-size'),
+ r =>
+ r.includes('.astryx-text[data-type="supporting"]') &&
+ r.includes('font-size'),
);
const sizeIdx = rules.findIndex(
- r => r.includes('.astryx-text.size-2xs') && r.includes('font-size'),
+ r =>
+ r.includes('.astryx-text[data-size="2xs"]') && r.includes('font-size'),
);
expect(typeIdx).toBeGreaterThanOrEqual(0);
expect(sizeIdx).toBeGreaterThan(typeIdx);
@@ -356,9 +381,9 @@ describe('generateThemeRules', () => {
// layer as the type rules (astryx-theme / component block), not the
// reset-tier prose block.
const {prose, component} = generateThemeCSS(theme);
- expect(component).toContain('.astryx-text.size-2xs');
- expect(component).toContain('.astryx-text.xsm');
- expect(prose).not.toContain('.astryx-text.size-2xs');
+ expect(component).toContain('.astryx-text[data-size="2xs"]');
+ expect(component).toContain('.astryx-text[data-size="xsm"]');
+ expect(prose).not.toContain('.astryx-text[data-size="2xs"]');
});
});
@@ -410,10 +435,10 @@ describe('generateThemeRules with an explicit Heading weight prop', () => {
it('emits named weight rules after the custom type default', () => {
const typeIndex = rules.findIndex(rule =>
- rule.includes('.astryx-heading.hero'),
+ rule.includes('.astryx-heading[data-type="hero"]'),
);
const boldIndex = rules.findIndex(rule =>
- rule.includes('.astryx-heading.bold'),
+ rule.includes('.astryx-heading[data-weight="bold"]'),
);
expect(typeIndex).toBeGreaterThanOrEqual(0);
@@ -423,8 +448,8 @@ describe('generateThemeRules with an explicit Heading weight prop', () => {
it('keeps explicit weight rules in the component theme layer', () => {
const {component, prose} = generateThemeCSS(theme);
- expect(component).toContain('.astryx-heading.bold');
- expect(prose).not.toContain('.astryx-heading.bold');
+ expect(component).toContain('.astryx-heading[data-weight="bold"]');
+ expect(prose).not.toContain('.astryx-heading[data-weight="bold"]');
});
it('keeps a targeted theme weight rule authoritative', () => {
@@ -439,10 +464,10 @@ describe('generateThemeRules with an explicit Heading weight prop', () => {
});
const rules = generateThemeRules(authored);
const typeIndex = rules.findIndex(rule =>
- rule.includes('.astryx-heading.hero'),
+ rule.includes('.astryx-heading[data-type="hero"]'),
);
const boldRules = rules.filter(rule =>
- rule.includes('.astryx-heading.bold'),
+ rule.includes('.astryx-heading[data-weight="bold"]'),
);
const lastBoldIndex = rules.lastIndexOf(boldRules.at(-1) ?? '');
@@ -466,7 +491,7 @@ describe('generateThemeRules with an explicit Heading weight prop', () => {
expect(
rules.some(
rule =>
- rule.includes('.astryx-heading.bold') &&
+ rule.includes('.astryx-heading[data-weight="bold"]') &&
rule.includes('font-weight: var(--font-weight-bold)'),
),
).toBe(true);
@@ -487,7 +512,7 @@ describe('generateThemeRules with an explicit Heading weight prop', () => {
expect(
rules.some(
rule =>
- rule.includes('.astryx-heading.bold') &&
+ rule.includes('.astryx-heading[data-weight="bold"]') &&
rule.includes('font-weight: var(--font-weight-bold)'),
),
).toBe(true);
@@ -511,8 +536,8 @@ describe('generateThemeRules with an explicit Heading weight prop', () => {
},
});
const css = generateOnMediaCSS(themed);
- const typeIndex = css.indexOf('.astryx-heading.hero');
- const boldIndex = css.lastIndexOf('.astryx-heading.bold');
+ const typeIndex = css.indexOf('.astryx-heading[data-type="hero"]');
+ const boldIndex = css.lastIndexOf('.astryx-heading[data-weight="bold"]');
expect(typeIndex).toBeGreaterThanOrEqual(0);
expect(boldIndex).toBeGreaterThan(typeIndex);
@@ -536,8 +561,8 @@ describe('generateThemeRules with an explicit Heading weight prop', () => {
},
});
const css = generateOnMediaCSS(themed);
- const typeIndex = css.indexOf('.astryx-heading.hero');
- const boldIndex = css.lastIndexOf('.astryx-heading.bold');
+ const typeIndex = css.indexOf('.astryx-heading[data-type="hero"]');
+ const boldIndex = css.lastIndexOf('.astryx-heading[data-weight="bold"]');
expect(typeIndex).toBeGreaterThanOrEqual(0);
expect(boldIndex).toBeGreaterThan(typeIndex);
@@ -565,9 +590,9 @@ describe('generateThemeRules with an explicit Heading weight prop', () => {
['light', 'body'],
] as const) {
const surfacePrefix = `:is([data-astryx-media="${surface}"])`;
- const typeSelector = `${surfacePrefix} :is(.astryx-text.${type})`;
- const colorSelector = `${surfacePrefix} :is(.astryx-text.primary)`;
- const sizeSelector = `${surfacePrefix} :is(.astryx-text.sm)`;
+ const typeSelector = `${surfacePrefix} :is(.astryx-text[data-type="${type}"])`;
+ const colorSelector = `${surfacePrefix} :is(.astryx-text[data-color="primary"])`;
+ const sizeSelector = `${surfacePrefix} :is(.astryx-text[data-size="sm"])`;
const typeIndex = css.indexOf(typeSelector);
expect(typeIndex).toBeGreaterThanOrEqual(0);
@@ -612,19 +637,19 @@ describe('generateThemeRules with an explicit Heading weight prop', () => {
);
const rootGuard = blocks.find(block => block.startsWith('@scope '));
- expect(fineBlock).toContain('.astryx-heading.level-2');
+ expect(fineBlock).toContain('.astryx-heading[data-level="2"]');
expect(fineBlock).not.toContain('font-weight: 800');
expect(rootGuard).toContain(
- '.astryx-heading.normal { font-weight: var(--font-weight-normal); }',
+ '.astryx-heading[data-weight="normal"] { font-weight: var(--font-weight-normal); }',
);
expect(rootGuard).toContain(
- '.astryx-heading.medium { font-weight: var(--font-weight-medium); }',
+ '.astryx-heading[data-weight="medium"] { font-weight: var(--font-weight-medium); }',
);
expect(rootGuard).toContain(
- '.astryx-heading.semibold { font-weight: var(--font-weight-semibold); }',
+ '.astryx-heading[data-weight="semibold"] { font-weight: var(--font-weight-semibold); }',
);
expect(rootGuard).toContain(
- '.astryx-heading.bold { font-weight: var(--font-weight-bold); }',
+ '.astryx-heading[data-weight="bold"] { font-weight: var(--font-weight-bold); }',
);
expect(blocks.indexOf(rootGuard!)).toBeGreaterThan(
blocks.indexOf(fineBlock!),
@@ -669,7 +694,7 @@ describe('generateThemeRules with an explicit Heading weight prop', () => {
const broadLevelBlock = blocks.find(
block =>
block.startsWith('@media (prefers-contrast: more)') &&
- block.includes('.astryx-heading.level-2'),
+ block.includes('.astryx-heading[data-level="2"]'),
);
const rootGuard = blocks.find(block => block.startsWith('@scope '));
const coarseGuard = blocks
@@ -678,9 +703,11 @@ describe('generateThemeRules with an explicit Heading weight prop', () => {
expect(broadLevelBlock).not.toContain('font-weight: 800');
expect(rootGuard).toContain(
- '.astryx-heading.bold { font-weight: var(--font-weight-bold); }',
+ '.astryx-heading[data-weight="bold"] { font-weight: var(--font-weight-bold); }',
+ );
+ expect(coarseGuard).toContain(
+ '.astryx-heading[data-weight="bold"] { font-weight: 800; }',
);
- expect(coarseGuard).toContain('.astryx-heading.bold { font-weight: 800; }');
expect(blocks.indexOf(rootGuard!)).toBeGreaterThan(
blocks.indexOf(broadLevelBlock!),
);
@@ -757,8 +784,10 @@ describe('generateThemeRules with an explicit Heading weight prop', () => {
);
const rootGuard = blocks.find(block => block.startsWith('@scope '));
- expect(fineBlock).toContain('.astryx-heading.level-2');
- expect(rootGuard).toContain('.astryx-heading.bold { font-weight: 900; }');
+ expect(fineBlock).toContain('.astryx-heading[data-level="2"]');
+ expect(rootGuard).toContain(
+ '.astryx-heading[data-weight="bold"] { font-weight: 900; }',
+ );
expect(blocks.indexOf(rootGuard!)).toBeGreaterThan(
blocks.indexOf(fineBlock!),
);
@@ -790,12 +819,12 @@ describe('generateThemeRules with an explicit Heading weight prop', () => {
const rootGuard = blocks.find(block => block.startsWith('@scope '));
expect(coarseBlocks).toHaveLength(2);
- expect(coarseBlocks[0]).toContain('.astryx-heading.hero');
+ expect(coarseBlocks[0]).toContain('.astryx-heading[data-type="hero"]');
expect(rootGuard).toContain(
- '.astryx-heading.bold { font-weight: var(--font-weight-bold); }',
+ '.astryx-heading[data-weight="bold"] { font-weight: var(--font-weight-bold); }',
);
expect(coarseBlocks[1]).toContain(
- '.astryx-heading.bold { font-weight: 800; }',
+ '.astryx-heading[data-weight="bold"] { font-weight: 800; }',
);
expect(blocks.at(-1)).toBe(coarseBlocks[1]);
});
@@ -962,7 +991,9 @@ describe('derived var expansion', () => {
},
});
const rules = generateThemeRules(theme);
- const rule = rules.find(r => r.includes('.astryx-avatar-fallback.sm'));
+ const rule = rules.find(r =>
+ r.includes('.astryx-avatar-fallback[data-size="sm"]'),
+ );
expect(rule).toBeDefined();
expect(rule).toContain('font-size: 9px');
// Direct class target now — no internal derived var.
@@ -1012,7 +1043,9 @@ describe('derived var expansion', () => {
},
});
const rules = generateThemeRules(theme);
- const rule = rules.find(r => r.includes('.astryx-card.muted'));
+ const rule = rules.find(r =>
+ r.includes('.astryx-card[data-variant="muted"]'),
+ );
expect(rule).toBeDefined();
expect(rule).toContain('border-radius: 16px');
expect(rule).toContain('--_card-radius: 16px');
diff --git a/packages/core/src/theme/generateThemeRules.ts b/packages/core/src/theme/generateThemeRules.ts
index 05f4f8e46d..2af3a0fb69 100644
--- a/packages/core/src/theme/generateThemeRules.ts
+++ b/packages/core/src/theme/generateThemeRules.ts
@@ -153,7 +153,7 @@ export interface ThemeCSSOutput {
*/
prose: string;
/**
- * Token overrides + component .astryx-* overrides scoped to the theme.
+ * Token overrides + component target/data-attribute overrides scoped to the theme.
* Should be injected into @layer astryx-theme — above StyleX layers so
* theme component overrides take effect. Empty string if no rules.
*/
@@ -414,8 +414,8 @@ export function generateThemeRules(theme: ThemeRuleSource): string[] {
parts.push(` :scope {\n${declarations}\n }`);
}
- // 2. Component overrides (.astryx-* class rules; components also emit
- // data-* prop reflections for external selector migrations)
+ // 2. Component overrides: stable .astryx-* target classes combined with
+ // reflected data-* selectors for visual props and runtime states.
if (theme.components) {
generateComponentRules(theme.components, parts);
}
@@ -532,10 +532,9 @@ interface ComponentRuleOptions {
}
/**
- * Generate component override rules using the .astryx-* class selector
- * format. Runtime components also emit matching data-* prop reflections for
- * external selector migrations. Handles derived var expansion and container
- * padding mapping for every theme layer.
+ * Generate component override rules using stable `.astryx-*` target classes
+ * and reflected `data-*` selectors for prop/state keys. Handles derived var
+ * expansion and container padding mapping for every theme layer.
*/
function generateComponentRules(
components: Record<
@@ -743,17 +742,17 @@ function generateColorOverrides(
for (const [colorName, colorValue] of Object.entries(TEXT_COLOR_MAP)) {
if (touchesText) {
parts.push(
- ` ${componentSelector('text', `.${colorName}`, surface)} { color: ${colorValue}; }`,
+ ` ${componentSelector('text', parseStyleKey(`color:${colorName}`), surface)} { color: ${colorValue}; }`,
);
}
if (touchesHeading) {
parts.push(
- ` ${componentSelector('heading', `.${colorName}`, surface)} { color: ${colorValue}; }`,
+ ` ${componentSelector('heading', parseStyleKey(`color:${colorName}`), surface)} { color: ${colorValue}; }`,
);
}
if (touchesLink) {
parts.push(
- ` ${componentSelector('link', `.${colorName}`, surface)} { color: ${colorValue}; }`,
+ ` ${componentSelector('link', parseStyleKey(`color:${colorName}`), surface)} { color: ${colorValue}; }`,
);
}
}
@@ -820,7 +819,7 @@ function generateSizeOverrides(
* as themed defaults — conceptually the same tier as the CSS reset. They
* belong in the reset layer so any class-based style wins.
*
- * Component rules (tokens, .astryx-* overrides) are intentional theme overrides
+ * Component rules (tokens, stable .astryx-* targets plus data-* selectors) are
* that need to beat StyleX — they stay in astryx-theme (above StyleX layers).
*/
export function generateThemeRulesSplit(theme: DefinedTheme): ThemeRulesSplit {
diff --git a/packages/core/src/theme/onMediaTokens.test.ts b/packages/core/src/theme/onMediaTokens.test.ts
index 5ec3ba37a4..9464252f6a 100644
--- a/packages/core/src/theme/onMediaTokens.test.ts
+++ b/packages/core/src/theme/onMediaTokens.test.ts
@@ -140,9 +140,7 @@ describe('generateOnMediaCSS', () => {
it('emits @scope with [data-astryx-media] token rules', () => {
const theme = defineTheme({name: 'test'});
const css = generateOnMediaCSS(theme);
- expect(css).toContain(
- '@scope ([data-astryx-theme="test"])',
- );
+ expect(css).toContain('@scope ([data-astryx-theme="test"])');
// Same scope boundary as main theme
expect(css).toContain('to ([data-astryx-theme])');
expect(css).toContain('[data-astryx-media="dark"]');
@@ -172,7 +170,7 @@ describe('generateOnMediaCSS', () => {
});
const css = generateOnMediaCSS(theme);
expect(css).toContain(
- ':is([data-astryx-media="dark"]) :is(.astryx-button.secondary)',
+ ':is([data-astryx-media="dark"]) :is(.astryx-button[data-variant="secondary"])',
);
expect(css).toContain(
'background-color: color-mix(in srgb, white 20%, transparent)',
diff --git a/packages/core/src/theme/publicThemeHelperContract.test.ts b/packages/core/src/theme/publicThemeHelperContract.test.ts
new file mode 100644
index 0000000000..201168221b
--- /dev/null
+++ b/packages/core/src/theme/publicThemeHelperContract.test.ts
@@ -0,0 +1,67 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, expect, it} from 'vitest';
+import {parseStyleKey, themeProps} from '@astryxdesign/core/utils';
+import {
+ defineTheme,
+ generateOnMediaCSS,
+ generateThemeCSS,
+ generateThemeRules,
+ generateThemeRulesSplit,
+} from '@astryxdesign/core/theme';
+
+const theme = defineTheme({
+ name: 'public-helper-contract',
+ components: {
+ button: {
+ 'variant:primary': {color: 'red'},
+ },
+ },
+ onDark: {
+ components: {
+ button: {
+ 'variant:primary': {color: 'pink'},
+ },
+ },
+ },
+});
+
+const selector = '.astryx-button[data-variant="primary"]';
+
+describe('public theme helper selector contract', () => {
+ it('keeps themeProps shape while removing bare value classes', () => {
+ expect(themeProps('button', {variant: 'primary', size: 'sm'})).toEqual({
+ className: 'astryx-button',
+ 'data-variant': 'primary',
+ 'data-size': 'sm',
+ });
+ });
+
+ it('returns reflected data-attribute suffixes from parseStyleKey', () => {
+ expect(parseStyleKey('variant:primary+size:sm')).toBe(
+ '[data-variant="primary"][data-size="sm"]',
+ );
+ });
+
+ it('keeps generator containers while changing component selector bytes', () => {
+ const rules = generateThemeRules(theme);
+ expect(Array.isArray(rules)).toBe(true);
+ expect(rules.join('\n')).toContain(selector);
+ expect(rules.join('\n')).not.toContain('.astryx-button.primary');
+
+ const split = generateThemeRulesSplit(theme);
+ expect(Object.keys(split).sort()).toEqual(['component', 'prose']);
+ expect(split.component.join('\n')).toContain(selector);
+ expect(split.prose.join('\n')).not.toContain(selector);
+
+ const media = generateOnMediaCSS(theme);
+ expect(media).toContain(selector);
+ expect(media).not.toContain('.astryx-button.primary');
+
+ const css = generateThemeCSS(theme);
+ expect(Object.keys(css).sort()).toEqual(['component', 'prose']);
+ expect(css.component).toContain(selector);
+ expect(css.component).not.toContain('.astryx-button.primary');
+ expect(css.prose).not.toContain(selector);
+ });
+});
diff --git a/packages/core/src/utils/parseStyleKey.test.ts b/packages/core/src/utils/parseStyleKey.test.ts
index 9e50305cc7..91f3fa8b28 100644
--- a/packages/core/src/utils/parseStyleKey.test.ts
+++ b/packages/core/src/utils/parseStyleKey.test.ts
@@ -4,49 +4,53 @@ import {describe, it, expect} from 'vitest';
import {parseStyleKey} from './parseStyleKey';
describe('parseStyleKey', () => {
- it('returns empty string for base', () => {
+ it('returns no suffix for base', () => {
expect(parseStyleKey('base')).toBe('');
});
- it('converts variant:value to .value', () => {
- expect(parseStyleKey('variant:secondary')).toBe('.secondary');
+ it('preserves the prop axis in data-attribute selectors', () => {
+ expect(parseStyleKey('variant:secondary')).toBe(
+ '[data-variant="secondary"]',
+ );
+ expect(parseStyleKey('size:sm')).toBe('[data-size="sm"]');
});
- it('prefixes numeric values with prop name', () => {
- expect(parseStyleKey('level:1')).toBe('.level-1');
+ it('keeps numeric values literal', () => {
+ expect(parseStyleKey('level:2')).toBe('[data-level="2"]');
});
- it('handles compound keys', () => {
- expect(parseStyleKey('variant:destructive+size:sm')).toBe(
- '.destructive.sm',
+ it('kebab-cases camelCase prop names', () => {
+ expect(parseStyleKey('listStyle:ordered')).toBe(
+ '[data-list-style="ordered"]',
);
});
- it('handles compound with numeric value', () => {
- expect(parseStyleKey('variant:primary+level:2')).toBe('.primary.level-2');
- });
-});
-
-describe('parseStyleKey — bare state keys', () => {
- it('converts bare state to .state', () => {
- expect(parseStyleKey('checked')).toBe('.checked');
+ it('combines multiple prop selectors', () => {
+ expect(parseStyleKey('variant:destructive+size:sm')).toBe(
+ '[data-variant="destructive"][data-size="sm"]',
+ );
});
- it('converts disabled state', () => {
- expect(parseStyleKey('disabled')).toBe('.disabled');
+ it('converts bare states to reflected state attributes', () => {
+ expect(parseStyleKey('checked')).toBe('[data-checked="checked"]');
+ expect(parseStyleKey('checked+disabled')).toBe(
+ '[data-checked="checked"][data-disabled="disabled"]',
+ );
});
- it('converts selected state', () => {
- expect(parseStyleKey('selected')).toBe('.selected');
+ it('combines a prop selector and a bare state selector', () => {
+ expect(parseStyleKey('variant:destructive+disabled')).toBe(
+ '[data-variant="destructive"][data-disabled="disabled"]',
+ );
});
- it('handles compound bare states', () => {
- expect(parseStyleKey('checked+disabled')).toBe('.checked.disabled');
+ it('escapes CSS string metacharacters in values', () => {
+ expect(parseStyleKey('variant:quote"slash\\')).toBe(
+ '[data-variant="quote\\22 slash\\5c "]',
+ );
});
- it('handles mixed bare state + prop:value', () => {
- expect(parseStyleKey('variant:destructive+disabled')).toBe(
- '.destructive.disabled',
- );
+ it('preserves empty values for compatibility', () => {
+ expect(parseStyleKey('variant:')).toBe('[data-variant=""]');
});
});
diff --git a/packages/core/src/utils/parseStyleKey.ts b/packages/core/src/utils/parseStyleKey.ts
index 6de950aeef..4e8ae989ca 100644
--- a/packages/core/src/utils/parseStyleKey.ts
+++ b/packages/core/src/utils/parseStyleKey.ts
@@ -1,34 +1,50 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
+import {themeDataAttributeName} from './themeProps';
+
+/** Escape a value for a double-quoted CSS attribute selector string. */
+function escapeAttributeValue(value: string): string {
+ let escaped = '';
+ for (const char of value) {
+ const codePoint = char.codePointAt(0) ?? 0;
+ if (
+ char === '"' ||
+ char === '\\' ||
+ codePoint < 0x20 ||
+ codePoint === 0x7f
+ ) {
+ escaped += `\\${(codePoint === 0 ? 0xfffd : codePoint).toString(16)} `;
+ } else {
+ escaped += char;
+ }
+ }
+ return escaped;
+}
+
/**
- * Parse a component style key into a CSS selector suffix.
+ * Parse a component style key into a CSS data-attribute selector suffix.
*
- * Used by both defineTheme (CSS generation) and components (class name rendering)
- * to ensure the same convention is applied consistently.
+ * Used by the shared theme compiler so semantic authoring keys match the
+ * attributes emitted by `themeProps()`:
*
- * <!-- SYNC: packages/core/src/utils/themeProps.ts -->
- *
- * Emits the legacy class-selector suffix used by defineTheme/component override
- * generation today. Components also reflect the same prop values as data
- * attributes via `themeProps()` (`variant:secondary` renders both `.secondary`
- * and `[data-variant="secondary"]` in the DOM), but generated theme CSS still
- * uses these class selectors until the selector contract migrates fully.
+ * - `prop:value` selects `[data-prop="value"]`.
+ * - A bare state selects `[data-state="state"]`.
+ * - `+` combines selectors on the same stable `astryx-*` target.
*
- * Values starting with a digit get prefixed with the prop name since
- * CSS class names can't start with a number.
+ * Keeping the axis name in the selector prevents collisions between equal
+ * values on different props, such as Grid's `align="center"` and
+ * `justify="center"`.
*
- * Bare state names (no colon) are used directly as class names.
- * This supports state-based theming targets like 'checked', 'disabled',
- * 'selected' documented in the Theming Infrastructure wiki.
+ * <!-- SYNC: packages/core/src/utils/themeProps.ts -->
*
* @example
* ```ts
* parseStyleKey('base') // ''
- * parseStyleKey('checked') // '.checked'
- * parseStyleKey('checked+disabled') // '.checked.disabled'
- * parseStyleKey('variant:secondary') // '.secondary'
- * parseStyleKey('level:1') // '.level-1'
- * parseStyleKey('variant:destructive+size:sm') // '.destructive.sm'
+ * parseStyleKey('checked') // '[data-checked="checked"]'
+ * parseStyleKey('checked+disabled') // '[data-checked="checked"][data-disabled="disabled"]'
+ * parseStyleKey('variant:secondary') // '[data-variant="secondary"]'
+ * parseStyleKey('level:1') // '[data-level="1"]'
+ * parseStyleKey('variant:destructive+size:sm') // '[data-variant="destructive"][data-size="sm"]'
* ```
*/
export function parseStyleKey(key: string): string {
@@ -39,16 +55,10 @@ export function parseStyleKey(key: string): string {
return key
.split('+')
.map(part => {
- const [prop, value] = part.split(':');
- // Bare state name (no colon) — e.g. 'checked', 'disabled', 'selected'
- if (value === undefined) {
- return `.${prop}`;
- }
- // CSS classes can't start with a digit — prefix with prop name
- if (/^\d/.test(value)) {
- return `.${prop}-${value}`;
- }
- return `.${value}`;
+ const separator = part.indexOf(':');
+ const prop = separator === -1 ? part : part.slice(0, separator);
+ const value = separator === -1 ? part : part.slice(separator + 1);
+ return `[${themeDataAttributeName(prop)}="${escapeAttributeValue(value)}"]`;
})
.join('');
}
diff --git a/packages/core/src/utils/themeProps.test.ts b/packages/core/src/utils/themeProps.test.ts
index 5196d8c3c5..d288d9183c 100644
--- a/packages/core/src/utils/themeProps.test.ts
+++ b/packages/core/src/utils/themeProps.test.ts
@@ -4,36 +4,23 @@ import {describe, it, expect} from 'vitest';
import {themeDataAttributes, themeProps} from './themeProps';
describe('themeProps', () => {
- it('returns base class for component', () => {
+ it('returns the stable target class for a component', () => {
expect(themeProps('card').className).toBe('astryx-card');
});
- it('adds variant classes', () => {
+ it('does not emit bare prop-value classes', () => {
expect(
themeProps('button', {variant: 'secondary', size: 'sm'}).className,
- ).toBe('astryx-button secondary sm');
+ ).toBe('astryx-button');
+ expect(themeProps('heading', {level: 1}).className).toBe('astryx-heading');
});
- it('prefixes numeric values with prop name', () => {
- expect(themeProps('heading', {level: 1}).className).toBe(
- 'astryx-heading level-1',
- );
- });
-
- it('skips null and undefined props', () => {
+ it('continues to emit deprecated target-name aliases when requested', () => {
expect(
- themeProps('button', {variant: 'primary', size: undefined}).className,
- ).toBe('astryx-button primary');
- });
-
- it('works with no props', () => {
- expect(themeProps('divider').className).toBe('astryx-divider');
- });
-
- it('handles string numeric values', () => {
- expect(themeProps('heading', {level: '3'}).className).toBe(
- 'astryx-heading level-3',
- );
+ themeProps('progress-bar', undefined, {
+ legacyNames: ['progressbar'],
+ }).className,
+ ).toBe('astryx-progress-bar astryx-progressbar');
});
it('reflects visual props as data attributes', () => {
@@ -58,9 +45,9 @@ describe('themeProps', () => {
});
});
- it('returns class and data attributes together', () => {
+ it('returns the target class and data attributes together', () => {
expect(themeProps('button', {variant: 'primary', size: 'sm'})).toEqual({
- className: 'astryx-button primary sm',
+ className: 'astryx-button',
'data-variant': 'primary',
'data-size': 'sm',
});
diff --git a/packages/core/src/utils/themeProps.ts b/packages/core/src/utils/themeProps.ts
index d5e01f579b..423f542b2d 100644
--- a/packages/core/src/utils/themeProps.ts
+++ b/packages/core/src/utils/themeProps.ts
@@ -7,23 +7,17 @@ export type ClassProps = Record<string, ClassValue>;
export type ThemeDataAttributes = Record<`data-${string}`, string | undefined>;
export type ThemeProps = {className: string} & ThemeDataAttributes;
-function toDataAttributeName(prop: string): `data-${string}` {
+export function themeDataAttributeName(prop: string): `data-${string}` {
return `data-${prop.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase()}`;
}
-function classTokenForPropValue(prop: string, value: string): string {
- // CSS classes can't start with a digit — prefix with prop name.
- return /^\d/.test(value) ? `${prop}-${value}` : value;
-}
-
/**
- * Build the astryx-* class name string for a component.
+ * Build the stable astryx-* class name string for a component.
*
- * Every component renders a stable base class (`astryx-button`, `astryx-card`,
- * etc.) plus variant classes derived from visual props. Components also reflect
- * those visual props as data attributes via `themeProps()` (`data-variant`,
- * `data-size`, `data-level`, etc.) so consumers target stable data-attribute
- * selectors rather than collision-prone bare class names.
+ * Every component renders one stable target class (`astryx-button`,
+ * `astryx-card`, etc.). Visual props and runtime states are reflected only as
+ * data attributes (`data-variant`, `data-size`, `data-selected`, etc.), which
+ * preserve the axis name and cannot collide when two axes share a value.
*
* The `astryx-` prefix comes from the centralized naming module
* (`packages/core/src/naming.ts`) so the namespace lives in one place.
@@ -31,39 +25,11 @@ function classTokenForPropValue(prop: string, value: string): string {
* <!-- SYNC: packages/core/src/naming.ts (namespace prefix source of truth) -->
* <!-- SYNC: packages/core/src/utils/parseStyleKey.ts -->
*
- * Values starting with a digit get prefixed with the prop name since
- * CSS class names can't start with a number (e.g. level=1 → "level-1").
- * Data attributes keep the literal value (e.g. `data-level="1"`).
- *
* @param component - Component name in lowercase (e.g. 'button', 'card')
- * @param props - Visual prop values to include as variant classes
- * @returns Class name string (e.g. "astryx-button secondary sm")
- *
- * @example
- * ```ts
- * buildClassName('button', { variant: 'secondary', size: 'sm' })
- * // → "astryx-button secondary sm"
- *
- * buildClassName('heading', { level: 1 })
- * // → "astryx-heading level-1"
- *
- * buildClassName('card')
- * // → "astryx-card"
- * ```
+ * @returns Stable class name (e.g. "astryx-button")
*/
-function buildClassName(component: string, props?: ClassProps): string {
- const classes = [stableClassName(component)];
-
- if (props) {
- for (const [prop, value] of Object.entries(props)) {
- if (value == null) {
- continue;
- }
- classes.push(classTokenForPropValue(prop, String(value)));
- }
- }
-
- return classes.join(' ');
+function buildClassName(component: string): string {
+ return stableClassName(component);
}
/**
@@ -81,7 +47,7 @@ export function themeDataAttributes(props?: ClassProps): ThemeDataAttributes {
if (value == null) {
continue;
}
- attrs[toDataAttributeName(prop)] = String(value);
+ attrs[themeDataAttributeName(prop)] = String(value);
}
}
@@ -92,12 +58,12 @@ export function themeDataAttributes(props?: ClassProps): ThemeDataAttributes {
* Build the props object components should spread onto the same element that
* receives the stable Astryx class name.
*
- * This emits the stable astryx class plus the data-attribute reflection
- * surface. For example:
+ * This emits one stable astryx target class plus data-attribute reflection for
+ * visual props and runtime states. For example:
*
* ```ts
* themeProps('button', { variant: 'primary', size: 'sm' })
- * // → { className: 'astryx-button primary sm', data-variant: 'primary', data-size: 'sm' }
+ * // → { className: 'astryx-button', data-variant: 'primary', data-size: 'sm' }
* ```
*/
/**
@@ -125,7 +91,7 @@ export function themeProps(
props?: ClassProps,
options?: ThemePropsOptions,
): ThemeProps {
- const className = buildClassName(component, props);
+ const className = buildClassName(component);
const legacy = options?.legacyNames?.map(name => stableClassName(name)) ?? [];
return {
diff --git a/packages/lab/src/ListInput/ListInput.test.tsx b/packages/lab/src/ListInput/ListInput.test.tsx
index 4eafdc88ca..e0df60e137 100644
--- a/packages/lab/src/ListInput/ListInput.test.tsx
+++ b/packages/lab/src/ListInput/ListInput.test.tsx
@@ -240,7 +240,7 @@ describe('ListInput', () => {
'.astryx-empty-state',
);
expect(emptyState).toBeInTheDocument();
- expect(emptyState).toHaveClass('astryx-empty-state', 'compact');
+ expect(emptyState).toHaveClass('astryx-empty-state');
expect(emptyState).toHaveAttribute('data-variant', 'compact');
expect(getComputedStyle(emptyState!).alignItems).toBe('center');
expect(getComputedStyle(emptyState!).justifyContent).toBe('center');
diff --git a/packages/themes/probe/src/probeTheme.test.ts b/packages/themes/probe/src/probeTheme.test.ts
new file mode 100644
index 0000000000..eda1da0eeb
--- /dev/null
+++ b/packages/themes/probe/src/probeTheme.test.ts
@@ -0,0 +1,17 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, expect, it} from 'vitest';
+import {generateThemeCSS} from '@astryxdesign/core/theme';
+import {probeTheme} from './probeTheme';
+
+const BARE_VALUE_SELECTOR =
+ /\.astryx-[a-z0-9-]+\.(?:-?[_a-zA-Z][_a-zA-Z0-9-]*)/;
+
+describe('probe theme selector contract', () => {
+ it('emits reflected data attributes, never target-plus-bare-value selectors', () => {
+ const css = generateThemeCSS(probeTheme).component;
+
+ expect(css).toContain('[data-');
+ expect(css).not.toMatch(BARE_VALUE_SELECTOR);
+ });
+});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 4a57f45f40..ea50dd7e4e 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -659,6 +659,12 @@ importers:
jscodeshift:
specifier: ^17.3.0
version: 17.3.0
+ postcss:
+ specifier: ^8.5.23
+ version: 8.5.25
+ postcss-selector-parser:
+ specifier: ^7.1.5
+ version: 7.1.5
zod:
specifier: ^4.4.3
version: 4.4.3
@@ -4146,6 +4152,11 @@ packages:
resolution: {integrity: sha512-YUifsXXuknHlUsmlgyY0PKzgPOr7/FjCePfHNt0jxm83wHZi44VDMQ7/fGNkjY3/jV1MC+1CmZbaHzugyeRtpg==}
+ resolution: {integrity: sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==}
+ engines: {node: '>=4'}
+ hasBin: true
+
resolution: {integrity: sha512-7D2EPVltRrsTkhpQmksIu+LxeWAIEk6wRDMJ1qljlv+CKHJM+cJLlfhWIzNA44eAsHXSNe3+vO6DW1yCYx8SuQ==}
engines: {node: '>=20'}
@@ -5432,6 +5443,10 @@ packages:
yaml:
optional: true
+ resolution: {integrity: sha512-KvvtD7SrlBP7dlgkBghEE3r84CABm5SmV2aNcG4oCA+qDnJ/tvKonFVvwWAyyWUEwxuNawdfEAZKP9zM3oZ2Uw==}
+ engines: {node: '>=4'}
+
resolution: {integrity: sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==}
@@ -6098,6 +6113,9 @@ packages:
peerDependencies:
react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
+ resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==}
+
resolution: {integrity: sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==}
engines: {node: '>= 0.8'}
@@ -9461,6 +9479,8 @@ snapshots:
+
dependencies:
'@asamuzakjp/css-color': 4.1.2
@@ -10790,6 +10810,11 @@ snapshots:
tsx: 4.23.0
yaml: 2.9.0
+ dependencies:
+ cssesc: 3.0.0
+ util-deprecate: 1.0.2
+
@@ -11490,6 +11515,8 @@ snapshots:
dependencies:
react: 19.2.7
+