An open source design system that's fully customizable and agent ready
TypeScript
fix(indicator): close the six audit blocks on the indicator layer (#4890)
Cindy Zhangb4ec1168435f
diff --git a/.changeset/remove-dropdown-menu-radio-dot-target.md b/.changeset/remove-dropdown-menu-radio-dot-target.mdnew file mode 100644index 0000000000..bb389fa9d4--- /dev/null+++ b/.changeset/remove-dropdown-menu-radio-dot-target.md@@ -0,0 +1,9 @@+---+'@astryxdesign/core': minor+---++[breaking] Remove the `dropdown-menu-radio-dot` theme target. Menu radio rows draw the shared radio indicator now, so the dot is the indicator's dot: target `radio-indicator-dot` (the legacy `radio-dot` name still matches it too). The row's circle keeps its `dropdown-menu-radio` target, so only the dot moved.++Runtime themes are not validated — a theme keyed on the removed target keeps compiling and silently stops matching — so `astryx upgrade` now carries `rename-dropdown-menu-radio-dot-target`, which rewrites the key and the `astryx-dropdown-menu-radio-dot` class. The new target is app-wide rather than menu-only (there is no menu-only dot element left to address), so the codemod leaves a TODO at each site it rewrites.++@cixzhangdiff --git a/.changeset/themeable-indicators.md b/.changeset/themeable-indicators.mdindex 01ec948663..2a8ac40323 100644--- a/.changeset/themeable-indicators.md+++ b/.changeset/themeable-indicators.md@@ -7,6 +7,6 @@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`.+Migration: menu radios use those shared targets now. `dropdown-menu-radio-dot` is removed — target `radio-indicator-dot`; `astryx upgrade` rewrites it for you.@cixzhangdiff --git a/packages/cli/assets/codemods/transforms/next/__tests__/next-codemods.test.mjs b/packages/cli/assets/codemods/transforms/next/__tests__/next-codemods.test.mjsnew file mode 100644index 0000000000..16fdc850b3--- /dev/null+++ b/packages/cli/assets/codemods/transforms/next/__tests__/next-codemods.test.mjs@@ -0,0 +1,92 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Unit tests for the staged (next-release) codemods.+ *+ * Mirrors v0.3.0/__tests__/next-codemods.test.mjs, which covers the codemods+ * after promotion. Keeping a copy here means a staged transform is tested from+ * the day it is written rather than the day it is released.+ */++import {describe, expect, it} from 'vitest';+import jscodeshift from 'jscodeshift';++const j = jscodeshift.withParser('tsx');+const api = {jscodeshift: j, stats: () => {}, report: () => {}};++async function apply(name, source) {+ const {default: transform} = await import(`../${name}.mjs`);+ return transform({source, path: 'test.tsx'}, api) ?? source;+}++const TRANSFORM = 'rename-dropdown-menu-radio-dot-target';++describe('rename-dropdown-menu-radio-dot-target', () => {+ it('renames the theme target key in a defineTheme components map', async () => {+ const input = `import {defineTheme} from '@astryxdesign/core/theme';+export const theme = defineTheme({+ name: 'brand',+ components: {+ 'dropdown-menu-radio-dot': {base: {backgroundColor: 'var(--color-accent)'}},+ },+});`;+ const output = await apply(TRANSFORM, input);+ expect(output).toContain("'radio-indicator-dot':");+ // The old name survives only inside the TODO comment the rename attaches.+ expect(output).not.toContain("'dropdown-menu-radio-dot':");+ });++ it('warns that the new target is app-wide, not menu-only', async () => {+ const input = `const components = {+ 'dropdown-menu-radio-dot': {base: {width: '10px'}},+};`;+ const output = await apply(TRANSFORM, input);+ // The rename cannot preserve scope — there is no menu-only dot element+ // left — so the author has to decide, and must be told.+ expect(output).toContain('TODO(astryx upgrade)');+ expect(output).toContain('EVERY radio dot');+ });++ it('renames the rendered class inside a selector string', async () => {+ const input = `const sel = '.astryx-dropdown-menu-radio-dot';+const nested = '.astryx-dropdown-menu-radio .astryx-dropdown-menu-radio-dot';`;+ const output = await apply(TRANSFORM, input);+ expect(output).toContain("'.astryx-radio-indicator-dot'");+ expect(output).toContain(+ '.astryx-dropdown-menu-radio .astryx-radio-indicator-dot',+ );+ });++ it('renames the class inside a template literal', async () => {+ const input =+ 'const css = `.astryx-dropdown-menu-radio-dot { background: ${c}; }`;';+ const output = await apply(TRANSFORM, input);+ expect(output).toContain('.astryx-radio-indicator-dot {');+ expect(output).not.toContain('astryx-dropdown-menu-radio-dot');+ });++ it('leaves the surviving dropdown-menu-radio target alone', async () => {+ // Only the DOT target was removed; the circle still carries the+ // menu-specific target, so a theme keyed on it must not be rewritten.+ const input = `const components = {+ 'dropdown-menu-radio': {base: {borderWidth: '2px'}},+};`;+ const output = await apply(TRANSFORM, input);+ expect(output).toContain("'dropdown-menu-radio'");+ expect(output).not.toContain('radio-indicator');+ expect(output).not.toContain('TODO(astryx upgrade)');+ });++ it('is a no-op on files that never mention the target', async () => {+ const input = `const components = {button: {base: {fontWeight: '600'}}};`;+ expect(await apply(TRANSFORM, input)).toBe(input);+ });++ it('is idempotent', async () => {+ const input = `const components = {+ 'dropdown-menu-radio-dot': {base: {width: '10px'}},+};`;+ const once = await apply(TRANSFORM, input);+ expect(await apply(TRANSFORM, once)).toBe(once);+ });+});diff --git a/packages/cli/assets/codemods/transforms/next/index.mjs b/packages/cli/assets/codemods/transforms/next/index.mjsindex 2af3bdfcf0..8cb6e0a141 100644--- a/packages/cli/assets/codemods/transforms/next/index.mjs+++ b/packages/cli/assets/codemods/transforms/next/index.mjs@@ -7,4 +7,14 @@* this file into the resolved version folder.*/-export default [];+import renameDropdownMenuRadioDotTarget, {+ meta as renameDropdownMenuRadioDotTargetMeta,+} from './rename-dropdown-menu-radio-dot-target.mjs';++export default [+ {+ name: 'rename-dropdown-menu-radio-dot-target',+ transform: renameDropdownMenuRadioDotTarget,+ meta: renameDropdownMenuRadioDotTargetMeta,+ },+];diff --git a/packages/cli/assets/codemods/transforms/next/rename-dropdown-menu-radio-dot-target.mjs b/packages/cli/assets/codemods/transforms/next/rename-dropdown-menu-radio-dot-target.mjsnew file mode 100644index 0000000000..d12a731c13--- /dev/null+++ b/packages/cli/assets/codemods/transforms/next/rename-dropdown-menu-radio-dot-target.mjs@@ -0,0 +1,152 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Codemod: rename the removed `dropdown-menu-radio-dot` theme target+ *+ * The menu radio's dot is no longer drawn by DropdownMenuRadioItem. That row+ * now renders the shared radio indicator, so its dot is the indicator's dot and+ * carries `radio-indicator-dot` (plus the legacy `radio-dot`) instead of the+ * menu-specific `dropdown-menu-radio-dot`, which is gone.+ *+ * Runtime themes are not validated: a theme keyed on the old target keeps+ * compiling and simply stops matching, with no error anywhere. That silence is+ * why this rename needs a codemod rather than a changelog line.+ *+ * The rename is NOT scope-preserving, and that cannot be fixed here — there is+ * no menu-only dot element left to address. `radio-indicator-dot` reaches every+ * radio dot in the app, including RadioList's. So every rewritten site also+ * gets a TODO comment (api.report is a stub; comments are the only warning+ * channel) telling the author to check whether the rule was meant to be+ * menu-only, and pointing at the containing-target route if it was.+ */++export const meta = {+ title: 'Rename the removed dropdown-menu-radio-dot theme target',+ description:+ 'Renames the `dropdown-menu-radio-dot` theme target (and the ' ++ '`astryx-dropdown-menu-radio-dot` class it rendered) to ' ++ '`radio-indicator-dot` / `astryx-radio-indicator-dot`. Menu radios draw ' ++ 'the shared radio indicator now, so the menu-specific dot target no ' ++ 'longer exists. The new target is app-wide rather than menu-only, so each ' ++ 'rewritten site gets a TODO comment to confirm that widening is intended.',+ pr: '#4712',+};++const OLD_TARGET = 'dropdown-menu-radio-dot';+const NEW_TARGET = 'radio-indicator-dot';+const OLD_CLASS = `astryx-${OLD_TARGET}`;+const NEW_CLASS = `astryx-${NEW_TARGET}`;++const TODO_COMMENT =+ ' TODO(astryx upgrade): `dropdown-menu-radio-dot` became `radio-indicator-dot`,' ++ ' which styles EVERY radio dot, not just the ones in a menu. If this rule was' ++ ' meant to be menu-only, scope it under the containing `dropdown-menu-radio`' ++ ' target instead of this one. ';++/**+ * Rewrite one string value, or return null when it holds nothing to rename.+ *+ * Handles the target name on its own (a theme's `components` key) and the+ * rendered class inside a larger string (a selector such as+ * `.astryx-dropdown-menu-radio-dot`, or a className list).+ *+ * @param {string} value+ * @returns {string | null}+ */+function renameIn(value) {+ if (value === OLD_TARGET) {+ return NEW_TARGET;+ }+ if (value.includes(OLD_CLASS)) {+ return value.split(OLD_CLASS).join(NEW_CLASS);+ }+ return null;+}++/**+ * @param {import('../../../../authoring/codemod/type').AstryxCodemodFile} file+ * @param {import('../../../../authoring/codemod/type').CodemodTransformApi} api+ * @returns {string | null | undefined}+ */+export default function transformer(file, api) {+ // Cheap bail-out: most files in a consumer repo mention neither name.+ if (!file.source.includes(OLD_TARGET)) {+ return undefined;+ }++ const j = api.jscodeshift;+ const root = j(file.source);+ let hasChanges = false;++ /** Attach the widening warning once to the nearest statement-ish node. */+ function attachTodo(/** @type {any} */ path) {+ // The property (or its statement) reads better than the bare literal, and+ // matches where a human would look for the note.+ const host =+ path.parent?.node?.type === 'ObjectProperty' ||+ path.parent?.node?.type === 'Property'+ ? path.parent.node+ : path.node;+ if (!host.comments) {+ host.comments = [];+ }+ if (+ host.comments.some((/** @type {any} */ c) => c.value === TODO_COMMENT)+ ) {+ return;+ }+ host.comments.push(j.commentBlock(TODO_COMMENT, true, false));+ }++ root+ .find(j.StringLiteral)+ .forEach((/** @type {any} */ path) => {+ const renamed = renameIn(path.node.value);+ if (renamed == null) {+ return;+ }+ path.node.value = renamed;+ attachTodo(path);+ hasChanges = true;+ });++ // Older parsers surface string literals as `Literal`.+ root.find(j.Literal).forEach((/** @type {any} */ path) => {+ if (typeof path.node.value !== 'string') {+ return;+ }+ const renamed = renameIn(path.node.value);+ if (renamed == null) {+ return;+ }+ path.node.value = renamed;+ if (typeof path.node.raw === 'string') {+ path.node.raw = path.node.raw+ .split(OLD_TARGET)+ .join(NEW_TARGET);+ }+ attachTodo(path);+ hasChanges = true;+ });++ // Template literals carry the class in CSS strings: `.${OLD_CLASS} > span`.+ root.find(j.TemplateElement).forEach((/** @type {any} */ path) => {+ const cooked = path.node.value?.cooked;+ if (typeof cooked !== 'string') {+ return;+ }+ const renamed = renameIn(cooked);+ if (renamed == null) {+ return;+ }+ path.node.value.cooked = renamed;+ path.node.value.raw = path.node.value.raw+ .split(OLD_CLASS)+ .join(NEW_CLASS)+ .split(OLD_TARGET)+ .join(NEW_TARGET);+ hasChanges = true;+ });++ return hasChanges ? root.toSource({quote: 'single'}) : undefined;+}diff --git a/packages/core/src/Indicator/CheckIndicator.tsx b/packages/core/src/Indicator/CheckIndicator.tsxindex 8942b72ace..1223792f13 100644--- a/packages/core/src/Indicator/CheckIndicator.tsx+++ b/packages/core/src/Indicator/CheckIndicator.tsx@@ -29,8 +29,10 @@* is an icon, and `astryx-icon` plus the host's target already reach it.*/+import * as stylex from '@stylexjs/stylex';import type {SVGProps} from 'react';import {Icon} from '../Icon/Icon';+import {mergeProps} from '../utils';import type {IndicatorProps} from './types';/** The check glyph matches the control sizes the indicator families share. */@@ -72,23 +74,35 @@ export function CheckIndicator({}: 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.+ // indicator's place, matching the other indicators' contract. It is checked+ // BEFORE `state`: a host passes a busy visual through in whatever state the+ // row happens to be in, and an unchecked listbox row is the common one.+ //+ // There is no glyph to hang the caller's props on in this branch, so they go+ // on a span — every one of them, so a `data-testid`, an `id`, a handler or+ // an `xstyle` behaves the same whether or not children are present.if (children != null) {return (- <span ref={ref} aria-hidden="true" className={className} style={style}>+ <span+ // Spread first, as on the glyph path below, so the indicator's own+ // contract (aria-hidden, and the styling it composes) outranks any+ // same-named attribute a caller passed through.+ {...rest}+ ref={ref}+ aria-hidden="true"+ {...mergeProps(stylex.props(xstyle), className, style)}>{children}</span>);}+ // Nothing to draw, and no box to reserve: an unmarked row keeps the layout+ // it would have without this indicator.+ if (!isChecked) {+ return null;+ }+return (<Icon// Spread first so the indicator's own contract (below) wins over anydiff --git a/packages/core/src/Indicator/Indicator.doc.mjs b/packages/core/src/Indicator/Indicator.doc.mjsindex c8f06af089..8371bf39ba 100644--- a/packages/core/src/Indicator/Indicator.doc.mjs+++ b/packages/core/src/Indicator/Indicator.doc.mjs@@ -85,7 +85,8 @@ export const docs = {{name: 'children',type: 'ReactNode',- description: 'Rendered INSTEAD of the mark.',+ description:+ 'Rendered INSTEAD of the mark, in every state — a host showing a pending Spinner passes it through whether or not the row is chosen.',},],},@@ -247,7 +248,7 @@ defineTheme({name: 'brand', indicators: {check: RadioIndicator}});`,{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.',+ 'Render a single root ELEMENT, and let it keep the border-radius you want the focus ring to follow. A control whose real input is visually hidden cannot show focus on that input, so the owner paints the standard ring onto the indicator element itself at focus time (useIndicatorFocusRing) — `outline` then picks up that element\'s radius. A replacement needs no cooperation and can forget nothing: the ring is never missing (WCAG 2.4.7), it is only the wrong shape if the root has no radius of its own. Do not draw a focus ring yourself; the owner already did.',},{guidance: false,@@ -257,7 +258,7 @@ defineTheme({name: 'brand', indicators: {check: RadioIndicator}});`,{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.',+ 'Assume you are only mounted when selected. The host renders its indicator unconditionally and passes `state`, in every state — that is what lets a replacement draw where the default draws nothing (a radio\'s empty circle on an unchosen row). Drawing nothing in a state is a decision the indicator makes, not one the host makes for it.',},],anatomy: [@@ -265,7 +266,7 @@ defineTheme({name: 'brand', indicators: {check: RadioIndicator}});`,name: 'Chrome',required: true,description:- 'The persistent box or circle, present in every state. Carries the astryx-checkbox / astryx-radio theme target.',+ 'The persistent box or circle, present in every state. Carries the astryx-checkbox-indicator / astryx-radio-indicator theme target (the pre-indicator astryx-checkbox / astryx-radio names are still emitted on the same element).',},{name: 'State mark',diff --git a/packages/core/src/Indicator/Indicator.test.tsx b/packages/core/src/Indicator/Indicator.test.tsxindex f44a561491..ab995e3991 100644--- a/packages/core/src/Indicator/Indicator.test.tsx+++ b/packages/core/src/Indicator/Indicator.test.tsx@@ -6,6 +6,7 @@ import type {PropsWithChildren, ReactNode} from 'react';import {Theme} from '../theme/Theme';import {defineTheme} from '../theme/defineTheme';import {CheckboxIndicator} from './CheckboxIndicator';+import {CheckIndicator} from './CheckIndicator';import {RadioIndicator} from './RadioIndicator';import {getIndicator} from './indicatorRegistry';import {useIndicator} from './useIndicator';@@ -66,6 +67,69 @@ describe('default indicators', () => {});});+/**+ * CheckIndicator is the one indicator that draws nothing in a state, which is+ * what makes it the default selection mark — and what made its two escape+ * hatches (props and children) easy to get wrong. Both are pinned here.+ */+describe('CheckIndicator', () => {+ it('draws the mark when checked and nothing when not', () => {+ const {container, rerender} = render(<CheckIndicator state="checked" />);++ const mark = container.querySelector('.astryx-icon');+ expect(mark).toBeInTheDocument();+ expect(mark).toHaveAttribute('aria-hidden', 'true');++ rerender(<CheckIndicator state="unchecked" />);+ // No empty box beside an unchosen row — the reason a check is the default.+ expect(container).toBeEmptyDOMElement();+ });++ it('renders children INSTEAD of the mark, in both states', () => {+ // A host shows a pending Spinner through `children` in whatever state the+ // row is in, and an unchosen row is the common one. The unchecked case+ // used to render nothing at all.+ for (const state of ['checked', 'unchecked'] as const) {+ const {unmount} = render(+ <CheckIndicator state={state}>+ <span data-testid="busy" />+ </CheckIndicator>,+ );++ expect(screen.getByTestId('busy'), `state=${state}`).toBeInTheDocument();+ // The mark is replaced, not accompanied.+ expect(document.querySelector('.astryx-icon')).not.toBeInTheDocument();+ unmount();+ }+ });++ it('forwards caller props and styling on both render paths', () => {+ // Same contract whether or not children are present: a data-testid, an id+ // and an xstyle-driven class must survive either branch.+ const {container, rerender} = render(+ <CheckIndicator state="checked" data-testid="mark" id="pinned" />,+ );++ expect(screen.getByTestId('mark')).toHaveAttribute('id', 'pinned');++ rerender(+ <CheckIndicator+ state="checked"+ data-testid="mark"+ id="pinned"+ className="host-target">+ <span data-testid="busy" />+ </CheckIndicator>,+ );++ const withChildren = screen.getByTestId('mark');+ expect(withChildren).toHaveAttribute('id', 'pinned');+ expect(withChildren).toHaveClass('host-target');+ expect(withChildren).toHaveAttribute('aria-hidden', 'true');+ expect(container.querySelector('[data-testid="busy"]')).toBeInTheDocument();+ });+});+describe('useIndicator', () => {it('returns the built-in indicator without a theme override', () => {const {result} = renderHook(() => useIndicator('checkbox'));diff --git a/packages/core/src/Indicator/RadioIndicator.tsx b/packages/core/src/Indicator/RadioIndicator.tsxindex a73a531da3..a7b134c968 100644--- a/packages/core/src/Indicator/RadioIndicator.tsx+++ b/packages/core/src/Indicator/RadioIndicator.tsx@@ -14,6 +14,7 @@ import {colorVars,durationVars,easeVars,+ radiusVars,} from '../theme/tokens.stylex';import {mergeProps, themeProps} from '../utils';import {indicatorScope} from './indicator.markers.stylex';@@ -28,7 +29,11 @@ const styles = stylex.create({flexShrink: 0,borderWidth: borderVars['--border-width'],borderStyle: 'solid',- borderRadius: '50%',+ // A circle, in tokens: --radius-full is the house "fully rounded" value+ // (9999px) and renders pixel-identical to 50% on a square box, which the+ // size styles below guarantee. Themeable through --radius-full, unlike a+ // raw 50%.+ borderRadius: radiusVars['--radius-full'],transitionProperty: 'background-color, border-color',transitionDuration: {default: durationVars['--duration-fast'],@@ -82,7 +87,7 @@ const styles = stylex.create({},},dot: {- borderRadius: '50%',+ borderRadius: radiusVars['--radius-full'],backgroundColor: {default: colorVars['--color-on-accent'],// Forced colors (Windows High Contrast) strips painted backgrounds,diff --git a/packages/core/src/Indicator/index.ts b/packages/core/src/Indicator/index.tsindex 0334072b3b..4787f3fea5 100644--- a/packages/core/src/Indicator/index.ts+++ b/packages/core/src/Indicator/index.ts@@ -22,7 +22,10 @@ export {RadioIndicator} from './RadioIndicator';// Registry (RSC-compatible, no 'use client')export {defaultIndicators, getIndicator} from './indicatorRegistry';-export type {IndicatorRegistrySource} from './indicatorRegistry';+export type {+ CoreIndicatorName,+ IndicatorRegistrySource,+} from './indicatorRegistry';export {useIndicator} from './useIndicator';diff --git a/packages/core/src/Indicator/indicatorRegistry.test.tsx b/packages/core/src/Indicator/indicatorRegistry.test.tsxnew file mode 100644index 0000000000..96d3e7f21e--- /dev/null+++ b/packages/core/src/Indicator/indicatorRegistry.test.tsx@@ -0,0 +1,106 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file indicatorRegistry.test.tsx+ *+ * Pins the seam between the indicators core ships and the ones other packages+ * add, because that seam used to lie: `defaultIndicators` was typed as a total+ * map over the OPEN `IndicatorName` union, so augmenting `IndicatorMap` made+ * the compiler promise a component for a name nothing had registered, and+ * rendering the `undefined` it actually returned threw.+ *+ * The augmentation below is deliberately real, not a cast — it is exactly what+ * a downstream package writes, and it is what makes `defaultIndicators`+ * failing to cover `'brand-star'` a compile error if anyone re-widens the map.+ */++import {describe, expect, it} from 'vitest';+import {render} from '@testing-library/react';+import {defineTheme} from '../theme/defineTheme';+import {CheckboxIndicator} from './CheckboxIndicator';+import {CheckIndicator} from './CheckIndicator';+import {RadioIndicator} from './RadioIndicator';+import {defaultIndicators, getIndicator} from './indicatorRegistry';+import type {CoreIndicatorName} from './indicatorRegistry';+import type {IndicatorName, IndicatorProps} from './types';++declare module './types' {+ interface IndicatorMap {+ 'brand-star': 'singleSelection';+ }+}++function BrandStar({state}: IndicatorProps<'singleSelection'>) {+ return <span aria-hidden="true" data-testid="star" data-state={state} />;+}++describe('defaultIndicators', () => {+ it('covers exactly the core indicator names', () => {+ // A Record over the union, not an array: adding a name to+ // CoreIndicatorName without shipping a default fails to compile here+ // before it can fail at runtime anywhere else.+ const coreNames: Record<CoreIndicatorName, true> = {+ check: true,+ checkbox: true,+ radio: true,+ };++ expect(Object.keys(defaultIndicators).sort()).toEqual(+ Object.keys(coreNames).sort(),+ );+ expect(defaultIndicators.check).toBe(CheckIndicator);+ expect(defaultIndicators.checkbox).toBe(CheckboxIndicator);+ expect(defaultIndicators.radio).toBe(RadioIndicator);+ });+});++describe('getIndicator', () => {+ it('resolves a core name to its built-in with no theme', () => {+ expect(getIndicator('check')).toBe(CheckIndicator);+ expect(getIndicator('radio')).toBe(RadioIndicator);+ });++ it('prefers a theme override, by name, across every host', () => {+ const theme = defineTheme({+ name: 'registry-override',+ indicators: {check: RadioIndicator},+ });++ expect(getIndicator('check', theme)).toBe(RadioIndicator);+ // Unmapped names keep their built-in.+ expect(getIndicator('checkbox', theme)).toBe(CheckboxIndicator);+ });++ it('returns undefined for an augmented name no theme supplies', () => {+ // The honest answer: core ships no `brand-star`. The type says+ // `| undefined` for exactly this reason, so a caller writes `?? BrandStar`+ // instead of rendering undefined.+ expect(getIndicator('brand-star')).toBeUndefined();+ });++ it('resolves an augmented name the theme does supply', () => {+ const theme = defineTheme({+ name: 'brand-star-theme',+ indicators: {'brand-star': BrandStar},+ });++ const Star = getIndicator('brand-star', theme);+ expect(Star).toBe(BrandStar);++ const {container} = render(<BrandStar state="checked" />);+ expect(container.querySelector('[data-testid="star"]')).toBeInTheDocument();+ });++ it('types a core name as always resolvable and an open name as maybe', () => {+ // Compile-time assertions; the runtime body only keeps them referenced.+ const core = getIndicator('check');+ const open = getIndicator('brand-star' as IndicatorName);++ // @ts-expect-error — an augmented name may have no default; callers must+ // handle undefined rather than render it.+ const _mustHandle: NonNullable<typeof open> = open;++ expect(core).toBeDefined();+ expect(_mustHandle ?? null).toBeDefined();+ });+});diff --git a/packages/core/src/Indicator/indicatorRegistry.ts b/packages/core/src/Indicator/indicatorRegistry.tsindex e388cf5605..0ac921727a 100644--- a/packages/core/src/Indicator/indicatorRegistry.ts+++ b/packages/core/src/Indicator/indicatorRegistry.ts@@ -6,6 +6,22 @@* @output Exports the default indicator map and getIndicator resolution* @position Server-safe indicator resolver; no 'use client' so it is* importable from RSC+ *+ * Two name spaces meet here, and keeping them apart is the whole design:+ *+ * - {@link CoreIndicatorName} — the indicators Astryx itself ships. Closed,+ * and every one of them has a default, so resolving one always yields a+ * component.+ * - {@link IndicatorName} — every indicator name that exists, including the+ * ones other packages add by augmenting `IndicatorMap`. Open, and core has+ * no default for a name it has never heard of.+ *+ * `getIndicator` is overloaded along that seam: a core name resolves to a+ * component, an augmented name resolves to a component *or* `undefined`, and+ * the caller has to say what to do about it. Typing the map as total over the+ * open union instead — which is what shipped in #4712 — made the compiler+ * promise a component for `getIndicator('brand-star')` and hand back+ * `undefined` at runtime.*/import type {DefinedTheme} from '../theme/defineTheme';@@ -20,6 +36,16 @@ import type {IndicatorRegistry,} from './types';+/**+ * The indicator names Astryx ships a default for.+ *+ * Written out rather than derived from {@link IndicatorMap}, because that+ * interface is open to augmentation and this set is not: it is exactly what is+ * in {@link defaultIndicators} below. `indicatorRegistry.test.tsx` pins the two+ * together in both directions.+ */+export type CoreIndicatorName = 'check' | 'checkbox' | 'radio';+/*** The indicators Astryx ships. A theme's `indicators` entries override these* by name.@@ -29,7 +55,7 @@ import type {* {@link IndicatorRegistry} holds replacements to.*/export const defaultIndicators: {- [N in IndicatorName]: IndicatorComponent<IndicatorMap[N]>;+ [N in CoreIndicatorName]: IndicatorComponent<IndicatorMap[N]>;} = {check: CheckIndicator,checkbox: CheckboxIndicator,@@ -63,10 +89,32 @@ function getThemeIndicators(* const Radio = getIndicator('radio', themeName);* <Radio state="checked" />* ```+ *+ * For a name contributed by augmentation there is no built-in to fall back to,+ * so the result is `undefined` unless a theme supplies one — the package that+ * added the name owns its default:+ *+ * @example+ * ```tsx+ * const Star = getIndicator('brand-star', themeName) ?? BrandStar;+ * ```*/+export function getIndicator<N extends CoreIndicatorName>(+ name: N,+ source?: IndicatorRegistrySource,+): IndicatorComponent<IndicatorMap[N]>;export function getIndicator<N extends IndicatorName>(name: N,source?: IndicatorRegistrySource,-): IndicatorComponent<IndicatorMap[N]> {- return getThemeIndicators(source)?.[name] ?? defaultIndicators[name];+): IndicatorComponent<IndicatorMap[N]> | undefined;+export function getIndicator(+ name: IndicatorName,+ source?: IndicatorRegistrySource,+): IndicatorComponent | undefined {+ const override = getThemeIndicators(source)?.[name];+ return (override ??+ // `name` may be an augmented one, which this map has no entry for — hence+ // the `| undefined` the overloads expose to those callers.+ (defaultIndicators as Partial<Record<IndicatorName, unknown>>)[name]) as+ IndicatorComponent | undefined;}diff --git a/packages/core/src/Indicator/types.ts b/packages/core/src/Indicator/types.tsindex c3078688aa..3a9d831c04 100644--- a/packages/core/src/Indicator/types.ts+++ b/packages/core/src/Indicator/types.ts@@ -118,7 +118,10 @@ export type IndicatorComponent<F extends IndicatorFamily = IndicatorFamily> =* 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:+ * Packages outside core can contribute their own through module augmentation.+ * Core ships no default for a name it does not know, so the package that adds+ * the name owns its default — `getIndicator`/`useIndicator` return+ * `| undefined` for it, and the call site supplies the fallback:** ```ts* declare module '@astryxdesign/core/Indicator' {@@ -126,6 +129,8 @@ export type IndicatorComponent<F extends IndicatorFamily = IndicatorFamily> =* 'brand-star': 'singleSelection';* }* }+ *+ * const Star = useIndicator('brand-star') ?? BrandStar;* ```*/export interface IndicatorMap {diff --git a/packages/core/src/Indicator/useIndicator.ts b/packages/core/src/Indicator/useIndicator.tsindex 293ed8bef5..326bb0331a 100644--- a/packages/core/src/Indicator/useIndicator.ts+++ b/packages/core/src/Indicator/useIndicator.ts@@ -10,20 +10,30 @@*/import {useThemeName} from '../theme/useTheme';-import {getIndicator} from './indicatorRegistry';+import {getIndicator, type CoreIndicatorName} from './indicatorRegistry';import type {IndicatorComponent, IndicatorMap, IndicatorName} from './types';/*** Resolve an indicator component from the nearest `<Theme>`.*+ * A core indicator always resolves. A name contributed by augmentation+ * resolves only if a theme supplies it, so that overload returns+ * `| undefined` — see {@link getIndicator}.+ ** @example* ```tsx* const Checkbox = useIndicator('checkbox');* return <Checkbox state={isChecked ? 'checked' : 'unchecked'} size={size} />;* ```*/+export function useIndicator<N extends CoreIndicatorName>(+ name: N,+): IndicatorComponent<IndicatorMap[N]>;export function useIndicator<N extends IndicatorName>(name: N,-): IndicatorComponent<IndicatorMap[N]> {+): IndicatorComponent<IndicatorMap[N]> | undefined;+export function useIndicator(+ name: IndicatorName,+): IndicatorComponent | undefined {return getIndicator(name, useThemeName());}