Skip to content

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

TypeScript

feat(theme): add themeable indicators (#4712)

Cindy Zhang505ccaa32701
diff --git a/.changeset/themeable-indicators.md b/.changeset/themeable-indicators.md
new file mode 100644
index 0000000000..01ec948663
--- /dev/null
+++ b/.changeset/themeable-indicators.md
@@ -0,0 +1,12 @@
+---
+'@astryxdesign/core': patch
+'@astryxdesign/cli': patch
+---
+
+[feature] Add themeable indicators — the componentized check, checkbox, and radio visuals. `defineTheme({indicators: {check: RadioIndicator}})` replaces one by name, and every component drawing it follows.
+
+Theme targets now follow the component-name convention: `checkbox-indicator`, `radio-indicator`, `radio-indicator-dot`. The old names (`checkbox`, `radio`, `radio-dot`) are still emitted on the same element, so existing themes keep working — migrate at your convenience; they go away in the next major.
+
+Migration: menu radios use those shared targets now. `dropdown-menu-radio-dot` is removed — target `radio-indicator-dot`.
+
+@cixzhang
diff --git a/apps/storybook/stories/CheckboxInput.stories.tsx b/apps/storybook/stories/CheckboxInput.stories.tsx
index 3763cded3b..fa2fff2a71 100644
--- a/apps/storybook/stories/CheckboxInput.stories.tsx
+++ b/apps/storybook/stories/CheckboxInput.stories.tsx
@@ -3,6 +3,7 @@
import {useState} from 'react';
import type {Meta, StoryObj} from '@storybook/react';
import {CheckboxInput} from '@astryxdesign/core/CheckboxInput';
+import {Theme, defineTheme} from '@astryxdesign/core/theme';
import {
BellIcon,
EnvelopeIcon,
@@ -494,3 +495,72 @@ export const DisabledWithMessage: Story = {
disabledMessage: 'Terms are managed by your administrator',
},
};
+
+// A theme can replace the checkbox visual outright: the indicator receives the
+// state, the CheckboxInput keeps the input, label, focus, and disabled
+// behavior. Hover and focus reach the indicator through the row's ancestor
+// marker, so a replacement never needs interaction props.
+const brandIndicatorTheme = defineTheme({
+ name: 'checkbox-indicator-demo',
+ indicators: {
+ checkbox: ({state, size, isDisabled}) => (
+ <span
+ aria-hidden="true"
+ style={{
+ display: 'inline-flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ width: size === 'sm' ? 20 : 24,
+ height: size === 'sm' ? 20 : 24,
+ border: '1px solid currentColor',
+ borderRadius: 6,
+ color: '#7c3aed',
+ opacity: isDisabled ? 0.5 : 1,
+ }}>
+ {state === 'checked' ? '★' : state === 'indeterminate' ? '–' : ''}
+ </span>
+ ),
+ },
+});
+
+export const ThemedIndicator: Story = {
+ render: () => (
+ <Theme theme={brandIndicatorTheme} mode="light">
+ <div style={{display: 'grid', gap: 12}}>
+ <CheckboxInput label="Custom checked glyph" value={true} />
+ <CheckboxInput
+ label="Custom indeterminate glyph"
+ value="indeterminate"
+ />
+ <CheckboxInput label="Unchecked" value={false} />
+ <CheckboxInput label="Disabled" value={true} isDisabled />
+ </div>
+ </Theme>
+ ),
+};
+
+// Restyling without replacing: the indicator renders the `checkbox` theme
+// target, so ordinary component overrides reach it.
+const roundCheckboxTheme = defineTheme({
+ name: 'checkbox-round-demo',
+ components: {
+ checkbox: {
+ base: {borderRadius: 'var(--radius-full)'},
+ checked: {
+ backgroundColor: 'var(--color-positive)',
+ borderColor: 'var(--color-positive)',
+ },
+ },
+ },
+});
+
+export const ThemedCheckboxTarget: Story = {
+ render: () => (
+ <Theme theme={roundCheckboxTheme} mode="light">
+ <div style={{display: 'grid', gap: 12}}>
+ <CheckboxInput label="Round, positive when checked" value={true} />
+ <CheckboxInput label="Unchecked" value={false} />
+ </div>
+ </Theme>
+ ),
+};
diff --git a/apps/storybook/stories/Selector.stories.tsx b/apps/storybook/stories/Selector.stories.tsx
index 53a6e8a8e8..b86630df58 100644
--- a/apps/storybook/stories/Selector.stories.tsx
+++ b/apps/storybook/stories/Selector.stories.tsx
@@ -5,6 +5,7 @@ import {useState} from 'react';
import {Button} from '@astryxdesign/core/Button';
import {Selector, SelectorOption} from '@astryxdesign/core/Selector';
import {Theme, defineTheme} from '@astryxdesign/core/theme';
+import {RadioIndicator} from '@astryxdesign/core/Indicator';
import {UserIcon, CogIcon, BellIcon} from '@heroicons/react/24/outline';
const meta: Meta<typeof Selector> = {
@@ -837,3 +838,55 @@ export const ThemedIcons: Story = {
);
},
};
+
+/**
+ * Swap the single-selection indicator for a radio.
+ *
+ * `check` is the indicator every single-selection mark draws, so replacing it
+ * once in the theme reaches this Selector — and any other component that marks
+ * "this one is chosen" — without touching a call site.
+ *
+ * Note what the default check could never do: an unselected row draws an
+ * **empty circle**. The mark is rendered in every state and told which state to
+ * draw, so an indicator that has an unselected form can show it.
+ */
+const radioSelectionTheme = defineTheme({
+ name: 'radio-selection-demo',
+ indicators: {check: RadioIndicator},
+});
+
+export const RadioSelectionIndicator: Story = {
+ render: () => {
+ const [value, setValue] = useState<string | undefined>('Banana');
+ return (
+ <Theme theme={radioSelectionTheme} mode="light">
+ <Selector
+ label="Single selection drawn as a radio"
+ options={['Apple', 'Banana', 'Cherry']}
+ value={value}
+ onChange={setValue}
+ isDefaultOpen
+ />
+ </Theme>
+ );
+ },
+};
+
+/**
+ * The same Selector with no theme, for comparison: a checkmark on the selected
+ * row, and nothing at all on the others.
+ */
+export const DefaultSelectionIndicator: Story = {
+ render: () => {
+ const [value, setValue] = useState<string | undefined>('Banana');
+ return (
+ <Selector
+ label="Single selection drawn as a check (default)"
+ options={['Apple', 'Banana', 'Cherry']}
+ value={value}
+ onChange={setValue}
+ isDefaultOpen
+ />
+ );
+ },
+};
diff --git a/packages/cli/authoring/doctypes/base/type.ts b/packages/cli/authoring/doctypes/base/type.ts
index bb909f0e64..93a151c097 100644
--- a/packages/cli/authoring/doctypes/base/type.ts
+++ b/packages/cli/authoring/doctypes/base/type.ts
@@ -310,6 +310,15 @@ export interface ComponentThemingTarget {
* `[data-checked="checked"]`. Legacy state classes are still emitted for
* compatibility. 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`),
+ * so existing themes keep working, but the docsite should steer readers to
+ * the replacement. The value is the class name that supersedes this one,
+ * without the `astryx-` prefix — e.g. `"checkbox-indicator"`.
+ *
+ * A theme target is public API; renaming one without this is a silent
+ * break for every theme styling it. */
+ deprecatedFor?: string;
}
/**
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 221b4e37c5..a819d06a9b 100644
--- a/packages/cli/clients/cli/commands/build-theme.registry.test.mjs
+++ b/packages/cli/clients/cli/commands/build-theme.registry.test.mjs
@@ -74,6 +74,16 @@ function renderedClassLiterals() {
classes.add(m[1]);
}
}
+ // Renamed targets emit their old name too, via themeProps'
+ // `legacyNames`. Those classes are just as rendered as the primary
+ // one, so a doc entry for the old name is still backed by real output.
+ const legacyRe = /legacyNames:\s*\[([^\]]*)\]/g;
+ let lm;
+ while ((lm = legacyRe.exec(text)) !== null) {
+ for (const nm of lm[1].matchAll(/'([^']+)'/g)) {
+ classes.add(nm[1]);
+ }
+ }
}
}
};
diff --git a/packages/core/package.json b/packages/core/package.json
index 08dfe1b07f..a19f80a166 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -297,6 +297,11 @@
"types": "./dist/IconButton/index.d.ts",
"default": "./dist/IconButton/index.js"
},
+ "./Indicator": {
+ "source": "./src/Indicator/index.ts",
+ "types": "./dist/Indicator/index.d.ts",
+ "default": "./dist/Indicator/index.js"
+ },
"./InputGroup": {
"source": "./src/InputGroup/index.ts",
"types": "./dist/InputGroup/index.d.ts",
diff --git a/packages/core/src/CheckboxInput/CheckboxInput.doc.mjs b/packages/core/src/CheckboxInput/CheckboxInput.doc.mjs
index 7d90a67b81..d7ae6c3fcc 100644
--- a/packages/core/src/CheckboxInput/CheckboxInput.doc.mjs
+++ b/packages/core/src/CheckboxInput/CheckboxInput.doc.mjs
@@ -131,7 +131,8 @@ export const docs = {
theming: {
targets: [
{className: 'astryx-checkbox-input', visualProps: ['size']},
- {className: 'astryx-checkbox', visualProps: ['size'], states: ['checked', 'disabled']},
+ {className: 'astryx-checkbox-indicator', visualProps: ['size'], states: ['checked', 'disabled']},
+ {className: 'astryx-checkbox', visualProps: ['size'], states: ['checked', 'disabled'], deprecatedFor: 'checkbox-indicator'},
],
},
usage: {
@@ -206,7 +207,8 @@ export const docsZh = {
'size',
],
},
- {className: 'astryx-checkbox', visualProps: ['size'], states: ['checked', 'disabled']},
+ {className: 'astryx-checkbox-indicator', visualProps: ['size'], states: ['checked', 'disabled']},
+ {className: 'astryx-checkbox', visualProps: ['size'], states: ['checked', 'disabled'], deprecatedFor: 'checkbox-indicator'},
],
},
};
diff --git a/packages/core/src/CheckboxInput/CheckboxInput.test.tsx b/packages/core/src/CheckboxInput/CheckboxInput.test.tsx
index 9f511cf611..1b37a1c853 100644
--- a/packages/core/src/CheckboxInput/CheckboxInput.test.tsx
+++ b/packages/core/src/CheckboxInput/CheckboxInput.test.tsx
@@ -13,6 +13,8 @@ import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';
import {render, screen, fireEvent, waitFor} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {CheckboxInput} from './CheckboxInput';
+import {Theme} from '../theme/Theme';
+import {defineTheme} from '../theme/defineTheme';
import {getForcedColorsRules} from '../__tests__/forcedColors';
import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';
@@ -599,3 +601,84 @@ describe('forced colors (WCAG 1.4.11)', () => {
expect(getForcedColorsRules()).toContain('color: canvastext;');
});
});
+
+// The control's native input is `opacity: 0`, so the visible focus indicator
+// has to land on the indicator beside it — which is themeable, third-party
+// code. If drawing the ring were the indicator's job, a replacement that
+// simply doesn't would ship a control with no visible focus (WCAG 2.4.7), and
+// that is the default: our own sample replacement destructures
+// {state, size, isDisabled} and drops the rest.
+//
+// So the owner paints it, on the indicator's own element, at focus time. The
+// shape is right because `outline` follows that element's border-radius, and
+// no cooperation is required.
+describe('focus ring ownership (WCAG 2.4.7)', () => {
+ /** What a theme author plausibly writes: state in, picture out. */
+ const BareIndicator = ({state}: {state: string}) => (
+ <span aria-hidden="true" data-testid="bare-indicator">
+ {state === 'checked' ? 'x' : ''}
+ </span>
+ );
+
+ const bareTheme = defineTheme({
+ name: 'bare-indicator-theme',
+ indicators: {checkbox: BareIndicator},
+ });
+
+ /**
+ * The element the ring is painted on: the indicator slot's only child — the
+ * indicator's own root, whatever a theme renders there.
+ */
+ const indicatorOf = (container: HTMLElement) => {
+ const input = container.querySelector('input[type="checkbox"]');
+ const slot = input?.nextElementSibling;
+ return slot?.firstElementChild as HTMLElement;
+ };
+
+ const focusInput = (container: HTMLElement) => {
+ const input = container.querySelector(
+ 'input[type="checkbox"]',
+ ) as HTMLInputElement;
+ // A keydown first, so jsdom's :focus-visible heuristic sees keyboard
+ // modality — the ring is deliberately keyboard-only, and a bare
+ // fireEvent.focus() reads as a pointer focus. Same approach as the
+ // TreeList focus test.
+ fireEvent.keyDown(document.body, {key: 'Tab'});
+ input.focus();
+ fireEvent.focus(input);
+ return input;
+ };
+
+ it('paints the ring on the built-in indicator', () => {
+ const {container} = render(
+ <CheckboxInput label="Accept" value={false} onChange={() => {}} />,
+ );
+ focusInput(container);
+ expect(indicatorOf(container).style.outlineStyle).toBe('solid');
+ });
+
+ it('paints it on a replacement that forwards nothing', () => {
+ const {container} = render(
+ <Theme theme={bareTheme}>
+ <CheckboxInput label="Accept" value={false} onChange={() => {}} />
+ </Theme>,
+ );
+
+ // The replacement really took effect, and really is bare.
+ const replaced = screen.getByTestId('bare-indicator');
+ expect(replaced.className).toBe('');
+ // ...and it still gets a ring, because the owner drew it.
+ focusInput(container);
+ expect(replaced.style.outlineStyle).toBe('solid');
+ });
+
+ it('clears the ring on blur', () => {
+ const {container} = render(
+ <CheckboxInput label="Accept" value={false} onChange={() => {}} />,
+ );
+ const input = focusInput(container);
+ expect(indicatorOf(container).style.outlineStyle).toBe('solid');
+ fireEvent.blur(input);
+ expect(indicatorOf(container).style.outlineStyle).toBe('');
+ });
+});
diff --git a/packages/core/src/CheckboxInput/CheckboxInput.tsx b/packages/core/src/CheckboxInput/CheckboxInput.tsx
index 696c0f6862..13edf980d3 100644
--- a/packages/core/src/CheckboxInput/CheckboxInput.tsx
+++ b/packages/core/src/CheckboxInput/CheckboxInput.tsx
@@ -21,6 +21,7 @@ import {
useCallback,
use,
useOptimistic,
+ useRef,
useTransition,
type ChangeEvent,
type FocusEvent,
@@ -31,12 +32,9 @@ import {
colorVars,
spacingVars,
radiusVars,
- durationVars,
- easeVars,
typographyVars,
typeScaleVars,
fontWeightVars,
- borderVars,
} from '../theme/tokens.stylex';
import type {BaseProps} from '../BaseProps';
import type {SizeValue} from '../utils/types';
@@ -47,7 +45,9 @@ import type {InputStatus} from '../Field/types';
import {Spinner} from '../Spinner';
import {useTooltip} from '../Tooltip';
import {mergeProps, mergeRefs} from '../utils';
-import {checkboxScope} from './checkbox.markers.stylex';
+import {indicatorScope} from '../Indicator/indicator.markers.stylex';
+import {useIndicatorFocusRing} from '../hooks/useIndicatorFocusRing';
+import {useIndicator} from '../Indicator';
import {themeProps} from '../utils/themeProps';
import {CheckboxListContext} from '../CheckboxList/CheckboxListContext';
@@ -68,6 +68,12 @@ const styles = stylex.create({
flexShrink: 0,
isolation: 'isolate',
},
+ // Holds only the indicator, so the focus ring has one unambiguous target.
+ // `display: contents` adds no box of its own — the indicator keeps whatever
+ // layout relationship it already had with the wrapper.
+ indicatorSlot: {
+ display: 'contents',
+ },
input: {
position: 'absolute',
margin: 0,
@@ -79,113 +85,6 @@ const styles = stylex.create({
inputDisabled: {
cursor: 'not-allowed',
},
- checkbox: {
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- borderWidth: borderVars['--border-width'],
- borderStyle: 'solid',
- borderRadius: radiusVars['--radius-inner'],
- transitionProperty: 'background-color, border-color',
- transitionDuration: {
- default: durationVars['--duration-fast'],
- '@media (prefers-reduced-motion: reduce)': '0s',
- },
- transitionTimingFunction: easeVars['--ease-standard'],
- },
- checkboxFocus: {
- outline: {
- default: 'none',
- [stylex.when.ancestor(':has(:focus-visible)', checkboxScope)]:
- `2px solid ${colorVars['--color-accent']}`,
- },
- outlineOffset: {
- default: null,
- [stylex.when.ancestor(':has(:focus-visible)', checkboxScope)]: '2px',
- },
- },
- // State-dependent colors with ancestor hover behavior
- checkboxUnchecked: {
- // Foreground for the inherit-shade loading spinner (reads currentColor):
- // brand accent on the light surface fill.
- color: colorVars['--color-accent'],
- borderColor: {
- default: colorVars['--color-border-emphasized'],
- [stylex.when.ancestor(':hover', checkboxScope)]: {
- '@media (hover: hover)': `color-mix(in srgb, ${colorVars['--color-border-emphasized']}, ${colorVars['--color-tint-hover']} 20%)`,
- },
- },
- backgroundColor: {
- default: colorVars['--color-background-surface'],
- [stylex.when.ancestor(':hover', checkboxScope)]: {
- '@media (hover: hover)': `color-mix(in srgb, ${colorVars['--color-background-surface']}, ${colorVars['--color-tint-hover']} 5%)`,
- },
- },
- },
- checkboxChecked: {
- // Foreground for the inherit-shade loading spinner (reads currentColor):
- // on-accent color against the accent fill.
- color: colorVars['--color-on-accent'],
- borderColor: {
- default: colorVars['--color-accent'],
- [stylex.when.ancestor(':hover', checkboxScope)]: {
- '@media (hover: hover)': `color-mix(in srgb, ${colorVars['--color-accent']}, ${colorVars['--color-tint-hover']} 15%)`,
- },
- },
- backgroundColor: {
- default: colorVars['--color-accent'],
- [stylex.when.ancestor(':hover', checkboxScope)]: {
- '@media (hover: hover)': `color-mix(in srgb, ${colorVars['--color-accent']}, ${colorVars['--color-tint-hover']} 15%)`,
- },
- },
- },
- checkboxDisabled: {
- opacity: 0.5,
- borderColor: {
- default: colorVars['--color-border'],
- [stylex.when.ancestor(':hover', checkboxScope)]: {
- '@media (hover: hover)': colorVars['--color-border'],
- },
- },
- },
- checkboxDisabledUnchecked: {
- backgroundColor: {
- default: colorVars['--color-background-muted'],
- [stylex.when.ancestor(':hover', checkboxScope)]: {
- '@media (hover: hover)': colorVars['--color-background-muted'],
- },
- },
- },
- checkmark: {
- display: 'none',
- color: {
- default: colorVars['--color-on-accent'],
- // Forced colors (Windows High Contrast) does not reliably force an SVG
- // stroke painted with currentColor, so the check stays the same white as
- // the flattened (Canvas) box fill — a white check on a white box.
- // CanvasText keeps it perceivable on the Canvas box, matching the
- // indeterminate mark (WCAG 1.4.11).
- '@media (forced-colors: active)': 'CanvasText',
- },
- },
- checkmarkVisible: {
- display: 'block',
- },
- indeterminateMark: {
- display: 'none',
- backgroundColor: {
- default: colorVars['--color-on-accent'],
- // Forced colors (Windows High Contrast) strips painted backgrounds,
- // which would make the indeterminate bar invisible; CanvasText keeps it
- // perceivable on the Canvas box fill (WCAG 1.4.11). The checkmark carries
- // the matching CanvasText treatment on its own style.
- '@media (forced-colors: active)': 'CanvasText',
- },
- borderRadius: radiusVars['--radius-full'],
- },
- indeterminateMarkVisible: {
- display: 'block',
- },
labelWrapper: {
display: 'flex',
flexDirection: 'column',
@@ -211,39 +110,6 @@ const wrapperSizeStyles = stylex.create({
},
});
-const checkboxSizeStyles = stylex.create({
- sm: {
- width: 20,
- height: 20,
- },
- md: {
- width: 24,
- height: 24,
- },
-});
-
-const checkmarkSizeStyles = stylex.create({
- sm: {
- width: 12,
- height: 12,
- },
- md: {
- width: 14,
- height: 14,
- },
-});
-
-const indeterminateSizeStyles = stylex.create({
- sm: {
- width: 10,
- height: 2,
- },
- md: {
- width: 12,
- height: 2,
- },
-});
-
export type CheckboxInputSize = keyof typeof wrapperSizeStyles;
export interface CheckboxInputProps extends Omit<BaseProps, 'onChange'> {
@@ -443,9 +309,17 @@ export function CheckboxInput({
isEnabled: showsDisabledMessage,
});
+ // The checkbox visual is an indicator: a theme can restyle it through the
+ // `checkbox` target or replace the component outright.
+ const CheckboxControl = useIndicator('checkbox');
+ // The ring is drawn on the indicator itself: the native input is
+ // `opacity: 0`, and only the indicator's own element can shape the outline
+ // to match it. See useIndicatorFocusRing.
+ const indicatorRef = useRef<HTMLSpanElement>(null);
+ const {focusProps} = useIndicatorFocusRing(indicatorRef, isDisabled);
+
const isIndeterminate = optimisticValue === 'indeterminate';
const isChecked = optimisticValue === true;
- const isCheckedOrIndeterminate = isChecked || isIndeterminate;
// Sync the native indeterminate DOM property (can't be set via JSX
// attribute). On a native checkbox this is the authoritative way to expose
@@ -498,9 +372,13 @@ export function CheckboxInput({
{...stylex.props(
styles.container,
isLabelHidden && styles.containerLabelHidden,
- !isDisabled && checkboxScope,
+ // Hover and focus reach the checkbox visual through this ancestor
+ // marker rather than props, so the whole row drives it.
+ !isDisabled && indicatorScope,
)}>
- <div {...stylex.props(styles.checkboxWrapper, wrapperSizeStyles[size])}>
+ <div
+ {...stylex.props(styles.checkboxWrapper, wrapperSizeStyles[size])}
+ {...focusProps}>
<input
{...rest}
ref={mergeRefs(
@@ -547,61 +425,25 @@ export function CheckboxInput({
isDisabled && styles.inputDisabled,
)}
/>
- <div
- aria-hidden="true"
- {...mergeProps(
- themeProps('checkbox', {
- size,
- checked: isChecked
- ? 'checked'
- : isIndeterminate
- ? 'indeterminate'
- : null,
- disabled: isDisabled ? 'disabled' : null,
- }),
- stylex.props(
- styles.checkbox,
- checkboxSizeStyles[size],
- !isDisabled && styles.checkboxFocus,
- isCheckedOrIndeterminate
- ? styles.checkboxChecked
- : styles.checkboxUnchecked,
- isDisabled && styles.checkboxDisabled,
- isDisabled &&
- !isCheckedOrIndeterminate &&
- styles.checkboxDisabledUnchecked,
- ),
- )}>
- {isBusy ? (
- <Spinner size="sm" shade="inherit" />
- ) : (
- <>
- <svg
- viewBox="0 0 10 10"
- {...stylex.props(
- styles.checkmark,
- checkmarkSizeStyles[size],
- isChecked && styles.checkmarkVisible,
- )}>
- <path
- d="M8.5 2.5L4 7.5L1.5 5"
- stroke="currentColor"
- strokeWidth="1.5"
- fill="none"
- strokeLinecap="round"
- strokeLinejoin="round"
- />
- </svg>
- <div
- {...stylex.props(
- styles.indeterminateMark,
- indeterminateSizeStyles[size],
- isIndeterminate && styles.indeterminateMarkVisible,
- )}
- />
- </>
- )}
- </div>
+ {/*
+ * A container holding ONLY the indicator, so the focus ring has an
+ * unambiguous target whatever a theme renders. `display: contents`
+ * keeps it out of layout entirely.
+ */}
+ <span ref={indicatorRef} {...stylex.props(styles.indicatorSlot)}>
+ <CheckboxControl
+ state={
+ isIndeterminate
+ ? 'indeterminate'
+ : isChecked
+ ? 'checked'
+ : 'unchecked'
+ }
+ size={size}
+ isDisabled={isDisabled}>
+ {isBusy ? <Spinner size="sm" shade="inherit" /> : null}
+ </CheckboxControl>
+ </span>
</div>
<div {...stylex.props(styles.labelWrapper)}>
<FieldLabel
diff --git a/packages/core/src/CheckboxInput/checkbox.markers.stylex.ts b/packages/core/src/CheckboxInput/checkbox.markers.stylex.ts
deleted file mode 100644
index 1e4257f8b7..0000000000
--- a/packages/core/src/CheckboxInput/checkbox.markers.stylex.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-import * as stylex from '@stylexjs/stylex';
-
-/**
- * Scoped marker for CheckboxInput ancestor selectors.
- * Prevents focus-within and hover styles from leaking when
- * checkboxes are placed inside Popovers or other containers
- * that also have focus-within state.
- */
-export const checkboxScope: ReturnType<typeof stylex.defineMarker> =
- stylex.defineMarker();
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs b/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs
index 8f57632c38..e4f5b3c2be 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs
+++ b/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs
@@ -30,11 +30,6 @@ export const docs = {
visualProps: ['size'],
states: ['checked', 'disabled'],
},
- {
- className: 'astryx-dropdown-menu-radio-dot',
- visualProps: ['size'],
- states: ['checked', 'disabled'],
- },
{className: 'astryx-dropdown-menu-section-heading'},
{className: 'astryx-dropdown-menu-divider'},
{className: 'astryx-dropdown-menu-indicator-icon'},
diff --git a/packages/core/src/DropdownMenu/DropdownMenuCheckboxItem.tsx b/packages/core/src/DropdownMenu/DropdownMenuCheckboxItem.tsx
index fe24bbd571..fa481c0489 100644
--- a/packages/core/src/DropdownMenu/DropdownMenuCheckboxItem.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenuCheckboxItem.tsx
@@ -15,24 +15,21 @@
* Enter/Space activation come from the parent DropdownMenu's useListFocus +
* activation path, which matches menuitemcheckbox alongside plain menuitem rows.
*
- * The checkbox visual composes the real CheckboxInput primitive so its checkmark
- * matches CheckboxListItem and picks up the standard `checkbox` theming slots.
- * It is purely decorative: the composed control is wrapped in an element that is
- * both `aria-hidden` and `inert`, so it contributes nothing to the row's
- * accessible name, and its native <input> and sr-only label stay out of the tab
- * order and the accessibility tree while pointer clicks fall through to the row
- * — the same shim MultiSelector uses. The row owns the checked state and
- * accessible name. The control size is derived from the menu's item size (a
- * `sm` menu gets the compact control; `md`/`lg` get the standard one) and it
- * swaps to the inline-end of the row on coarse-pointer (touch) devices via CSS
- * `order`, so it lands where selection toggles are conventionally placed on
+ * The checkbox visual is the shared checkbox indicator, decorative
+ * (aria-hidden) — the row owns the role, checked state, and accessible name, so
+ * there is no nested native <input> to shim out of the accessibility tree. It
+ * picks up the same `checkbox` theming (and any theme replacement) as
+ * CheckboxInput. The control size is derived from the menu's item size (a `sm`
+ * menu gets the compact control; `md`/`lg` get the standard one) and the marker
+ * box swaps to the inline-end of the row on coarse-pointer (touch) devices via
+ * CSS `order`, so it lands where selection toggles are conventionally placed on
* mobile.
*/
import {useCallback, type PointerEvent, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import {renderIconSlot, type IconType} from '../Icon';
-import {CheckboxInput} from '../CheckboxInput/CheckboxInput';
+import {useIndicator} from '../Indicator';
import {Item} from '../Item';
import {useDropdownMenuContext} from './DropdownMenuContext';
import {focusMenuItemOnHover} from './menuItemHover';
@@ -61,9 +58,10 @@ const styles = stylex.create({
// `aria-hidden` + `inert` + pointer-events:none keep the composed CheckboxInput
// decorative: it adds no accessible name, and clicks fall through to the row,
// which owns the role and activation.
- markerBox: {
- display: 'flex',
- flexShrink: 0,
+ // Placement of the marker within the row. The indicator draws its own box
+ // (size, fill, border) — these are only the rules the MENU owns: where the
+ // marker sits in the row, and that it never takes the pointer.
+ marker: {
pointerEvents: 'none',
order: {
default: 0,
@@ -76,6 +74,8 @@ const styles = stylex.create({
},
});
+// Matches the control sizes CheckboxInput uses, so a checkbox reads the same in
+// a menu row as it does in a form.
export interface DropdownMenuCheckboxItemProps extends Omit<
BaseProps,
'onChange' | 'role' | 'aria-checked' | 'tabIndex'
@@ -157,12 +157,7 @@ export function DropdownMenuCheckboxItem({
const ctx = useDropdownMenuContext();
const menuSize = ctx?.menuSize ?? 'md';
const controlSize = menuSize === 'sm' ? 'sm' : 'md';
-
- // The composed checkbox is decorative and inert, so its label never reaches
- // the accessibility tree — the row's `label` prop provides the announced
- // name. CheckboxInput still requires a string label, so pass one through when
- // the row label is a plain string.
- const checkboxLabel = typeof label === 'string' ? label : '';
+ const CheckboxControl = useIndicator('checkbox');
const handleClick = useCallback(() => {
if (isDisabled) {
@@ -187,15 +182,17 @@ export function DropdownMenuCheckboxItem({
tabIndex={isDisabled ? undefined : -1}
onPointerMove={handlePointerMove}
marker={
- <div aria-hidden="true" inert {...stylex.props(styles.markerBox)}>
- <CheckboxInput
- label={checkboxLabel}
- isLabelHidden
- value={value}
- isDisabled={isDisabled}
- size={controlSize}
- />
- </div>
+ // No wrapper, and no menu-specific theme target: the shared
+ // `astryx-checkbox` target is already on this element (main reached
+ // the menu checkbox through it too), so the menu adds only its own
+ // placement rules. A wrapper here would have duplicated the
+ // indicator's control size and moved nothing themeable.
+ <CheckboxControl
+ state={value ? 'checked' : 'unchecked'}
+ size={controlSize}
+ isDisabled={isDisabled}
+ xstyle={styles.marker}
+ />
}
startContent={
icon
diff --git a/packages/core/src/DropdownMenu/DropdownMenuRadioItem.tsx b/packages/core/src/DropdownMenu/DropdownMenuRadioItem.tsx
index ffd2ac2537..87b686c5f2 100644
--- a/packages/core/src/DropdownMenu/DropdownMenuRadioItem.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenuRadioItem.tsx
@@ -14,26 +14,21 @@
* state + onChange come from DropdownMenuRadioGroupContext. Keyboard nav +
* Enter/Space activation come from the parent DropdownMenu.
*
- * The round radio visual (circle + center dot) is decorative (aria-hidden) —
- * the row owns the checked state. Its size is derived from the menu's item size
- * and it swaps to the inline-end of the row on coarse-pointer (touch) devices
- * via CSS `order`. The dot is a shaped element, not an icon (a filled circle
- * has no registry glyph).
+ * The round radio visual is the shared radio indicator, decorative
+ * (aria-hidden) — the row owns the checked state, and menu radios pick up the
+ * same `radio` theming (and any theme replacement) as RadioList. This row keeps
+ * the marker box: its size is derived from the menu's item size and it swaps to
+ * the inline-end of the row on coarse-pointer (touch) devices via CSS `order`.
*/
import {useCallback, type PointerEvent, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import {renderIconSlot, type IconType} from '../Icon';
+import {useIndicator} from '../Indicator';
import {Item} from '../Item';
import {useDropdownMenuContext} from './DropdownMenuContext';
import {focusMenuItemOnHover} from './menuItemHover';
-import {
- colorVars,
- spacingVars,
- durationVars,
- easeVars,
- borderVars,
-} from '../theme/tokens.stylex';
+import {colorVars, spacingVars} from '../theme/tokens.stylex';
import {mergeProps, themeProps} from '../utils';
import type {BaseProps} from '../BaseProps';
import {useDropdownMenuRadioGroupContext} from './DropdownMenuContext';
@@ -56,21 +51,13 @@ const styles = stylex.create({
},
// Rendered in Item's `marker` slot as a raw flex child. On touch it moves to
// the inline-end of the row via `order`.
- circle: {
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- flexShrink: 0,
- boxSizing: 'border-box',
- borderWidth: borderVars['--border-width'],
- borderStyle: 'solid',
- borderRadius: '50%',
- transitionProperty: 'background-color, border-color',
- transitionDuration: {
- default: durationVars['--duration-fast'],
- '@media (prefers-reduced-motion: reduce)': '0s',
- },
- transitionTimingFunction: easeVars['--ease-standard'],
+ // Layout box for the decorative marker. The painted circle is the radio
+ // indicator inside it, which carries the shared `radio` theme target.
+ // Placement of the marker within the row. The indicator draws its own box
+ // (size, fill, border) — these are only the rules the MENU owns: where the
+ // marker sits in the row, and that it never takes the pointer.
+ marker: {
+ pointerEvents: 'none',
order: {
default: 0,
'@media (pointer: coarse)': 1,
@@ -80,30 +67,10 @@ const styles = stylex.create({
'@media (pointer: coarse)': 'auto',
},
},
- unchecked: {
- borderColor: colorVars['--color-border-emphasized'],
- backgroundColor: colorVars['--color-background-surface'],
- },
- checked: {
- borderColor: colorVars['--color-accent'],
- backgroundColor: colorVars['--color-accent'],
- },
- dot: {
- borderRadius: '50%',
- backgroundColor: colorVars['--color-on-accent'],
- },
-});
-
-const circleSizeStyles = stylex.create({
- sm: {width: 18, height: 18},
- md: {width: 22, height: 22},
-});
-
-const dotSizeStyles = stylex.create({
- sm: {width: 6, height: 6},
- md: {width: 8, height: 8},
});
+// Matches the control sizes RadioList uses, so a radio reads the same in a
+// menu row as it does in a radio group.
export interface DropdownMenuRadioItemProps extends Omit<
BaseProps,
'role' | 'aria-checked' | 'tabIndex'
@@ -173,6 +140,7 @@ export function DropdownMenuRadioItem({
const menuSize = menuCtx?.menuSize ?? 'md';
const controlSize = menuSize === 'sm' ? 'sm' : 'md';
const isChecked = groupCtx.value === value;
+ const RadioControl = useIndicator('radio');
const handleClick = useCallback(() => {
if (isDisabled) {
@@ -197,33 +165,19 @@ export function DropdownMenuRadioItem({
tabIndex={isDisabled ? undefined : -1}
onPointerMove={handlePointerMove}
marker={
- <span
- aria-hidden="true"
- {...mergeProps(
- themeProps('dropdown-menu-radio', {
- size: controlSize,
- checked: isChecked ? 'checked' : null,
- disabled: isDisabled ? 'disabled' : null,
- }),
- stylex.props(
- styles.circle,
- circleSizeStyles[controlSize],
- isChecked ? styles.checked : styles.unchecked,
- ),
- )}>
- {isChecked && (
- <span
- {...mergeProps(
- themeProps('dropdown-menu-radio-dot', {
- size: controlSize,
- checked: 'checked',
- disabled: isDisabled ? 'disabled' : null,
- }),
- stylex.props(styles.dot, dotSizeStyles[controlSize]),
- )}
- />
- )}
- </span>
+ // No wrapper — see DropdownMenuCheckboxItem: the target belongs on the
+ // visible circle, and the indicator already owns its control size.
+ <RadioControl
+ state={isChecked ? 'checked' : 'unchecked'}
+ size={controlSize}
+ isDisabled={isDisabled}
+ xstyle={styles.marker}
+ {...themeProps('dropdown-menu-radio', {
+ size: controlSize,
+ checked: isChecked ? 'checked' : null,
+ disabled: isDisabled ? 'disabled' : null,
+ })}
+ />
}
startContent={
icon
diff --git a/packages/core/src/DropdownMenu/DropdownMenuSelectable.test.tsx b/packages/core/src/DropdownMenu/DropdownMenuSelectable.test.tsx
index 5f2df0473a..fe94754ce9 100644
--- a/packages/core/src/DropdownMenu/DropdownMenuSelectable.test.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenuSelectable.test.tsx
@@ -78,7 +78,7 @@ describe('DropdownMenuCheckboxItem', () => {
expect(onChangeSpy).toHaveBeenCalledWith(true);
});
- it('keeps the composed checkbox decorative (row is the only announced control)', async () => {
+ it('keeps the checkbox indicator decorative (row is the only announced control)', async () => {
const user = userEvent.setup();
render(
<DropdownMenu button={{label: 'View'}}>
@@ -92,21 +92,20 @@ describe('DropdownMenuCheckboxItem', () => {
screen.getAllByRole('menuitemcheckbox', {hidden: true}),
).toHaveLength(1);
- // The composed CheckboxInput is present in the DOM but sits inside an
- // `aria-hidden` + `inert` subtree: it contributes nothing to the row's
- // accessible name and its native <input> is out of the tab order and the
- // accessibility tree, so it is not a second announced/focusable control.
- // (Browsers enforce inert; jsdom does not model its a11y removal, so this
- // asserts the aria-hidden/inert boundary directly rather than via role.)
+ // The visual is the shared checkbox indicator: aria-hidden, with no nested
+ // native <input>, so the row is the only announced/focusable control.
const row = screen.getByRole('menuitemcheckbox', {
name: /Show archived/,
hidden: true,
});
- const input = row.querySelector('input[type="checkbox"]');
- expect(input).not.toBeNull();
- const marker = input?.closest('[inert]');
- expect(marker).not.toBeNull();
+ expect(row.querySelector('input[type="checkbox"]')).toBeNull();
+ // The shared checkbox target, directly on the row — no wrapper, and no
+ // menu-specific target added for it (main reached this element through
+ // `astryx-checkbox` too).
+ const marker = row.querySelector('.astryx-checkbox');
+ expect(marker).toBeInTheDocument();
expect(marker).toHaveAttribute('aria-hidden', 'true');
+ expect(marker).toHaveAttribute('data-checked', 'checked');
});
it('does not toggle when disabled', async () => {
@@ -159,7 +158,7 @@ describe('DropdownMenuRadioGroup / RadioItem', () => {
).toBeInTheDocument();
});
- it('exposes a themeable slot on the checked radio dot', async () => {
+ it('renders the shared radio indicator in the menu marker', async () => {
const user = userEvent.setup();
render(
<DropdownMenu button={{label: 'Sort'}}>
@@ -177,18 +176,25 @@ describe('DropdownMenuRadioGroup / RadioItem', () => {
name: 'Newest',
hidden: true,
});
- const dot = checked.querySelector('.astryx-dropdown-menu-radio-dot');
- expect(dot).toBeInTheDocument();
- // Mirrors the radio container's visual props/states for consistent theming.
- expect(dot).toHaveAttribute('data-size', 'md');
- expect(dot).toHaveAttribute('data-checked', 'checked');
- // The unchecked radio has no dot, so no dot slot either.
+ // The menu's target and the shared radio target land on the SAME painted
+ // circle, so menu radios and RadioList radios theme together and a theme
+ // never has to reach through a wrapper.
+ const box = checked.querySelector('.astryx-dropdown-menu-radio');
+ expect(box).toHaveClass('astryx-radio');
+ expect(box).toHaveAttribute('data-size', 'md');
+ expect(box).toHaveAttribute('data-checked', 'checked');
+ expect(box?.querySelector('.astryx-radio-dot')).toBeInTheDocument();
+
+ // The unchecked radio still draws its circle, without the dot.
const unchecked = screen.getByRole('menuitemradio', {
name: 'Oldest',
hidden: true,
});
+ const uncheckedIndicator = unchecked.querySelector('.astryx-radio');
+ expect(uncheckedIndicator).toBeInTheDocument();
+ expect(uncheckedIndicator).not.toHaveAttribute('data-checked');
expect(
- unchecked.querySelector('.astryx-dropdown-menu-radio-dot'),
+ uncheckedIndicator?.querySelector('.astryx-radio-dot'),
).not.toBeInTheDocument();
});
diff --git a/packages/core/src/Indicator/CheckIndicator.tsx b/packages/core/src/Indicator/CheckIndicator.tsx
new file mode 100644
index 0000000000..8942b72ace
--- /dev/null
+++ b/packages/core/src/Indicator/CheckIndicator.tsx
@@ -0,0 +1,119 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file CheckIndicator.tsx
+ * @input Indicator state props
+ * @output Exports CheckIndicator — the default single-selection mark
+ * @position Decorative check visual used wherever "this one is chosen" is
+ * marked without a control: selector options, menu rows
+ *
+ * This is the indicator a product replaces to change what "chosen" looks like.
+ * `defineTheme({indicators: {check: RadioIndicator}})` turns every
+ * single-selection mark into a radio, in one line, without any component
+ * knowing it happened.
+ *
+ * It draws NOTHING when unchecked, which is what makes it the default: a
+ * listbox should not show an empty box beside every row. A replacement is free
+ * to draw in both states — a radio does — and hosting components render the
+ * indicator unconditionally so that works.
+ *
+ * Unlike the checkbox and radio indicators, this one renders no chrome of its
+ * own: it IS the glyph. Two consequences, both deliberate:
+ *
+ * - It renders `<Icon>` directly rather than wrapping one, so the class the
+ * host passes (`selector-check`, say) lands on the same element as
+ * `astryx-icon` — one element carrying the mark and its theme target, per
+ * the wrapper reduction in #4838/#4846.
+ * - It adds NO theme target of its own. `astryx-checkbox` and `astryx-radio`
+ * exist because those indicators draw chrome that needs styling; a check
+ * is an icon, and `astryx-icon` plus the host's target already reach it.
+ */
+
+import type {SVGProps} from 'react';
+import {Icon} from '../Icon/Icon';
+import type {IndicatorProps} from './types';
+
+/** The check glyph matches the control sizes the indicator families share. */
+const iconSizeForIndicator = {
+ sm: 'sm',
+ md: 'sm',
+} as const;
+
+/**
+ * The default single-selection mark: a checkmark when chosen, nothing when not.
+ *
+ * Decorative and non-interactive — it renders `aria-hidden` and owns no role,
+ * state, or focus behavior; the option or row that hosts it keeps all of that.
+ *
+ * @example
+ * ```tsx
+ * <CheckIndicator state={isSelected ? 'checked' : 'unchecked'} size="sm" />
+ * ```
+ *
+ * Swap every single-selection mark for a radio:
+ *
+ * @example
+ * ```tsx
+ * import {RadioIndicator} from '@astryxdesign/core/Indicator';
+ *
+ * defineTheme({name: 'brand', indicators: {check: RadioIndicator}});
+ * ```
+ */
+export function CheckIndicator({
+ state,
+ size = 'md',
+ isDisabled = false,
+ children,
+ ref,
+ className,
+ style,
+ xstyle,
+ ...rest
+}: IndicatorProps<'singleSelection'>) {
+ const isChecked = state === 'checked';
+
+ // Nothing to draw, and no box to reserve: an unmarked row keeps the layout
+ // it would have without this indicator.
+ if (!isChecked) {
+ return null;
+ }
+
+ // `children` (a pending Spinner, say) replaces the mark but keeps the
+ // indicator's place, matching the other indicators' contract. There is no
+ // glyph to put the host's props on in that case, so they go on a span.
+ if (children != null) {
+ return (
+ <span ref={ref} aria-hidden="true" className={className} style={style}>
+ {children}
+ </span>
+ );
+ }
+
+ return (
+ <Icon
+ // Spread first so the indicator's own contract (below) wins over any
+ // same-named DOM attribute a caller passed through.
+ //
+ // An indicator declares span props (BaseProps<HTMLSpanElement>) while
+ // Icon declares SVG ones, so the handler types differ nominally. For a
+ // registry icon the element that actually receives these IS a span
+ // (IconFromRegistry renders one), so forwarding them is correct at
+ // runtime; the cast only reconciles the two declarations.
+ {...(rest as Omit<SVGProps<SVGSVGElement>, 'color' | 'ref'>)}
+ icon="check"
+ size={iconSizeForIndicator[size]}
+ color={isDisabled ? 'disabled' : 'accent'}
+ // The focus ring rides in through xstyle (composed at resolution), but
+ // never paints here: it only activates under an owner's indicatorScope
+ // marker, and a listbox row that marks selection takes focus itself
+ // rather than marking its indicator.
+ xstyle={xstyle}
+ // Icon merges className/style with its own rather than shadowing them,
+ // so the host's theme target composes with `astryx-icon`.
+ className={className}
+ style={style}
+ />
+ );
+}
+
+CheckIndicator.displayName = 'CheckIndicator';
diff --git a/packages/core/src/Indicator/CheckboxIndicator.tsx b/packages/core/src/Indicator/CheckboxIndicator.tsx
new file mode 100644
index 0000000000..5318edf597
--- /dev/null
+++ b/packages/core/src/Indicator/CheckboxIndicator.tsx
@@ -0,0 +1,251 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file CheckboxIndicator.tsx
+ * @input Indicator state props
+ * @output Exports CheckboxIndicator — the default checkbox selection visual
+ * @position Decorative checkbox visual shared by CheckboxInput, CheckboxList,
+ * and decorative menu markers
+ */
+
+import * as stylex from '@stylexjs/stylex';
+import {
+ borderVars,
+ colorVars,
+ durationVars,
+ easeVars,
+ radiusVars,
+} from '../theme/tokens.stylex';
+import {mergeProps, themeProps} from '../utils';
+import {indicatorScope} from './indicator.markers.stylex';
+import type {IndicatorProps} from './types';
+
+const styles = stylex.create({
+ box: {
+ boxSizing: 'border-box',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ flexShrink: 0,
+ borderWidth: borderVars['--border-width'],
+ borderStyle: 'solid',
+ borderRadius: radiusVars['--radius-inner'],
+ transitionProperty: 'background-color, border-color',
+ transitionDuration: {
+ default: durationVars['--duration-fast'],
+ '@media (prefers-reduced-motion: reduce)': '0s',
+ },
+ transitionTimingFunction: easeVars['--ease-standard'],
+ },
+ // State-dependent colors with ancestor hover behavior
+ unchecked: {
+ // Foreground for the inherit-shade loading spinner (reads currentColor):
+ // brand accent on the light surface fill.
+ color: colorVars['--color-accent'],
+ borderColor: {
+ default: colorVars['--color-border-emphasized'],
+ [stylex.when.ancestor(':hover', indicatorScope)]: {
+ '@media (hover: hover)': `color-mix(in srgb, ${colorVars['--color-border-emphasized']}, ${colorVars['--color-tint-hover']} 20%)`,
+ },
+ },
+ backgroundColor: {
+ default: colorVars['--color-background-surface'],
+ [stylex.when.ancestor(':hover', indicatorScope)]: {
+ '@media (hover: hover)': `color-mix(in srgb, ${colorVars['--color-background-surface']}, ${colorVars['--color-tint-hover']} 5%)`,
+ },
+ },
+ },
+ checked: {
+ // Foreground for the inherit-shade loading spinner (reads currentColor):
+ // on-accent color against the accent fill.
+ color: colorVars['--color-on-accent'],
+ borderColor: {
+ default: colorVars['--color-accent'],
+ [stylex.when.ancestor(':hover', indicatorScope)]: {
+ '@media (hover: hover)': `color-mix(in srgb, ${colorVars['--color-accent']}, ${colorVars['--color-tint-hover']} 15%)`,
+ },
+ },
+ backgroundColor: {
+ default: colorVars['--color-accent'],
+ [stylex.when.ancestor(':hover', indicatorScope)]: {
+ '@media (hover: hover)': `color-mix(in srgb, ${colorVars['--color-accent']}, ${colorVars['--color-tint-hover']} 15%)`,
+ },
+ },
+ },
+ disabled: {
+ opacity: 0.5,
+ borderColor: {
+ default: colorVars['--color-border'],
+ [stylex.when.ancestor(':hover', indicatorScope)]: {
+ '@media (hover: hover)': colorVars['--color-border'],
+ },
+ },
+ },
+ disabledUnchecked: {
+ backgroundColor: {
+ default: colorVars['--color-background-muted'],
+ [stylex.when.ancestor(':hover', indicatorScope)]: {
+ '@media (hover: hover)': colorVars['--color-background-muted'],
+ },
+ },
+ },
+ checkmark: {
+ display: 'none',
+ color: {
+ default: colorVars['--color-on-accent'],
+ // Forced colors (Windows High Contrast) does not reliably force an SVG
+ // stroke painted with currentColor, so the check stays the same white as
+ // the flattened (Canvas) box fill — a white check on a white box.
+ // CanvasText keeps it perceivable on the Canvas box, matching the
+ // indeterminate mark (WCAG 1.4.11).
+ '@media (forced-colors: active)': 'CanvasText',
+ },
+ },
+ checkmarkVisible: {
+ display: 'block',
+ },
+ indeterminateMark: {
+ display: 'none',
+ backgroundColor: {
+ default: colorVars['--color-on-accent'],
+ // Forced colors (Windows High Contrast) strips painted backgrounds,
+ // which would make the indeterminate bar invisible; CanvasText keeps it
+ // perceivable on the Canvas box fill (WCAG 1.4.11). The checkmark carries
+ // the matching CanvasText treatment on its own style.
+ '@media (forced-colors: active)': 'CanvasText',
+ },
+ borderRadius: radiusVars['--radius-full'],
+ },
+ indeterminateMarkVisible: {
+ display: 'block',
+ },
+});
+
+const boxSizeStyles = stylex.create({
+ sm: {
+ width: 20,
+ height: 20,
+ },
+ md: {
+ width: 24,
+ height: 24,
+ },
+});
+
+const checkmarkSizeStyles = stylex.create({
+ sm: {
+ width: 12,
+ height: 12,
+ },
+ md: {
+ width: 14,
+ height: 14,
+ },
+});
+
+const indeterminateSizeStyles = stylex.create({
+ sm: {
+ width: 10,
+ height: 2,
+ },
+ md: {
+ width: 12,
+ height: 2,
+ },
+});
+
+/**
+ * The default checkbox visual: a square box with a checkmark or an
+ * indeterminate bar.
+ *
+ * Decorative and non-interactive — it renders `aria-hidden` and owns no input,
+ * role, or focus behavior. The focus ring lives on the owner's control wrapper
+ * (see CheckboxInput), so a theme that replaces this component keeps a visible
+ * focus indicator for free. Themes replace it wholesale through
+ * `defineTheme({indicators: {checkbox: MyCheckbox}})`, or restyle it through
+ * the `checkbox` theme target like any other component.
+ *
+ * @example
+ * ```tsx
+ * <CheckboxIndicator state="indeterminate" size="sm" />
+ * ```
+ */
+export function CheckboxIndicator({
+ state,
+ size = 'md',
+ isDisabled = false,
+ children,
+ ref,
+ className,
+ style,
+ xstyle,
+ ...rest
+}: IndicatorProps<'multiSelection'>) {
+ const isChecked = state === 'checked';
+ const isIndeterminate = state === 'indeterminate';
+ const isCheckedOrIndeterminate = isChecked || isIndeterminate;
+
+ return (
+ <span
+ ref={ref}
+ aria-hidden="true"
+ {...mergeProps(
+ themeProps(
+ 'checkbox-indicator',
+ {
+ size,
+ checked: isChecked
+ ? 'checked'
+ : isIndeterminate
+ ? 'indeterminate'
+ : null,
+ disabled: isDisabled ? 'disabled' : null,
+ },
+ // `checkbox` was the target before indicators existed; themes
+ // styling it keep working until the next major.
+ {legacyNames: ['checkbox']},
+ ),
+ stylex.props(
+ styles.box,
+ boxSizeStyles[size],
+ isCheckedOrIndeterminate ? styles.checked : styles.unchecked,
+ isDisabled && styles.disabled,
+ isDisabled && !isCheckedOrIndeterminate && styles.disabledUnchecked,
+ xstyle,
+ ),
+ className,
+ style,
+ )}
+ {...rest}>
+ {children ?? (
+ <>
+ <svg
+ viewBox="0 0 10 10"
+ {...stylex.props(
+ styles.checkmark,
+ checkmarkSizeStyles[size],
+ isChecked && styles.checkmarkVisible,
+ )}>
+ <path
+ d="M8.5 2.5L4 7.5L1.5 5"
+ stroke="currentColor"
+ strokeWidth="1.5"
+ fill="none"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ </svg>
+ <span
+ {...stylex.props(
+ styles.indeterminateMark,
+ indeterminateSizeStyles[size],
+ isIndeterminate && styles.indeterminateMarkVisible,
+ )}
+ />
+ </>
+ )}
+ </span>
+ );
+}
+
+CheckboxIndicator.displayName = 'CheckboxIndicator';
diff --git a/packages/core/src/Indicator/Indicator.doc.mjs b/packages/core/src/Indicator/Indicator.doc.mjs
new file mode 100644
index 0000000000..c8f06af089
--- /dev/null
+++ b/packages/core/src/Indicator/Indicator.doc.mjs
@@ -0,0 +1,278 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').ComponentDoc} */
+
+export const docs = {
+ name: 'Indicator',
+ displayName: 'Indicator',
+ group: 'Indicator',
+ category: 'Data Input',
+ isHiddenFromOverview: true,
+ keywords: [
+ 'indicator',
+ 'checkbox',
+ 'radio',
+ 'control',
+ 'selection',
+ 'mark',
+ 'tick',
+ 'themeable',
+ 'swap',
+ ],
+ description:
+ 'Decorative control visuals — the mark on a chosen option, the box a checkbox draws, the circle a radio draws. Rendered by Selector, CheckboxInput, RadioList, and menu selection rows. Replace one by name through defineTheme({indicators}) and every component drawing it follows.',
+ components: [
+ {
+ name: 'CheckboxIndicator',
+ displayName: 'Checkbox Indicator',
+ description:
+ 'The checkbox visual: a square box with a checkmark or an indeterminate bar. Decorative (aria-hidden) — the owning control keeps the input, role, accessible name, focus, and keyboard behavior.',
+ props: [
+ {
+ name: 'state',
+ type: "'unchecked' | 'checked' | 'indeterminate'",
+ description:
+ 'Which state to draw. An indicator draws in EVERY state — the unchecked box is an empty box, not nothing.',
+ required: true,
+ },
+ {
+ name: 'size',
+ type: "'sm' | 'md'",
+ description: 'Control size: 20px or 24px.',
+ default: "'md'",
+ },
+ {
+ name: 'isDisabled',
+ type: 'boolean',
+ description:
+ 'Whether the owning control is disabled. Purely visual — the owner keeps the real disabled semantics.',
+ default: 'false',
+ },
+ {
+ name: 'children',
+ type: 'ReactNode',
+ description:
+ 'Rendered inside the chrome INSTEAD of the state mark. CheckboxInput passes its loading Spinner through this while a change action is pending, so a replacement indicator must render children when present or the busy visual is lost.',
+ },
+ ],
+ },
+ {
+ name: 'CheckIndicator',
+ displayName: 'Check Indicator',
+ description:
+ 'The mark on a chosen option — a checkmark by default, and nothing at all when unchosen, so a listbox shows no empty box beside every row. This is the indicator to replace to change what "chosen" looks like: mapping it to RadioIndicator gives every single-selection mark radio visuals, including an empty circle on unchosen rows. Unlike the checkbox and radio visuals it renders no chrome of its own — it IS the glyph — so a host\'s theme target lands on the same element as astryx-icon.',
+ props: [
+ {
+ name: 'state',
+ type: "'unchecked' | 'checked'",
+ description:
+ 'Which state to draw. The default renders nothing when unchecked; a replacement may draw in both states.',
+ required: true,
+ },
+ {
+ name: 'size',
+ type: "'sm' | 'md'",
+ description: 'Control size, matching the other indicators.',
+ default: "'md'",
+ },
+ {
+ name: 'isDisabled',
+ type: 'boolean',
+ description:
+ 'Whether the owning row is disabled. Purely visual — the owner keeps the real disabled semantics.',
+ default: 'false',
+ },
+ {
+ name: 'children',
+ type: 'ReactNode',
+ description: 'Rendered INSTEAD of the mark.',
+ },
+ ],
+ },
+ {
+ name: 'RadioIndicator',
+ displayName: 'Radio Indicator',
+ description:
+ 'The radio visual: a circle with a filled inner dot when selected. Draws in both states — an unselected radio is an empty circle, which is what lets it stand in for a checkmark in a selection slot.',
+ props: [
+ {
+ name: 'state',
+ type: "'unchecked' | 'checked'",
+ description:
+ 'Which state to draw. Radio belongs to the singleSelection family, which has no partial state.',
+ required: true,
+ },
+ {
+ name: 'size',
+ type: "'sm' | 'md'",
+ description: 'Control size: 20px or 24px.',
+ default: "'md'",
+ },
+ {
+ name: 'isDisabled',
+ type: 'boolean',
+ description:
+ 'Whether the owning control is disabled. Purely visual — the owner keeps the real disabled semantics.',
+ default: 'false',
+ },
+ {
+ name: 'children',
+ type: 'ReactNode',
+ description:
+ 'Rendered inside the chrome INSTEAD of the state mark.',
+ },
+ ],
+ },
+ ],
+ theming: {
+ targets: [
+ {
+ className: 'astryx-checkbox-indicator',
+ visualProps: ['size'],
+ states: ['checked', 'disabled'],
+ },
+ {
+ className: 'astryx-radio-indicator',
+ visualProps: ['size'],
+ states: ['checked', 'disabled'],
+ },
+ {className: 'astryx-radio-indicator-dot', visualProps: ['size']},
+ // Still emitted beside the names above, so themes written against them
+ // keep working. Drop in the next major.
+ {
+ className: 'astryx-checkbox',
+ visualProps: ['size'],
+ states: ['checked', 'disabled'],
+ deprecatedFor: 'checkbox-indicator',
+ },
+ {
+ className: 'astryx-radio',
+ visualProps: ['size'],
+ states: ['checked', 'disabled'],
+ deprecatedFor: 'radio-indicator',
+ },
+ {
+ className: 'astryx-radio-dot',
+ visualProps: ['size'],
+ deprecatedFor: 'radio-indicator-dot',
+ },
+ ],
+ },
+ examples: [
+ {
+ label: 'Restyle an indicator (the common path)',
+ code: `// Indicators render the same stable class targets wherever they appear, so
+// one component override reaches the form control, the menu row, and any
+// selection slot themed to use it. No indicator-specific API needed.
+defineTheme({
+ name: 'brand',
+ components: {
+ 'checkbox-indicator': {
+ base: {borderRadius: 'var(--radius-full)', borderWidth: '2px'},
+ checked: {
+ backgroundColor: 'var(--color-accent)',
+ borderColor: 'var(--color-accent)',
+ },
+ 'checked+disabled': {backgroundColor: 'var(--color-background-muted)'},
+ },
+ 'radio-indicator': {base: {borderWidth: '2px'}},
+ 'radio-indicator-dot': {base: {borderRadius: '2px'}},
+ },
+});`,
+ },
+ {
+ label: 'Replace an indicator with your own component',
+ code: `// When the shape itself is wrong, hand the theme a component. It receives
+// {state, size, isDisabled, children} and nothing else.
+//
+// Use theme tokens, never raw values — run \`npx astryx docs tokens\` for the
+// full set. Color: --color-accent, --color-on-accent, --color-border,
+// --color-border-emphasized, --color-background-surface,
+// --color-background-muted. Radius: --radius-inner, --radius-full.
+// Border width: --border-width.
+function BrandCheckbox({state, size = 'md', isDisabled, children}) {
+ return (
+ <span
+ aria-hidden="true"
+ style={{
+ width: size === 'sm' ? 20 : 24,
+ height: size === 'sm' ? 20 : 24,
+ borderRadius: 'var(--radius-inner)',
+ border: 'var(--border-width) solid var(--color-border-emphasized)',
+ color: 'var(--color-accent)',
+ opacity: isDisabled ? 0.5 : 1,
+ }}>
+ {/* children first: the owner passes a loading Spinner through it */}
+ {children ?? (state === 'checked' ? <StarGlyph /> : null)}
+ </span>
+ );
+}
+
+defineTheme({name: 'brand', indicators: {checkbox: BrandCheckbox}});`,
+ },
+ {
+ label: 'Use radio visuals for single selection',
+ code: `// Replacement is by NAME, so one entry reaches every component that draws
+// that indicator. Here every option in a Selector listbox draws a radio —
+// including the unselected ones, which a check mark cannot do.
+import {RadioIndicator} from '@astryxdesign/core/Indicator';
+
+defineTheme({name: 'brand', indicators: {check: RadioIndicator}});`,
+ },
+ ],
+ usage: {
+ description:
+ 'Indicators are the componentized selection visuals shared by CheckboxInput, RadioList, and menu selection rows. They are decorative: the owning component keeps the input, role, accessible name, focus, and keyboard behavior, while the indicator turns state into a picture. That split is what makes them themeable — restyle one through its class targets, or replace the component outright.',
+ bestPractices: [
+ {
+ guidance: true,
+ description:
+ 'Reach for component overrides first (components: {checkbox}). Replacing the component is the heavier path, for when the shape itself is wrong.',
+ },
+ {
+ guidance: true,
+ description:
+ 'A replacement must render `children` when present — the owning control passes its loading Spinner through it, and dropping it loses the busy visual while aria-busy still fires.',
+ },
+ {
+ guidance: true,
+ description:
+ 'A replacement must set aria-hidden. The owning control provides the role and accessible name; a visible indicator would be announced twice.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Use theme tokens for every color, radius, and border width in a replacement. Run `npx astryx docs tokens` for the set.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Spread `indicatorFocusRingProps()` on a replacement\'s root if its shape differs from the control\'s default. It carries the ring AND the marker that tells the owning control to stand down, as one spread, so you cannot suppress the owner\'s ring without drawing your own. Skip it and the owner draws a correctly-visible ring in the default shape — the failure mode is a slightly-wrong outline, never a missing one (WCAG 2.4.7). It keys off the owner scope marker because the native input is a visually hidden SIBLING that a plain :focus-visible could never see.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Thread hover or pressed state in as props. Interaction state reaches an indicator through the owner\u2019s CSS ancestor marker, so hovering the row tints the control with no props involved.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Render only in the selected state. An indicator draws in every state — an unselected radio is an empty circle, and a mark that disappears leaves blank rows.',
+ },
+ ],
+ anatomy: [
+ {
+ name: 'Chrome',
+ required: true,
+ description:
+ 'The persistent box or circle, present in every state. Carries the astryx-checkbox / astryx-radio theme target.',
+ },
+ {
+ name: 'State mark',
+ required: false,
+ description:
+ 'The checkmark, indeterminate bar, or radio dot shown inside the chrome for the current state.',
+ },
+ ],
+ },
+};
diff --git a/packages/core/src/Indicator/Indicator.test.tsx b/packages/core/src/Indicator/Indicator.test.tsx
new file mode 100644
index 0000000000..f44a561491
--- /dev/null
+++ b/packages/core/src/Indicator/Indicator.test.tsx
@@ -0,0 +1,145 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, expect, it} from 'vitest';
+import {render, renderHook, screen} from '@testing-library/react';
+import type {PropsWithChildren, ReactNode} from 'react';
+import {Theme} from '../theme/Theme';
+import {defineTheme} from '../theme/defineTheme';
+import {CheckboxIndicator} from './CheckboxIndicator';
+import {RadioIndicator} from './RadioIndicator';
+import {getIndicator} from './indicatorRegistry';
+import {useIndicator} from './useIndicator';
+import type {IndicatorProps} from './types';
+
+function createThemeWrapper(theme: ReturnType<typeof defineTheme>) {
+ function ThemeWrapper({children}: PropsWithChildren): ReactNode {
+ return <Theme theme={theme}>{children}</Theme>;
+ }
+ return ThemeWrapper;
+}
+
+describe('default indicators', () => {
+ it('renders the checkbox theme target with state and size', () => {
+ render(<CheckboxIndicator state="indeterminate" size="sm" />);
+
+ const box = document.querySelector('.astryx-checkbox');
+ expect(box).toBeInTheDocument();
+ expect(box).toHaveAttribute('data-checked', 'indeterminate');
+ expect(box).toHaveAttribute('data-size', 'sm');
+ // Decorative: the owning control keeps the role and accessible name.
+ expect(box).toHaveAttribute('aria-hidden', 'true');
+ });
+
+ it('renders the radio dot only when checked, in both states', () => {
+ const {rerender} = render(<RadioIndicator state="unchecked" />);
+
+ // The circle draws in the unchecked state — this is what lets a radio act
+ // as a selection indicator where an icon would render nothing.
+ expect(document.querySelector('.astryx-radio')).toBeInTheDocument();
+ expect(document.querySelector('.astryx-radio-dot')).not.toBeInTheDocument();
+
+ rerender(<RadioIndicator state="checked" />);
+ expect(document.querySelector('.astryx-radio-dot')).toBeInTheDocument();
+ expect(document.querySelector('.astryx-radio')).toHaveAttribute(
+ 'data-checked',
+ 'checked',
+ );
+ });
+
+ it('renders children instead of the state mark', () => {
+ render(
+ <CheckboxIndicator state="checked">
+ <span data-testid="busy" />
+ </CheckboxIndicator>,
+ );
+
+ expect(screen.getByTestId('busy')).toBeInTheDocument();
+ });
+
+ it('reflects the disabled state for theme targeting', () => {
+ render(<RadioIndicator state="checked" isDisabled />);
+
+ expect(document.querySelector('.astryx-radio')).toHaveAttribute(
+ 'data-disabled',
+ 'disabled',
+ );
+ });
+});
+
+describe('useIndicator', () => {
+ it('returns the built-in indicator without a theme override', () => {
+ const {result} = renderHook(() => useIndicator('checkbox'));
+
+ expect(result.current).toBe(CheckboxIndicator);
+ });
+
+ it('resolves an indicator component from the nearest theme', () => {
+ function BrandCheckbox({state}: IndicatorProps) {
+ return <span data-testid="brand">{state}</span>;
+ }
+ const theme = defineTheme({
+ name: 'brand-indicators',
+ indicators: {checkbox: BrandCheckbox},
+ });
+
+ const {result} = renderHook(() => useIndicator('checkbox'), {
+ wrapper: createThemeWrapper(theme),
+ });
+
+ expect(result.current).toBe(BrandCheckbox);
+ // Unmapped indicators keep the built-in.
+ expect(getIndicator('radio', theme)).toBe(RadioIndicator);
+ });
+});
+
+/**
+ * A theme target is public API. Renaming one to follow the
+ * `<component>-kebab` convention (`checkbox` → `checkbox-indicator`) would
+ * silently break every theme styling the old name — the CSS still compiles, it
+ * just stops matching. So both names are emitted for a deprecation window, and
+ * these tests pin that promise from both ends: the new name exists, and the
+ * old one has not quietly disappeared.
+ */
+describe('renamed theme targets stay non-breaking', () => {
+ const cases = [
+ {
+ name: 'CheckboxIndicator',
+ render: () => <CheckboxIndicator state="checked" />,
+ current: 'astryx-checkbox-indicator',
+ legacy: 'astryx-checkbox',
+ },
+ {
+ name: 'RadioIndicator',
+ render: () => <RadioIndicator state="checked" />,
+ current: 'astryx-radio-indicator',
+ legacy: 'astryx-radio',
+ },
+ ] as const;
+
+ for (const {name, render: renderCase, current, legacy} of cases) {
+ it(`${name} emits both the current and the legacy target`, () => {
+ const {container} = render(renderCase());
+ const el = container.querySelector(`.${current}`);
+ expect(el, `${name} should render ${current}`).toBeInTheDocument();
+ expect(el, `${name} must keep emitting ${legacy}`).toHaveClass(legacy);
+ });
+ }
+
+ it('keeps the legacy dot target on the radio mark', () => {
+ const {container} = render(<RadioIndicator state="checked" />);
+ const dot = container.querySelector('.astryx-radio-indicator-dot');
+ expect(dot).toBeInTheDocument();
+ expect(dot).toHaveClass('astryx-radio-dot');
+ });
+
+ it('puts both names on ONE element, so either selector wins equally', () => {
+ // If the legacy class were moved to a wrapper instead, an old theme's
+ // rules would land on a different box than a new theme's — same-element
+ // is what makes the two names interchangeable.
+ const {container} = render(<CheckboxIndicator state="unchecked" />);
+ expect(container.querySelectorAll('.astryx-checkbox')).toHaveLength(1);
+ expect(container.querySelector('.astryx-checkbox')).toBe(
+ container.querySelector('.astryx-checkbox-indicator'),
+ );
+ });
+});
diff --git a/packages/core/src/Indicator/RadioIndicator.tsx b/packages/core/src/Indicator/RadioIndicator.tsx
new file mode 100644
index 0000000000..a73a531da3
--- /dev/null
+++ b/packages/core/src/Indicator/RadioIndicator.tsx
@@ -0,0 +1,196 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file RadioIndicator.tsx
+ * @input Indicator state props
+ * @output Exports RadioIndicator — the default radio selection visual
+ * @position Decorative radio visual shared by RadioList, decorative menu
+ * markers, and any selection slot themed to use a radio
+ */
+
+import * as stylex from '@stylexjs/stylex';
+import {
+ borderVars,
+ colorVars,
+ durationVars,
+ easeVars,
+} from '../theme/tokens.stylex';
+import {mergeProps, themeProps} from '../utils';
+import {indicatorScope} from './indicator.markers.stylex';
+import type {IndicatorProps} from './types';
+
+const styles = stylex.create({
+ circle: {
+ boxSizing: 'border-box',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ flexShrink: 0,
+ borderWidth: borderVars['--border-width'],
+ borderStyle: 'solid',
+ borderRadius: '50%',
+ transitionProperty: 'background-color, border-color',
+ transitionDuration: {
+ default: durationVars['--duration-fast'],
+ '@media (prefers-reduced-motion: reduce)': '0s',
+ },
+ transitionTimingFunction: easeVars['--ease-standard'],
+ },
+ unchecked: {
+ borderColor: {
+ default: colorVars['--color-border-emphasized'],
+ [stylex.when.ancestor(':hover', indicatorScope)]: {
+ '@media (hover: hover)': `color-mix(in srgb, ${colorVars['--color-border-emphasized']}, ${colorVars['--color-tint-hover']} 20%)`,
+ },
+ },
+ backgroundColor: {
+ default: colorVars['--color-background-surface'],
+ [stylex.when.ancestor(':hover', indicatorScope)]: {
+ '@media (hover: hover)': `color-mix(in srgb, ${colorVars['--color-background-surface']}, ${colorVars['--color-tint-hover']} 5%)`,
+ },
+ },
+ },
+ checked: {
+ borderColor: {
+ default: colorVars['--color-accent'],
+ [stylex.when.ancestor(':hover', indicatorScope)]: {
+ '@media (hover: hover)': `color-mix(in srgb, ${colorVars['--color-accent']}, ${colorVars['--color-tint-hover']} 15%)`,
+ },
+ },
+ backgroundColor: {
+ default: colorVars['--color-accent'],
+ [stylex.when.ancestor(':hover', indicatorScope)]: {
+ '@media (hover: hover)': `color-mix(in srgb, ${colorVars['--color-accent']}, ${colorVars['--color-tint-hover']} 15%)`,
+ },
+ },
+ },
+ disabled: {
+ opacity: 0.5,
+ borderColor: {
+ default: colorVars['--color-border'],
+ [stylex.when.ancestor(':hover', indicatorScope)]: {
+ '@media (hover: hover)': colorVars['--color-border'],
+ },
+ },
+ },
+ disabledUnchecked: {
+ backgroundColor: {
+ default: colorVars['--color-background-muted'],
+ [stylex.when.ancestor(':hover', indicatorScope)]: {
+ '@media (hover: hover)': colorVars['--color-background-muted'],
+ },
+ },
+ },
+ dot: {
+ borderRadius: '50%',
+ backgroundColor: {
+ default: colorVars['--color-on-accent'],
+ // Forced colors (Windows High Contrast) strips painted backgrounds,
+ // which would make the selected dot invisible — checked and unchecked
+ // radios would look identical. CanvasText keeps the dot perceivable on
+ // the Canvas circle fill (WCAG 1.4.11).
+ '@media (forced-colors: active)': 'CanvasText',
+ },
+ },
+});
+
+const circleSizeStyles = stylex.create({
+ sm: {
+ width: 20,
+ height: 20,
+ },
+ md: {
+ width: 24,
+ height: 24,
+ },
+});
+
+const dotSizeStyles = stylex.create({
+ sm: {
+ width: 8,
+ height: 8,
+ },
+ md: {
+ width: 10,
+ height: 10,
+ },
+});
+
+/**
+ * The default radio visual: a circle with a filled inner dot when selected.
+ *
+ * Decorative and non-interactive — it renders `aria-hidden` and owns no input,
+ * role, or focus behavior. Themes replace it wholesale through
+ * `defineTheme({indicators: {radio: MyRadio}})`, or restyle it through the
+ * `radio` / `radio-dot` theme targets like any other component.
+ *
+ * Unlike an icon, a radio draws in *both* states — an empty circle when
+ * unchecked. That is what makes it usable as a selection indicator in
+ * components whose default is "a checkmark when selected, nothing otherwise".
+ *
+ * @example
+ * ```tsx
+ * <RadioIndicator state="checked" size="md" />
+ * ```
+ */
+export function RadioIndicator({
+ state,
+ size = 'md',
+ isDisabled = false,
+ children,
+ ref,
+ className,
+ style,
+ xstyle,
+ ...rest
+}: IndicatorProps<'singleSelection'>) {
+ // A radio has no partial state; anything other than unchecked reads as
+ // selected.
+ const isChecked = state !== 'unchecked';
+
+ return (
+ <span
+ ref={ref}
+ aria-hidden="true"
+ {...mergeProps(
+ themeProps(
+ 'radio-indicator',
+ {
+ size,
+ checked: isChecked ? 'checked' : null,
+ disabled: isDisabled ? 'disabled' : null,
+ },
+ // `radio` was the target before indicators existed; themes styling
+ // it keep working until the next major.
+ {legacyNames: ['radio']},
+ ),
+ stylex.props(
+ styles.circle,
+ circleSizeStyles[size],
+ isChecked ? styles.checked : styles.unchecked,
+ isDisabled && styles.disabled,
+ isDisabled && !isChecked && styles.disabledUnchecked,
+ xstyle,
+ ),
+ className,
+ style,
+ )}
+ {...rest}>
+ {children ??
+ (isChecked && (
+ <span
+ {...mergeProps(
+ themeProps(
+ 'radio-indicator-dot',
+ {size},
+ {legacyNames: ['radio-dot']},
+ ),
+ stylex.props(styles.dot, dotSizeStyles[size]),
+ )}
+ />
+ ))}
+ </span>
+ );
+}
+
+RadioIndicator.displayName = 'RadioIndicator';
diff --git a/packages/core/src/Indicator/index.ts b/packages/core/src/Indicator/index.ts
new file mode 100644
index 0000000000..0334072b3b
--- /dev/null
+++ b/packages/core/src/Indicator/index.ts
@@ -0,0 +1,42 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file index.ts
+ * @input None (re-export barrel)
+ * @output Public indicator surface: components, registry, hook, types
+ * @position Entry point for the stateful control-visual layer
+ *
+ * Indicators are the componentized form of stateful control visuals — the
+ * checkbox box, the radio circle, the mark on a chosen option. They are
+ * decorative: the owning component keeps the role, state, and focus behavior,
+ * while the indicator turns state into a picture.
+ *
+ * That makes them themeable through CSS targets like any other component, and
+ * replaceable wholesale by name through `defineTheme({indicators})` — replace
+ * `check` and every single-selection mark in the app follows.
+ */
+
+export {CheckboxIndicator} from './CheckboxIndicator';
+export {CheckIndicator} from './CheckIndicator';
+export {RadioIndicator} from './RadioIndicator';
+
+// Registry (RSC-compatible, no 'use client')
+export {defaultIndicators, getIndicator} from './indicatorRegistry';
+export type {IndicatorRegistrySource} from './indicatorRegistry';
+
+export {useIndicator} from './useIndicator';
+
+export {indicatorScope} from './indicator.markers.stylex';
+
+export type {
+ IndicatorComponent,
+ IndicatorFamily,
+ IndicatorFamilyMap,
+ IndicatorMap,
+ IndicatorName,
+ IndicatorNameOfFamily,
+ IndicatorProps,
+ IndicatorRegistry,
+ IndicatorSize,
+ IndicatorState,
+} from './types';
diff --git a/packages/core/src/Indicator/indicator.markers.stylex.ts b/packages/core/src/Indicator/indicator.markers.stylex.ts
new file mode 100644
index 0000000000..9fa548da64
--- /dev/null
+++ b/packages/core/src/Indicator/indicator.markers.stylex.ts
@@ -0,0 +1,19 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import * as stylex from '@stylexjs/stylex';
+
+/**
+ * Scoped marker for indicator ancestor selectors.
+ *
+ * An owner (CheckboxInput's row, RadioListItem's row) applies this marker to
+ * the element whose hover and focus should drive the indicator's appearance.
+ * The indicator reads it through `stylex.when.ancestor()`, so interaction
+ * state stays in CSS instead of being threaded through React props — and
+ * owners that should *not* tint their indicator on hover (decorative menu
+ * markers, listbox options) simply don't apply the marker.
+ *
+ * Owners apply it only while enabled, so disabled controls get no hover
+ * feedback.
+ */
+export const indicatorScope: ReturnType<typeof stylex.defineMarker> =
+ stylex.defineMarker();
diff --git a/packages/core/src/Indicator/indicatorRegistry.ts b/packages/core/src/Indicator/indicatorRegistry.ts
new file mode 100644
index 0000000000..e388cf5605
--- /dev/null
+++ b/packages/core/src/Indicator/indicatorRegistry.ts
@@ -0,0 +1,72 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file indicatorRegistry.ts
+ * @input Theme source and indicator name
+ * @output Exports the default indicator map and getIndicator resolution
+ * @position Server-safe indicator resolver; no 'use client' so it is
+ * importable from RSC
+ */
+
+import type {DefinedTheme} from '../theme/defineTheme';
+import {getRegisteredTheme} from '../theme/themeRegistry';
+import {CheckboxIndicator} from './CheckboxIndicator';
+import {CheckIndicator} from './CheckIndicator';
+import {RadioIndicator} from './RadioIndicator';
+import type {
+ IndicatorComponent,
+ IndicatorMap,
+ IndicatorName,
+ IndicatorRegistry,
+} from './types';
+
+/**
+ * The indicators Astryx ships. A theme's `indicators` entries override these
+ * by name.
+ *
+ * Typed per family (rather than as one widened component type) so a default
+ * declared here has to accept the states its family passes — the same rule
+ * {@link IndicatorRegistry} holds replacements to.
+ */
+export const defaultIndicators: {
+ [N in IndicatorName]: IndicatorComponent<IndicatorMap[N]>;
+} = {
+ check: CheckIndicator,
+ checkbox: CheckboxIndicator,
+ radio: RadioIndicator,
+};
+
+export type IndicatorRegistrySource = DefinedTheme | string | null | undefined;
+
+function getTheme(source: IndicatorRegistrySource): DefinedTheme | null {
+ if (source == null) {
+ return null;
+ }
+ return typeof source === 'string' ? getRegisteredTheme(source) : source;
+}
+
+function getThemeIndicators(
+ source: IndicatorRegistrySource,
+): IndicatorRegistry | null {
+ return getTheme(source)?.indicators ?? null;
+}
+
+/**
+ * Resolve an indicator component by name, preferring the theme's override and
+ * falling back to the built-in indicator.
+ *
+ * Works in both server and client environments. Client components should use
+ * the {@link useIndicator} hook, which resolves against the nearest `<Theme>`.
+ *
+ * @example
+ * ```tsx
+ * const Radio = getIndicator('radio', themeName);
+ * <Radio state="checked" />
+ * ```
+ */
+export function getIndicator<N extends IndicatorName>(
+ name: N,
+ source?: IndicatorRegistrySource,
+): IndicatorComponent<IndicatorMap[N]> {
+ return getThemeIndicators(source)?.[name] ?? defaultIndicators[name];
+}
diff --git a/packages/core/src/Indicator/types.ts b/packages/core/src/Indicator/types.ts
new file mode 100644
index 0000000000..c3078688aa
--- /dev/null
+++ b/packages/core/src/Indicator/types.ts
@@ -0,0 +1,158 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file types.ts
+ * @input None (pure type definitions)
+ * @output The indicator contract: families, states, props, names, registry
+ * @position Type foundation for stateful control visuals
+ *
+ * An **indicator** is a decorative visual that expresses a piece of component
+ * state: the box a checkbox draws, the circle a radio draws, the mark on a
+ * chosen list option. The owning component keeps the input, role, accessible
+ * name, focus, and keyboard behavior; the indicator turns state into a picture.
+ *
+ * Componentizing them buys three things a theme could not otherwise have:
+ *
+ * 1. **Theme it** — an indicator renders stable `astryx-*` class targets, so
+ * `defineTheme({components})` restyles it like any other component, in one
+ * place rather than per host component.
+ * 2. **Swizzle it** — `astryx swizzle <Name>` copies the source to own.
+ * 3. **Replace it** — `defineTheme({indicators})` swaps in another component
+ * by name, and every component that renders that indicator follows. A
+ * product that wants radio visuals for single selection replaces `check`.
+ *
+ * Indicators come in **families**, and a family fixes the state space. That is
+ * what lets one mechanism serve semantics as different as "is this option
+ * chosen" and "are several of these chosen" without either pretending to be
+ * the other, and without a shared enum that would typecheck `indeterminate` on
+ * a radio.
+ *
+ * Each family's vocabulary is the one the accessibility layer already uses, so
+ * a component passing state down says the same word its ARIA attribute says.
+ * Sharing one enum across families was measured and rejected (#4831): it
+ * produced call sites reading `aria-expanded={isOpen}` beside
+ * `state={isOpen ? 'on' : 'off'}`.
+ */
+
+import type {ComponentType, ReactNode, Ref} from 'react';
+import type {BaseProps} from '../BaseProps';
+
+/**
+ * The indicator families, each mapped to the states it can express.
+ *
+ * Single and multi selection are separate families because their state spaces
+ * genuinely differ: `aria-checked` is `true|false` for a radio and
+ * `true|false|mixed` for a checkbox. Keeping them apart is what makes a
+ * replacement type-checkable — a checkbox visual cannot stand in where only
+ * two states are ever passed, and a radio cannot be asked to draw a partial
+ * state it has no picture for.
+ *
+ * Adding a family is additive: declare it here, then declare indicators of
+ * that family in {@link IndicatorMap}. Packages outside core can contribute
+ * families through module augmentation.
+ */
+export interface IndicatorFamilyMap {
+ /** Is this one thing chosen? Radios, and the mark on a selected option. */
+ singleSelection: 'unchecked' | 'checked';
+ /** Which of these are chosen? Checkboxes, including the partial state. */
+ multiSelection: 'unchecked' | 'checked' | 'indeterminate';
+}
+
+export type IndicatorFamily = keyof IndicatorFamilyMap & string;
+
+/** The states an indicator of family `F` can be asked to draw. */
+export type IndicatorState<F extends IndicatorFamily = IndicatorFamily> =
+ IndicatorFamilyMap[F];
+
+/** Indicator size scale — matches the control sizes of the owning inputs. */
+export type IndicatorSize = 'sm' | 'md';
+
+/**
+ * Props every indicator accepts.
+ *
+ * Indicators are **decorative**: they render `aria-hidden` visuals and own no
+ * role, focus, keyboard handling, or state. The component that renders one
+ * (CheckboxInput, RadioListItem, a listbox option) keeps all of that. An
+ * indicator's only job is to turn `state` into a picture.
+ *
+ * Interaction state is deliberately *not* a prop. Hover and focus reach an
+ * indicator through the CSS ancestor marker ({@link indicatorScope}) applied
+ * by its owner, so a row hover tints the control without anyone threading a
+ * boolean through React — and an owner that should not tint its indicator
+ * simply does not apply the marker.
+ */
+export interface IndicatorProps<
+ F extends IndicatorFamily = IndicatorFamily,
+> extends BaseProps<HTMLSpanElement> {
+ /** Ref forwarded to the indicator's root element. */
+ ref?: Ref<HTMLSpanElement>;
+ /** Which state to draw. The state space is fixed by the family. */
+ state: IndicatorState<F>;
+ /**
+ * Control size.
+ * @default 'md'
+ */
+ size?: IndicatorSize;
+ /**
+ * Whether the owning control is disabled. Purely visual — the owner still
+ * owns the actual disabled semantics.
+ * @default false
+ */
+ isDisabled?: boolean;
+ /**
+ * Content rendered inside the indicator chrome *instead of* the state mark.
+ * CheckboxInput uses this to show a loading Spinner inside the box while a
+ * change action is pending.
+ */
+ children?: ReactNode;
+}
+
+/** An indicator is any component accepting {@link IndicatorProps} of its family. */
+export type IndicatorComponent<F extends IndicatorFamily = IndicatorFamily> =
+ ComponentType<IndicatorProps<F>>;
+
+/**
+ * The named indicators a theme can replace, each mapped to its family.
+ *
+ * The name is what a theme addresses, and what every component renders
+ * through — so replacing `check` reaches every single-selection mark at once,
+ * which is the point.
+ *
+ * Packages outside core can contribute their own through module augmentation:
+ *
+ * ```ts
+ * declare module '@astryxdesign/core/Indicator' {
+ * interface IndicatorMap {
+ * 'brand-star': 'singleSelection';
+ * }
+ * }
+ * ```
+ */
+export interface IndicatorMap {
+ /** The mark on a chosen option — a checkmark by default. */
+ check: 'singleSelection';
+ /** The filled circle of a radio control. */
+ radio: 'singleSelection';
+ /** The box of a checkbox control, including its partial state. */
+ checkbox: 'multiSelection';
+}
+
+export type IndicatorName = keyof IndicatorMap & string;
+
+/** The indicator names belonging to family `F`. */
+export type IndicatorNameOfFamily<F extends IndicatorFamily> = {
+ [N in IndicatorName]: IndicatorMap[N] extends F ? N : never;
+}[IndicatorName];
+
+/**
+ * Theme-provided indicator overrides, keyed by indicator name.
+ *
+ * Family-checked: each entry must accept the state space of that indicator's
+ * family, so a replacement cannot be written against the wrong states. A
+ * `check` replacement that only handles `collapsed`/`expanded`, or a `radio`
+ * replacement expecting `indeterminate`, is a type error rather than a
+ * runtime surprise.
+ */
+export type IndicatorRegistry = {
+ [N in IndicatorName]?: IndicatorComponent<IndicatorMap[N]>;
+};
diff --git a/packages/core/src/Indicator/useIndicator.ts b/packages/core/src/Indicator/useIndicator.ts
new file mode 100644
index 0000000000..293ed8bef5
--- /dev/null
+++ b/packages/core/src/Indicator/useIndicator.ts
@@ -0,0 +1,29 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file useIndicator.ts
+ * @input Indicator name
+ * @output Exports useIndicator hook for theme-aware indicator components
+ * @position Client hook used by controls that render a selection visual
+ */
+
+import {useThemeName} from '../theme/useTheme';
+import {getIndicator} from './indicatorRegistry';
+import type {IndicatorComponent, IndicatorMap, IndicatorName} from './types';
+
+/**
+ * Resolve an indicator component from the nearest `<Theme>`.
+ *
+ * @example
+ * ```tsx
+ * const Checkbox = useIndicator('checkbox');
+ * return <Checkbox state={isChecked ? 'checked' : 'unchecked'} size={size} />;
+ * ```
+ */
+export function useIndicator<N extends IndicatorName>(
+ name: N,
+): IndicatorComponent<IndicatorMap[N]> {
+ return getIndicator(name, useThemeName());
+}
diff --git a/packages/core/src/RadioList/RadioList.doc.mjs b/packages/core/src/RadioList/RadioList.doc.mjs
index 44c1bae2d5..ffca432217 100644
--- a/packages/core/src/RadioList/RadioList.doc.mjs
+++ b/packages/core/src/RadioList/RadioList.doc.mjs
@@ -12,8 +12,10 @@ export const docs = {
targets: [
{className: 'astryx-radio-list', visualProps: ['orientation', 'size']},
{className: 'astryx-radio-list-item'},
- {className: 'astryx-radio', visualProps: ['size'], states: ['checked', 'disabled']},
- {className: 'astryx-radio-dot', visualProps: ['size']},
+ {className: 'astryx-radio-indicator', visualProps: ['size'], states: ['checked', 'disabled']},
+ {className: 'astryx-radio-indicator-dot', visualProps: ['size']},
+ {className: 'astryx-radio', visualProps: ['size'], states: ['checked', 'disabled'], deprecatedFor: 'radio-indicator'},
+ {className: 'astryx-radio-dot', visualProps: ['size'], deprecatedFor: 'radio-indicator-dot'},
],
},
description: 'Radio group container with field integration for label, description, and status.',
diff --git a/packages/core/src/RadioList/RadioListItem.tsx b/packages/core/src/RadioList/RadioListItem.tsx
index 35d97257bc..a4b6cbd14d 100644
--- a/packages/core/src/RadioList/RadioListItem.tsx
+++ b/packages/core/src/RadioList/RadioListItem.tsx
@@ -18,19 +18,15 @@
* - /packages/cli/assets/templates/blocks/components/RadioList/ (showcase blocks)
*/
-import React, {use, useId, type ReactNode} from 'react';
+import React, {use, useId, useRef, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {BaseProps} from '../BaseProps';
-import {
- colorVars,
- spacingVars,
- durationVars,
- easeVars,
- borderVars,
-} from '../theme/tokens.stylex';
+import {colorVars, spacingVars} from '../theme/tokens.stylex';
import {RadioListContext} from './RadioList';
import {mergeProps} from '../utils';
-import {radioScope} from './radio.markers.stylex';
+import {indicatorScope} from '../Indicator/indicator.markers.stylex';
+import {useIndicatorFocusRing} from '../hooks/useIndicatorFocusRing';
+import {useIndicator} from '../Indicator';
import {Item} from '../Item';
import {themeProps} from '../utils/themeProps';
@@ -59,74 +55,9 @@ const styles = stylex.create({
inputDisabled: {
cursor: 'not-allowed',
},
- radio: {
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- borderWidth: borderVars['--border-width'],
- borderStyle: 'solid',
- borderRadius: '50%',
- transitionProperty: 'background-color, border-color',
- transitionDuration: durationVars['--duration-fast'],
- transitionTimingFunction: easeVars['--ease-standard'],
- boxSizing: 'border-box',
- },
- radioUnchecked: {
- borderColor: {
- default: colorVars['--color-border-emphasized'],
- [stylex.when.ancestor(':hover', radioScope)]: {
- '@media (hover: hover)': `color-mix(in srgb, ${colorVars['--color-border-emphasized']}, ${colorVars['--color-tint-hover']} 20%)`,
- },
- },
- backgroundColor: {
- default: colorVars['--color-background-surface'],
- [stylex.when.ancestor(':hover', radioScope)]: {
- '@media (hover: hover)': `color-mix(in srgb, ${colorVars['--color-background-surface']}, ${colorVars['--color-tint-hover']} 5%)`,
- },
- },
- },
- radioChecked: {
- borderColor: {
- default: colorVars['--color-accent'],
- [stylex.when.ancestor(':hover', radioScope)]: {
- '@media (hover: hover)': `color-mix(in srgb, ${colorVars['--color-accent']}, ${colorVars['--color-tint-hover']} 15%)`,
- },
- },
- backgroundColor: {
- default: colorVars['--color-accent'],
- [stylex.when.ancestor(':hover', radioScope)]: {
- '@media (hover: hover)': `color-mix(in srgb, ${colorVars['--color-accent']}, ${colorVars['--color-tint-hover']} 15%)`,
- },
- },
- },
- radioWrapperFocus: {
- outline: {
- default: 'none',
- ':has(:focus-visible)': `2px solid ${colorVars['--color-accent']}`,
- },
- outlineOffset: {
- default: '0',
- ':has(:focus-visible)': '2px',
- },
- borderRadius: '50%',
- },
- radioDisabled: {
- opacity: 0.5,
- borderColor: colorVars['--color-border'],
- },
- radioDisabledUnchecked: {
- backgroundColor: colorVars['--color-background-muted'],
- },
- innerDot: {
- borderRadius: '50%',
- backgroundColor: {
- default: colorVars['--color-on-accent'],
- // Forced colors (Windows High Contrast) strips painted backgrounds,
- // which would make the selected dot invisible — checked and unchecked
- // radios would look identical. CanvasText keeps the dot perceivable on
- // the Canvas circle fill (WCAG 1.4.11).
- '@media (forced-colors: active)': 'CanvasText',
- },
+ // Holds only the indicator, so the focus ring has one unambiguous target.
+ indicatorSlot: {
+ display: 'contents',
},
labelDisabled: {
color: colorVars['--color-text-disabled'],
@@ -145,28 +76,6 @@ const wrapperSizeStyles = stylex.create({
},
});
-const radioSizeStyles = stylex.create({
- sm: {
- width: 20,
- height: 20,
- },
- md: {
- width: 24,
- height: 24,
- },
-});
-
-const dotSizeStyles = stylex.create({
- sm: {
- width: 8,
- height: 8,
- },
- md: {
- width: 10,
- height: 10,
- },
-});
-
const embeddedStyles = stylex.create({
root: {
paddingBlock: 0,
@@ -248,14 +157,18 @@ export function RadioListItem({
context.hasDisabledMessage && !isItemDisabled;
const isChecked = context.value === value;
const size = context.size;
+ // The radio visual is an indicator: a theme can restyle it through the
+ // `radio` / `radio-dot` targets or replace the component outright.
+ const RadioControl = useIndicator('radio');
+ // See CheckboxInput: the ring goes on the indicator's own element, because
+ // the native input is visually hidden and only the indicator knows its shape.
+ const indicatorRef = useRef<HTMLSpanElement>(null);
+ const {focusProps} = useIndicatorFocusRing(indicatorRef, isDisabled);
const radioCircle = (
<div
- {...stylex.props(
- styles.radioWrapper,
- wrapperSizeStyles[size],
- !isDisabled && styles.radioWrapperFocus,
- )}>
+ {...stylex.props(styles.radioWrapper, wrapperSizeStyles[size])}
+ {...focusProps}>
<input
id={id}
type="radio"
@@ -282,31 +195,13 @@ export function RadioListItem({
isDisabled && styles.inputDisabled,
)}
/>
- <div
- aria-hidden="true"
- {...mergeProps(
- themeProps('radio', {
- size,
- checked: isChecked ? 'checked' : null,
- disabled: isDisabled ? 'disabled' : null,
- }),
- stylex.props(
- styles.radio,
- radioSizeStyles[size],
- isChecked ? styles.radioChecked : styles.radioUnchecked,
- isDisabled && styles.radioDisabled,
- isDisabled && !isChecked && styles.radioDisabledUnchecked,
- ),
- )}>
- {isChecked && (
- <div
- {...mergeProps(
- themeProps('radio-dot', {size}),
- stylex.props(styles.innerDot, dotSizeStyles[size]),
- )}
- />
- )}
- </div>
+ <span ref={indicatorRef} {...stylex.props(styles.indicatorSlot)}>
+ <RadioControl
+ state={isChecked ? 'checked' : 'unchecked'}
+ size={size}
+ isDisabled={isDisabled}
+ />
+ </span>
</div>
);
@@ -325,7 +220,13 @@ export function RadioListItem({
ref={ref}
{...mergeProps(
themeProps('radio-list-item'),
- stylex.props(styles.container, !isDisabled && radioScope, xstyle),
+ stylex.props(
+ styles.container,
+ // Hover reaches the radio visual through this ancestor marker rather
+ // than props, so hovering the row tints the control.
+ !isDisabled && indicatorScope,
+ xstyle,
+ ),
className,
style,
)}
diff --git a/packages/core/src/RadioList/radio.markers.stylex.ts b/packages/core/src/RadioList/radio.markers.stylex.ts
deleted file mode 100644
index 1fcfe86e47..0000000000
--- a/packages/core/src/RadioList/radio.markers.stylex.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-import * as stylex from '@stylexjs/stylex';
-
-/**
- * Scoped marker for RadioListItem ancestor selectors.
- * Prevents hover styles from leaking from parent containers.
- */
-export const radioScope: ReturnType<typeof stylex.defineMarker> =
- stylex.defineMarker();
diff --git a/packages/core/src/Selector/Selector.test.tsx b/packages/core/src/Selector/Selector.test.tsx
index 476e0b9b3e..ab6162dbea 100644
--- a/packages/core/src/Selector/Selector.test.tsx
+++ b/packages/core/src/Selector/Selector.test.tsx
@@ -22,9 +22,11 @@ import {useState} from 'react';
import {Selector} from './Selector';
import {SelectorOption} from './SelectorOption';
import {Icon} from '../Icon';
+import {RadioIndicator} from '../Indicator';
import {InputGroup, InputGroupText} from '../InputGroup';
import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';
import {defineTheme} from '../theme/defineTheme';
+import {Theme} from '../theme/Theme';
import {generateThemeCSS} from '../theme/generateThemeRules';
function generateThemeTestCSS(theme: Parameters<typeof generateThemeCSS>[0]) {
@@ -236,6 +238,60 @@ describe('Selector', () => {
expect(screen.getByRole('combobox')).toHaveTextContent('Banana');
});
+ it('draws the selected mark through the check indicator', () => {
+ render(
+ <Selector
+ label="Fruit"
+ options={OPTIONS}
+ value="Banana"
+ onChange={() => {}}
+ />,
+ );
+
+ const selected = screen.getByRole('option', {name: /Banana/, hidden: true});
+ // The default check indicator IS the glyph — no wrapper element, so the
+ // host's theme target sits on the same node as astryx-icon.
+ const mark = selected.querySelector('.astryx-selector-check');
+ expect(mark).not.toBeNull();
+ expect(mark).toHaveClass('astryx-icon');
+ });
+
+ it('lets a theme replace the mark with a radio, which draws when unselected too', () => {
+ // The point of the indicator layer: one theme entry, and every
+ // single-selection mark becomes a radio — including the empty circle on
+ // rows that are NOT selected, which a check-only mark never drew.
+ const theme = defineTheme({
+ name: 'selector-radio-mark-test',
+ indicators: {check: RadioIndicator},
+ });
+
+ render(
+ <Theme theme={theme}>
+ <Selector
+ label="Fruit"
+ options={OPTIONS}
+ value="Banana"
+ onChange={() => {}}
+ />
+ </Theme>,
+ );
+
+ const options = screen.getAllByRole('option', {hidden: true});
+ expect(options.length).toBeGreaterThan(1);
+
+ // Every row has a radio, selected or not.
+ for (const option of options) {
+ expect(option.querySelector('.astryx-radio')).not.toBeNull();
+ }
+
+ // And exactly the selected one is filled.
+ const filled = options.filter(
+ o => o.querySelector('.astryx-radio-dot') != null,
+ );
+ expect(filled).toHaveLength(1);
+ expect(filled[0]).toHaveTextContent('Banana');
+ });
+
it('renders custom option endContent', async () => {
const user = userEvent.setup();
render(
@@ -2385,7 +2441,9 @@ describe('Selector selected-marker theme target (selector-check)', () => {
o => o.getAttribute('aria-selected') !== 'true',
);
for (const row of unselected) {
- expect(row.querySelector('.astryx-selector-check')).not.toBeInTheDocument();
+ expect(
+ row.querySelector('.astryx-selector-check'),
+ ).not.toBeInTheDocument();
}
});
diff --git a/packages/core/src/Selector/Selector.tsx b/packages/core/src/Selector/Selector.tsx
index 1acafe2f4a..dbf74b0d4e 100644
--- a/packages/core/src/Selector/Selector.tsx
+++ b/packages/core/src/Selector/Selector.tsx
@@ -32,6 +32,7 @@ import * as stylex from '@stylexjs/stylex';
import {usePopover} from '../Popover/usePopover';
import {useTooltip} from '../Tooltip';
import {Icon, renderIconSlot, type IconType} from '../Icon';
+import {useIndicator} from '../Indicator';
import type {IconName} from '../Icon';
import {
Field,
@@ -1091,6 +1092,11 @@ export function Selector<T extends SelectorOptionType>(
t,
]);
+ // The single-selection mark, resolved from the theme once per render. A
+ // theme that maps `check` to another indicator (a radio, say) changes every
+ // selected-option mark in the app through this one lookup.
+ const SelectionMark = useIndicator('check');
+
// Render an individual item
const renderItem = useCallback(
(item: SelectorOptionData, flatIndex: number) => {
@@ -1120,17 +1126,21 @@ export function Selector<T extends SelectorOptionType>(
<DefaultOption option={item} />
)}
</span>
- {isSelected && (
- <Icon
- icon="check"
- size="sm"
- color="accent"
- // Stable theme target on the selected-row marker, so a theme can
- // restyle or hide it (e.g. to compose its own selected indicator
- // via renderOption) without a structural sibling selector.
- {...themeProps('selector-check')}
- />
- )}
+ {/*
+ * Rendered UNCONDITIONALLY, with the state passed down: the default
+ * check draws nothing when unchecked, but a theme that replaces the
+ * `check` indicator with a radio needs the unselected state to draw
+ * its empty circle. `{isSelected && …}` would make that impossible.
+ *
+ * `selector-check` stays the stable target for the mark's position
+ * in the row; the indicator owns what the mark looks like.
+ */}
+ <SelectionMark
+ state={isSelected ? 'checked' : 'unchecked'}
+ size="sm"
+ isDisabled={item.disabled ?? false}
+ {...themeProps('selector-check')}
+ />
</div>
);
},
@@ -1142,6 +1152,7 @@ export function Selector<T extends SelectorOptionType>(
getItemId,
onItemSelect,
onItemMouseEnter,
+ SelectionMark,
],
);
@@ -1347,50 +1358,50 @@ export function Selector<T extends SelectorOptionType>(
the two affordances stop sharing a node.
*/}
{showStatusIcon ? (
- showStatusTooltip ? (
- <button
- ref={statusTooltip.ref}
- type="button"
- aria-label={t(STATUS_BUTTON_LABEL_KEY[status.type])}
- aria-describedby={statusTooltip.describedBy}
- onClick={e => e.stopPropagation()}
- {...stylex.props(styles.statusButton)}>
- <Icon
- icon={STATUS_ICON_MAP[status.type]}
- size="sm"
- color={STATUS_ICON_COLOR_MAP[status.type]}
- xstyle={styles.triggerIcon}
- />
- </button>
- ) : (
+ showStatusTooltip ? (
+ <button
+ ref={statusTooltip.ref}
+ type="button"
+ aria-label={t(STATUS_BUTTON_LABEL_KEY[status.type])}
+ aria-describedby={statusTooltip.describedBy}
+ onClick={e => e.stopPropagation()}
+ {...stylex.props(styles.statusButton)}>
<Icon
icon={STATUS_ICON_MAP[status.type]}
size="sm"
color={STATUS_ICON_COLOR_MAP[status.type]}
xstyle={styles.triggerIcon}
/>
- )
+ </button>
) : (
<Icon
- icon="chevronDown"
+ icon={STATUS_ICON_MAP[status.type]}
size="sm"
- color="secondary"
- // The rotation rides on the glyph, alongside the box and color
- // the wrapper used to provide, so one element carries the mark,
- // its open/closed transform, and the theme target.
- xstyle={[
- styles.triggerIcon,
- styles.triggerIconRotation,
- popover.isOpen && styles.triggerIconOpen,
- ]}
- // Stable theme target on the chevron glyph itself, so a theme can
- // restyle just this icon (color, size, hover) — and its
- // open/closed state — via `defineTheme`. Same-element rules in
- // @layer astryx-theme win over the icon's own base color/size,
- // which a button-level target could not reach.
- {...themeProps('selector-indicator-icon', {
- state: popover.isOpen ? 'expanded' : 'collapsed',
- })}
+ color={STATUS_ICON_COLOR_MAP[status.type]}
+ xstyle={styles.triggerIcon}
+ />
+ )
+ ) : (
+ <Icon
+ icon="chevronDown"
+ size="sm"
+ color="secondary"
+ // The rotation rides on the glyph, alongside the box and color
+ // the wrapper used to provide, so one element carries the mark,
+ // its open/closed transform, and the theme target.
+ xstyle={[
+ styles.triggerIcon,
+ styles.triggerIconRotation,
+ popover.isOpen && styles.triggerIconOpen,
+ ]}
+ // Stable theme target on the chevron glyph itself, so a theme can
+ // restyle just this icon (color, size, hover) — and its
+ // open/closed state — via `defineTheme`. Same-element rules in
+ // @layer astryx-theme win over the icon's own base color/size,
+ // which a button-level target could not reach.
+ {...themeProps('selector-indicator-icon', {
+ state: popover.isOpen ? 'expanded' : 'collapsed',
+ })}
/>
)}
</div>
diff --git a/packages/core/src/hooks/index.ts b/packages/core/src/hooks/index.ts
index 69e16d5f6a..90fdda38de 100644
--- a/packages/core/src/hooks/index.ts
+++ b/packages/core/src/hooks/index.ts
@@ -92,6 +92,7 @@ export {useLongPress} from './useLongPress';
export type {UseLongPressOptions, UseLongPressHandlers} from './useLongPress';
export {useDevWarning} from './useDevWarning';
+export {useIndicatorFocusRing} from './useIndicatorFocusRing';
export {useContainerReveal} from './useContainerReveal';
export type {
diff --git a/packages/core/src/hooks/useIndicatorFocusRing.tsx b/packages/core/src/hooks/useIndicatorFocusRing.tsx
new file mode 100644
index 0000000000..44b5af3ef3
--- /dev/null
+++ b/packages/core/src/hooks/useIndicatorFocusRing.tsx
@@ -0,0 +1,121 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file useIndicatorFocusRing.tsx
+ * @input A ref to the element wrapping only the indicator
+ * @output Focus handlers that draw the standard ring on the indicator itself
+ * @position Used by controls whose focusable input is visually hidden
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/hooks/index.ts (exports)
+ *
+ * A checkbox or radio focuses a native `<input>` that is `opacity: 0`, so the
+ * visible focus indicator has to appear on the picture beside it — and that
+ * picture is a themeable indicator, which is what makes "who draws the ring"
+ * awkward:
+ *
+ * - Only the indicator's own element can shape the ring: `outline` follows
+ * that element's `border-radius`. Draw it on a wrapper and the owner has to
+ * hardcode a guess about whatever indicator it hosts (RadioListItem used to
+ * carry `border-radius: 50%` for a circle it did not own).
+ * - But an indicator supplied by a theme is third-party code. If drawing the
+ * ring is its job, a replacement that simply doesn't ships a control with no
+ * visible focus (WCAG 2.4.7) — and that is the DEFAULT outcome: the sample
+ * replacement in our own Storybook destructures `{state, size, isDisabled}`
+ * and drops the rest, which is what a theme author plausibly writes. Nothing
+ * can enforce otherwise; a component ignoring every prop is still assignable
+ * to `IndicatorComponent`, and branding the return type does not work either
+ * (JSX types every expression as `JSX.Element`).
+ *
+ * So the owner draws it, on the indicator's own element, imperatively at focus
+ * time. No cooperation is required and none can be forgotten.
+ *
+ * Two details that are load-bearing, both measured rather than assumed:
+ *
+ * 1. **Inline style, not a class.** React replaces `className` wholesale on
+ * re-render, so an injected class disappears the moment the control changes
+ * state — pressing Space on a focused checkbox lost the ring. React
+ * reconciles `style` per property, so an `outline` set here survives.
+ * 2. **`:focus-visible`, not `:focus`.** The CSS this replaces got
+ * keyboard-vs-pointer for free; an event handler has to ask. Checking the
+ * element keeps the browser's heuristic, including `focus({focusVisible:
+ * true})`, which a hand-rolled modality guess would miss.
+ *
+ * Imperative styling on an interaction event follows `useTableSelection`,
+ * which sets row-selection styles the same way.
+ */
+
+import {useCallback, useMemo} from 'react';
+import type {FocusEvent, RefObject} from 'react';
+import {
+ FOCUS_OUTLINE_PARTS,
+ FOCUS_OUTLINE_PARTS_NONE,
+} from '../utils/focusOutline.stylex';
+
+export interface UseIndicatorFocusRingReturn {
+ /** Spread onto the element that owns the focusable input. */
+ focusProps: {
+ onFocus: (event: FocusEvent<HTMLElement>) => void;
+ onBlur: () => void;
+ };
+}
+
+/**
+ * Draw the standard focus ring on the indicator inside `containerRef`, shaped
+ * by whatever that indicator actually is.
+ *
+ * @param containerRef - Wraps ONLY the indicator, so its single element child
+ * is unambiguously the thing to ring, whatever a theme renders there.
+ * @param isDisabled - Skip the ring; a disabled control is not focusable.
+ *
+ * @example
+ * ```tsx
+ * const indicatorRef = useRef<HTMLSpanElement>(null);
+ * const {focusProps} = useIndicatorFocusRing(indicatorRef, isDisabled);
+ *
+ * <div {...focusProps}>
+ * <input type="checkbox" />
+ * <span ref={indicatorRef}><Indicator state={…} /></span>
+ * </div>
+ * ```
+ */
+export function useIndicatorFocusRing(
+ containerRef: RefObject<HTMLElement | null>,
+ isDisabled = false,
+): UseIndicatorFocusRingReturn {
+ const paint = useCallback(
+ (on: boolean) => {
+ // `firstElementChild`, not a search: the container holds the indicator
+ // and nothing else, so there is no ambiguity — and no way for a later
+ // sibling to quietly become the target.
+ const indicator = containerRef.current?.firstElementChild;
+ if (indicator instanceof HTMLElement) {
+ Object.assign(
+ indicator.style,
+ on ? FOCUS_OUTLINE_PARTS : FOCUS_OUTLINE_PARTS_NONE,
+ );
+ }
+ },
+ [containerRef],
+ );
+
+ const onFocus = useCallback(
+ (event: FocusEvent<HTMLElement>) => {
+ if (isDisabled) {
+ return;
+ }
+ const target = event.target;
+ if (target instanceof HTMLElement && !target.matches(':focus-visible')) {
+ return;
+ }
+ paint(true);
+ },
+ [isDisabled, paint],
+ );
+
+ const onBlur = useCallback(() => paint(false), [paint]);
+
+ return useMemo(() => ({focusProps: {onFocus, onBlur}}), [onFocus, onBlur]);
+}
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 5a3f342ac9..9fafdc9550 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -68,6 +68,7 @@ export * from './SelectableCard';
export * from './Selector';
export * from './MultiSelector';
export * from './Icon';
+export * from './Indicator';
export * from './InputGroup';
export * from './Item';
export * from './Text';
diff --git a/packages/core/src/theme/defineTheme.ts b/packages/core/src/theme/defineTheme.ts
index 08c19f477f..d670cea31f 100644
--- a/packages/core/src/theme/defineTheme.ts
+++ b/packages/core/src/theme/defineTheme.ts
@@ -31,6 +31,7 @@
*/
import type {IconRegistry} from '../Icon/globalIconRegistry';
+import type {IndicatorRegistry} from '../Indicator/types';
import type {TypographyConfig, FontWeight} from './types';
import {
resolveOnMedia,
@@ -280,6 +281,19 @@ export interface DefineThemeInput {
components?: ComponentStyleMap;
/** Icon registry — maps semantic icon names to React nodes */
icons?: Partial<IconRegistry>;
+ /**
+ * Indicator overrides — replaces the components that draw stateful control
+ * visuals with the theme's own, by name.
+ *
+ * Replacement is by indicator name, not per call site, so a single entry
+ * reaches every component that draws that indicator: mapping `check` to
+ * `RadioIndicator` gives radio visuals to every single-selection mark in the
+ * app.
+ *
+ * Each entry is checked against its indicator's family, so a replacement
+ * must accept the states that family passes.
+ */
+ indicators?: IndicatorRegistry;
/**
* Default syntax highlighting theme for code components.
* Sets --color-syntax-* tokens at the theme root. Can be overridden
@@ -329,6 +343,8 @@ export interface DefinedTheme {
components?: ComponentStyleMap;
/** Icon registry */
icons?: Partial<IconRegistry>;
+ /** Indicator overrides for stateful control visuals, keyed by name */
+ indicators?: IndicatorRegistry;
/** Whether this theme has been pre-compiled by theme build CLI */
__built?: true;
/**
@@ -622,11 +638,19 @@ export function defineTheme(input: DefineThemeInput): DefinedTheme {
? {...base.icons, ...input.icons}
: (input.icons ?? base?.icons);
+ // Indicator overrides merge by name, like icons: a child theme replacing one
+ // indicator keeps the ones its base replaced.
+ const indicators =
+ input.indicators && base?.indicators
+ ? {...base.indicators, ...input.indicators}
+ : (input.indicators ?? base?.indicators);
+
const theme: DefinedTheme = {
name: input.name,
tokens,
components,
icons,
+ indicators,
__inputTokens: input.tokens,
__onDark,
__onLight,
diff --git a/packages/core/src/theme/index.ts b/packages/core/src/theme/index.ts
index dda4fce9f3..90b6d3bbf4 100644
--- a/packages/core/src/theme/index.ts
+++ b/packages/core/src/theme/index.ts
@@ -130,6 +130,19 @@ export type {
export {useTheme, useThemeName, ThemeContext} from './useTheme';
export type {UseThemeReturn, ThemeContextValue} from './useTheme';
+
+export type {
+ IndicatorComponent,
+ IndicatorFamily,
+ IndicatorFamilyMap,
+ IndicatorMap,
+ IndicatorName,
+ IndicatorNameOfFamily,
+ IndicatorProps,
+ IndicatorRegistry,
+ IndicatorSize,
+ IndicatorState,
+} from '../Indicator';
export {
resolveThemeToken,
resolveThemeTokens,
diff --git a/packages/core/src/utils/focusOutline.stylex.ts b/packages/core/src/utils/focusOutline.stylex.ts
index b0861a24e5..9b32dababa 100644
--- a/packages/core/src/utils/focusOutline.stylex.ts
+++ b/packages/core/src/utils/focusOutline.stylex.ts
@@ -44,6 +44,41 @@ const focusOutlineLonghands = {
outlineColor: FOCUS_OUTLINE_COLOR,
} as const;
+/**
+ * The standard focus ring as plain CSS values, for the one case that has to
+ * apply it imperatively: a control whose focusable input is visually hidden and
+ * whose ring must land on a *themeable indicator* beside it (see
+ * `useIndicatorFocusRing`). Everything else should use the styles above.
+ *
+ * Longhands, not the `outline` shorthand, for the same reason the styles are:
+ * a shorthand resets every longhand it covers, so a caller could not re-color
+ * the ring without restating its width and style. Split, each part is
+ * independently overridable — and `--color-accent` stays a var, so a theme's
+ * accent still flows through.
+ *
+ * Keys are camelCase to match `HTMLElement.style`, so this spreads straight
+ * onto an element:
+ *
+ * ```ts
+ * Object.assign(el.style, FOCUS_OUTLINE_PARTS); // draw
+ * Object.assign(el.style, FOCUS_OUTLINE_PARTS_NONE); // clear
+ * ```
+ */
+export const FOCUS_OUTLINE_PARTS = {
+ outlineWidth: FOCUS_OUTLINE_WIDTH,
+ outlineStyle: 'solid',
+ outlineColor: FOCUS_OUTLINE_COLOR,
+ outlineOffset: FOCUS_OUTLINE_OFFSET,
+} as const;
+
+/** Clears {@link FOCUS_OUTLINE_PARTS}, one key per part so nothing lingers. */
+export const FOCUS_OUTLINE_PARTS_NONE = {
+ outlineWidth: '',
+ outlineStyle: '',
+ outlineColor: '',
+ outlineOffset: '',
+} as const;
+
export const focusOutlineStyles = stylex.create({
focusVisible: {
outlineWidth: {
diff --git a/packages/core/src/utils/themeProps.ts b/packages/core/src/utils/themeProps.ts
index 925ea01e29..d5e01f579b 100644
--- a/packages/core/src/utils/themeProps.ts
+++ b/packages/core/src/utils/themeProps.ts
@@ -73,9 +73,7 @@ function buildClassName(component: string, props?: ClassProps): string {
* literal prop values, including numeric values (`level: 1` → `data-level="1"`).
* Nullish values are omitted.
*/
-export function themeDataAttributes(
- props?: ClassProps,
-): ThemeDataAttributes {
+export function themeDataAttributes(props?: ClassProps): ThemeDataAttributes {
const attrs: ThemeDataAttributes = {};
if (props) {
@@ -102,12 +100,36 @@ export function themeDataAttributes(
* // → { className: 'astryx-button primary sm', data-variant: 'primary', data-size: 'sm' }
* ```
*/
+/**
+ * Options for {@link themeProps}.
+ */
+export type ThemePropsOptions = {
+ /**
+ * Stable class names to emit ALONGSIDE the component's own, for targets that
+ * have been renamed.
+ *
+ * A theme target is public API: renaming one silently breaks every theme
+ * that styles it. Emitting the old name beside the new one keeps those
+ * themes working through a deprecation window, at the cost of one extra
+ * class on the element until the old name is dropped in a major.
+ *
+ * Pass plain string literals — the theming guards scan for them statically.
+ * Document the old name with `deprecated` in the component's
+ * `theming.targets` so the docsite says which to use.
+ */
+ legacyNames?: ReadonlyArray<string>;
+};
+
export function themeProps(
component: string,
props?: ClassProps,
+ options?: ThemePropsOptions,
): ThemeProps {
+ const className = buildClassName(component, props);
+ const legacy = options?.legacyNames?.map(name => stableClassName(name)) ?? [];
+
return {
- className: buildClassName(component, props),
+ className: legacy.length > 0 ? [className, ...legacy].join(' ') : className,
...themeDataAttributes(props),
};
}