Skip to content

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

TypeScript

fix(Switch): persistently mount busy live region and localize loading announcement (#6114) (#6125)

Geervan4d83402742d7
diff --git a/.changeset/switch-busy-announcement.md b/.changeset/switch-busy-announcement.md
new file mode 100644
index 0000000000..ef529d7f7a
--- /dev/null
+++ b/.changeset/switch-busy-announcement.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Switch: announce busy/loading states through the persistent `useAnnounce` live region and localize the announcement via `@astryx.switch.loading`.
+
+@Geervan
diff --git a/packages/core/locales/en.json b/packages/core/locales/en.json
index bc31c4a19a..36d7c6c1f3 100644
--- a/packages/core/locales/en.json
+++ b/packages/core/locales/en.json
@@ -1251,6 +1251,10 @@
"defaultMessage": "error",
"description": "Screen-reader-only status word rendered next to a Stepper step label when status=error. Lowercase noun; read mid-sentence after the step label."
},
+ "@astryx.switch.loading": {
+ "defaultMessage": "Loading",
+ "description": "Screen-reader-only live-region announcement while a Switch is in its busy state (spinner shown, action in flight)."
+ },
"@astryx.tableTree.collapseRow": {
"defaultMessage": "Collapse row",
"description": "Aria label for the Table tree-data expander chevron when the row is currently expanded."
diff --git a/packages/core/src/Switch/Switch.test.tsx b/packages/core/src/Switch/Switch.test.tsx
index b71c31c68d..524748879c 100644
--- a/packages/core/src/Switch/Switch.test.tsx
+++ b/packages/core/src/Switch/Switch.test.tsx
@@ -32,6 +32,7 @@ import {
} from '../__tests__/forcedColors';
import {hasPressedArm} from '../__tests__/pressState';
import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';
+import {InternationalizationProvider} from '../i18n';
afterEach(() => {
__resetLiveRegionsForTest();
@@ -388,6 +389,81 @@ describe('Switch', () => {
});
});
+ it('announces loading state through useAnnounce when busy', async () => {
+ const {container, rerender} = render(
+ <Switch label="Enable notifications" value={false} onChange={() => {}} />,
+ );
+ // Does not introduce a permanent live region DOM element per switch
+ expect(
+ container.querySelector('[role="status"][aria-live="polite"]'),
+ ).toBeNull();
+
+ rerender(
+ <Switch
+ label="Enable notifications"
+ value={false}
+ onChange={() => {}}
+ isLoading
+ />,
+ );
+ await waitFor(() => {
+ expect(
+ document.querySelector('[data-astryx-live-region="polite"]'),
+ ).toHaveTextContent('Loading');
+ });
+ });
+
+ it('localizes the loading announcement through the i18n catalog', async () => {
+ render(
+ <InternationalizationProvider
+ locale="fr"
+ overrides={{fr: {'@astryx.switch.loading': 'Chargement'}}}>
+ <Switch
+ label="Enable notifications"
+ value={false}
+ onChange={() => {}}
+ isLoading
+ />
+ </InternationalizationProvider>,
+ );
+ await waitFor(() => {
+ expect(
+ document.querySelector('[data-astryx-live-region="polite"]'),
+ ).toHaveTextContent('Chargement');
+ });
+ });
+
+ it('announces loading state while async changeAction is pending', async () => {
+ let resolveAction!: () => void;
+ const changeAction = vi.fn(
+ async () =>
+ new Promise<void>(resolve => {
+ resolveAction = resolve;
+ }),
+ );
+
+ render(
+ <Switch
+ label="Enable notifications"
+ value={false}
+ onChange={() => {}}
+ changeAction={changeAction}
+ />,
+ );
+
+ const switchEl = screen.getByRole('switch');
+ fireEvent.click(switchEl);
+
+ expect(changeAction).toHaveBeenCalled();
+ await waitFor(() => {
+ expect(
+ document.querySelector('[data-astryx-live-region="polite"]'),
+ ).toHaveTextContent('Loading');
+ });
+
+ resolveAction();
+ });
+
it('calls onFocus and onBlur callbacks', async () => {
const user = userEvent.setup();
const handleFocus = vi.fn();
diff --git a/packages/core/src/Switch/Switch.tsx b/packages/core/src/Switch/Switch.tsx
index 8698d6a96b..156187cd2d 100644
--- a/packages/core/src/Switch/Switch.tsx
+++ b/packages/core/src/Switch/Switch.tsx
@@ -4,7 +4,7 @@
/**
* @file Switch.tsx
- * @input Uses React, useId, ChangeEvent, FieldLabel, FieldStatus, IconType, InputStatus, useTooltip
+ * @input Uses React, useId, ChangeEvent, FieldLabel, FieldStatus, IconType, InputStatus, useTooltip, i18n (useTranslator)
* @output Exports Switch component, SwitchProps, SwitchLabelPosition, SwitchLabelSpacing
* @position Core implementation; consumed by index.ts, tested by Switch.test.tsx
*
@@ -20,6 +20,7 @@ import {
useId,
useOptimistic,
useTransition,
+ useEffect,
type ChangeEvent,
type FocusEvent,
type ReactNode,
@@ -46,8 +47,9 @@ import {switchScope} from './switch.markers.stylex';
import type {BaseProps} from '../BaseProps';
import type {SizeValue} from '../utils/types';
import {themeProps} from '../utils/themeProps';
-import {VisuallyHidden} from '../VisuallyHidden';
+import {useAnnounce} from '../hooks/useAnnounce';
import {useResolvedRequired} from '../hooks/useResolvedRequired';
+import {useTranslator} from '../i18n';
import {useMergedRefs} from '../hooks/useMergedRefs';
const wrapperSizeStyles = stylex.create({
@@ -519,6 +521,7 @@ export function Switch({
ref,
...rest
}: SwitchProps) {
+ const t = useTranslator();
const id = useId();
const descriptionID = useId();
const statusMessageID = useId();
@@ -531,6 +534,13 @@ export function Switch({
const [optimisticValue, setOptimisticValue] = useOptimistic(value);
const isBusy = isLoading || optimisticValue !== value;
+ const announce = useAnnounce();
+ useEffect(() => {
+ if (isBusy) {
+ announce(t('@astryx.switch.loading'));
+ }
+ }, [announce, isBusy, t]);
+
const isOn = optimisticValue === true;
// Disabled-reason tooltip. Disabled controls swallow pointer events, so the
@@ -642,7 +652,6 @@ export function Switch({
{isBusy && <Spinner size="sm" />}
</div>
</div>
- {isBusy && <VisuallyHidden role="status">Loading</VisuallyHidden>}
</div>
);