Skip to content

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

TypeScript

fix(Kbd): ctrl, alt, shift and meta show text off Apple platforms (#10524)

Cindy Zhangfac363ee868c
diff --git a/.changeset/kbd-platform-modifiers.md b/.changeset/kbd-platform-modifiers.md
new file mode 100644
index 0000000000..4244373162
--- /dev/null
+++ b/.changeset/kbd-platform-modifiers.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] `Kbd` shows `ctrl`, `alt` and `shift` as text ("Ctrl", "Alt", "Shift") off Apple platforms and before hydration, and `meta` as "Win" off Apple platforms and before hydration, instead of Apple's ⌃ ⌥ ⇧ symbols and "META". Apple platforms keep the symbols, and spoken names are unchanged. The text comes from the catalog, so other locales can translate it.
+
+@cixzhang
diff --git a/apps/storybook/stories/Kbd.stories.tsx b/apps/storybook/stories/Kbd.stories.tsx
index bee2330b00..c525d6f939 100644
--- a/apps/storybook/stories/Kbd.stories.tsx
+++ b/apps/storybook/stories/Kbd.stories.tsx
@@ -150,28 +150,28 @@ export const AllModifierSymbols: Story = {
Cmd (mod):
</Text>
<Kbd keys="mod" />
- <Text type="supporting">⌘</Text>
+ <Text type="supporting">⌘ on Apple platforms, Ctrl elsewhere</Text>
</div>
<div style={{display: 'flex', gap: '16px', alignItems: 'center'}}>
<Text type="label" style={{width: '120px'}}>
Ctrl:
</Text>
<Kbd keys="ctrl" />
- <Text type="supporting">⌃</Text>
+ <Text type="supporting">⌃ on Apple platforms, Ctrl elsewhere</Text>
</div>
<div style={{display: 'flex', gap: '16px', alignItems: 'center'}}>
<Text type="label" style={{width: '120px'}}>
Alt/Option:
</Text>
<Kbd keys="alt" />
- <Text type="supporting">⌥</Text>
+ <Text type="supporting">⌥ on Apple platforms, Alt elsewhere</Text>
</div>
<div style={{display: 'flex', gap: '16px', alignItems: 'center'}}>
<Text type="label" style={{width: '120px'}}>
Shift:
</Text>
<Kbd keys="shift" />
- <Text type="supporting">⇧</Text>
+ <Text type="supporting">⇧ on Apple platforms, Shift elsewhere</Text>
</div>
</div>
),
diff --git a/docs/specs/components/Kbd/Kbd.spec.md b/docs/specs/components/Kbd/Kbd.spec.md
index 484074f3bb..633c8730f7 100644
--- a/docs/specs/components/Kbd/Kbd.spec.md
+++ b/docs/specs/components/Kbd/Kbd.spec.md
@@ -83,12 +83,12 @@ Consumer migration instructions belong in consumer docs and release notes.
## Behavioral and layout contract
-| ID | Invariant | Basis |
-| --- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- |
-| FR1 | The current render contains one shortcut group and one painted key badge for every parsed key segment. `keys` splits on `+`; each segment is trimmed and lowercased, `esc` reads as `escape` and `return` as `enter`, and a repeated key gets its own badge. Each badge is at least the `--spacing-5` size and MUST grow with a set text size so its glyph never clips (`spec:AST-102` FR4). | Current source, docs, and tests; `spec:AST-102` FR4 |
-| FR2 | The shortcut group carries the current `kbd` target; individual key badges currently carry no public target (OQ1). | Current source, docs, and tests |
-| FR3 | Each badge shows a glyph: `mod` is ⌘ on Apple platforms and the catalog's short Control text ("Ctrl" in English) elsewhere and before hydration; `escape` shows the catalog's short Escape text ("Esc"); `ctrl`, `alt`, `shift`, `enter`, `backspace`, `tab`, and the arrows show their symbols; `plus` shows "+"; any other key shows uppercased. | `architecture:internationalization` INV1a; current source and tests |
-| FR4 | The group has `role="img"` and an `aria-label` built from each key's spoken name, taken from the Astryx catalog (`mod` is "Command" on Apple platforms and "Control" elsewhere and before hydration; an unknown key is spoken uppercased), joined pairwise through the catalog's shortcut message (" + " in English, for example "Command + K"); every badge is `aria-hidden`. A caller's `role` and `aria-label` never replace the computed ones; other caller ARIA props, such as `aria-labelledby` and `aria-hidden`, still reach the group. | `architecture:internationalization` INV1, INV1a; current source and tests |
+| ID | Invariant | Basis |
+| --- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- |
+| FR1 | The current render contains one shortcut group and one painted key badge for every parsed key segment. `keys` splits on `+`; each segment is trimmed and lowercased, `esc` reads as `escape` and `return` as `enter`, and a repeated key gets its own badge. Each badge is at least the `--spacing-5` size and MUST grow with a set text size so its glyph never clips (`spec:AST-102` FR4). | Current source, docs, and tests; `spec:AST-102` FR4 |
+| FR2 | The shortcut group carries the current `kbd` target; individual key badges currently carry no public target (OQ1). | Current source, docs, and tests |
+| FR3 | Each badge shows a glyph: `mod` is ⌘ on Apple platforms and the catalog's short Control text ("Ctrl" in English) elsewhere and before hydration; `ctrl`, `alt`, and `shift` follow the same rule, ⌃ ⌥ ⇧ on Apple platforms and the catalog's short text ("Ctrl", "Alt", "Shift" in English) elsewhere and before hydration; `meta` shows the catalog's short Windows-key text ("Win" in English) elsewhere and before hydration; spoken names are unchanged; `escape` shows the catalog's short Escape text ("Esc"); `enter`, `backspace`, `tab`, and the arrows show their symbols; `plus` shows "+"; any other key shows uppercased. | `architecture:internationalization` INV1a; current source and tests |
+| FR4 | The group has `role="img"` and an `aria-label` built from each key's spoken name, taken from the Astryx catalog (`mod` is "Command" on Apple platforms and "Control" elsewhere and before hydration; an unknown key is spoken uppercased), joined pairwise through the catalog's shortcut message (" + " in English, for example "Command + K"); every badge is `aria-hidden`. A caller's `role` and `aria-label` never replace the computed ones; other caller ARIA props, such as `aria-labelledby` and `aria-hidden`, still reach the group. | `architecture:internationalization` INV1, INV1a; current source and tests |
### Allowed variation
@@ -157,13 +157,14 @@ target.
## Verification map
-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
-| ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------- |
-| FR1 | `Kbd.test.tsx` single-key, multi-key, whitespace, alias, and repeated-key cases | Single and multiple keys; spaced and mixed-case input; repeated aliases | A missing or extra badge, an untrimmed or wrongly cased key, or a lost alias fails. `KbdAudit.a11y.chromium.spec.ts` larger-text cases measure each badge growing past `--spacing-5` with a set text size. | `audit:Kbd/anatomy` |
-| FR2 | `Kbd.test.tsx` theme-class case | Root target and child badges | A missing root `kbd` target fails. Evidence gap: no test asserts that badges carry no target. | `audit:Kbd/theming` |
-| FR3, FR4 | `Kbd.test.tsx` glyph, platform, accessible-name, override, and localization cases ("localizes visible key text and the spoken shortcut combination") | Mac and non-Mac; special and unknown keys | A wrong glyph for `mod`, `ctrl`, `alt`, `shift`, `enter`, `escape`, `plus`, or an unknown key, an exposed badge, a caller `role` or `aria-label` that replaces the computed one, or text that skips the catalog fails. Evidence gap: no test asserts the `backspace`, `tab`, or arrow glyphs, or the "Ctrl" text and "Control" name before hydration. | `audit:Kbd/accessibility` |
-| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and targets | Missing, extra, prefixed, stale, or alias-backed mappings fail repository validation. | `audit:Kbd/theming` |
-| ORD1, PR1, AR1, AR2 | ORD1 is covered by the FR1 and FR3 rows and AR1 and AR2 by the FR3, FR4 row. Evidence gap: no test asserts the absence of listeners | — | — | `audit:Kbd/behavior` |
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------- |
+| FR1 | `Kbd.test.tsx` single-key, multi-key, whitespace, alias, and repeated-key cases | Single and multiple keys; spaced and mixed-case input; repeated aliases | A missing or extra badge, an untrimmed or wrongly cased key, or a lost alias fails. `KbdAudit.a11y.chromium.spec.ts` larger-text cases measure each badge growing past `--spacing-5` with a set text size. | `audit:Kbd/anatomy` |
+| FR2 | `Kbd.test.tsx` theme-class case | Root target and child badges | A missing root `kbd` target fails. Evidence gap: no test asserts that badges carry no target. | `audit:Kbd/theming` |
+| FR3, FR4 | `Kbd.test.tsx` glyph, platform, accessible-name, override, and localization cases ("localizes visible key text and the spoken shortcut combination") | Mac and non-Mac; special and unknown keys | A wrong glyph for `mod`, `ctrl`, `alt`, `shift`, `enter`, `escape`, `plus`, or an unknown key, an exposed badge, a caller `role` or `aria-label` that replaces the computed one, or text that skips the catalog fails. Evidence gap: no test asserts the `backspace`, `tab`, or arrow glyphs, or the "Ctrl" text and "Control" name before hydration. | `audit:Kbd/accessibility` |
+| FR3 modifiers | `Kbd.test.tsx` modifier cases: Apple symbols, Windows and Linux catalog text, server render on a Mac, localized short text; real-browser render with a Windows user agent | Apple (`MacIntel`); non-Apple (`Win32`, `Linux x86_64`); before hydration | `ctrl`, `alt`, or `shift` showing a symbol off Apple platforms or before hydration, `meta` showing anything but the catalog's Windows-key text off Apple platforms or before hydration, a spoken name that changes, or modifier text that skips the catalog fails. | `audit:Kbd/accessibility` |
+| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and targets | Missing, extra, prefixed, stale, or alias-backed mappings fail repository validation. | `audit:Kbd/theming` |
+| ORD1, PR1, AR1, AR2 | ORD1 is covered by the FR1 and FR3 rows and AR1 and AR2 by the FR3, FR4 row. Evidence gap: no test asserts the absence of listeners | — | — | `audit:Kbd/behavior` |
## Current-state impact
diff --git a/packages/core/locales/en.json b/packages/core/locales/en.json
index 3232a95f69..33463386fa 100644
--- a/packages/core/locales/en.json
+++ b/packages/core/locales/en.json
@@ -1507,6 +1507,10 @@
"defaultMessage": "Alt",
"description": "Spoken name of the Alt modifier key in a keyboard shortcut's accessible name."
},
+ "@astryx.kbd.key.altShort": {
+ "defaultMessage": "Alt",
+ "description": "Abbreviated visible label of the Alt keycap on non-Apple platforms (Apple platforms show the Option symbol). Localize to the keyboard's conventional short label."
+ },
"@astryx.kbd.key.backspace": {
"defaultMessage": "Backspace",
"description": "Spoken name of the Backspace key in a keyboard shortcut's accessible name."
@@ -1555,6 +1559,10 @@
"defaultMessage": "Shift",
"description": "Spoken name of the Shift modifier key in a keyboard shortcut's accessible name."
},
+ "@astryx.kbd.key.shiftShort": {
+ "defaultMessage": "Shift",
+ "description": "Abbreviated visible label of the Shift keycap on non-Apple platforms (Apple platforms show the Shift symbol). Localize to the keyboard's conventional short label."
+ },
"@astryx.kbd.key.tab": {
"defaultMessage": "Tab",
"description": "Spoken name of the Tab key in a keyboard shortcut's accessible name."
@@ -1563,6 +1571,10 @@
"defaultMessage": "Up arrow",
"description": "Spoken name of the up arrow key in a keyboard shortcut's accessible name."
},
+ "@astryx.kbd.key.windowsShort": {
+ "defaultMessage": "Win",
+ "description": "Abbreviated visible label of the Windows logo keycap, shown for the meta key on non-Apple platforms. Localize to the keyboard's conventional short label."
+ },
"@astryx.kbd.shortcut": {
"defaultMessage": "{shortcut} + {key}",
"description": "Combines spoken key names into one keyboard shortcut's accessible name. {shortcut} is the preceding keys and {key} is the next key's localized spoken name. Applied once for each key after the first; translators may change the separator or order."
diff --git a/packages/core/src/Kbd/Kbd.doc.mjs b/packages/core/src/Kbd/Kbd.doc.mjs
index d254603405..c1dc306e01 100644
--- a/packages/core/src/Kbd/Kbd.doc.mjs
+++ b/packages/core/src/Kbd/Kbd.doc.mjs
@@ -11,17 +11,38 @@ const anatomy = [
{
name: 'Key badge',
required: true,
- description: 'Painted key badge rendered once for each key in the shortcut.',
+ description:
+ 'Painted key badge rendered once for each key in the shortcut.',
},
];
/** @type {import('@astryxdesign/cli/authoring').ComponentBestPractice[]} */
const bestPractices = [
- { guidance: true, description: 'Place shortcuts near the action they trigger: in a tooltip, menu item, or inline instruction.' },
- { guidance: true, description: 'Use mod instead of ctrl or cmd; it automatically adapts to the user\'s platform.' },
- { guidance: true, description: 'Let Kbd name the shortcut: screen readers hear the keys as words, such as "Command + K". Kbd ignores an aria-label you pass; to name it from visible text, use aria-labelledby.' },
- { guidance: false, description: 'Use Kbd as the only way to discover an action; shortcuts should supplement visible controls, not replace them.' },
- { guidance: false, description: 'Expect Kbd to handle the key press. It only shows the keys; listen for the shortcut in your own code.' },
+ {
+ guidance: true,
+ description:
+ 'Place shortcuts near the action they trigger: in a tooltip, menu item, or inline instruction.',
+ },
+ {
+ guidance: true,
+ description:
+ "Use mod instead of ctrl or cmd; it automatically adapts to the user's platform.",
+ },
+ {
+ guidance: true,
+ description:
+ 'Let Kbd name the shortcut: screen readers hear the keys as words, such as "Command + K". Kbd ignores an aria-label you pass; to name it from visible text, use aria-labelledby.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Use Kbd as the only way to discover an action; shortcuts should supplement visible controls, not replace them.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Expect Kbd to handle the key press. It only shows the keys; listen for the shortcut in your own code.',
+ },
];
/** @type {import('@astryxdesign/cli/authoring').ComponentDoc} */
@@ -30,13 +51,23 @@ export const docs = {
name: 'Kbd',
displayName: 'Kbd',
category: 'Content',
- keywords: ["kbd","keyboard","shortcut","hotkey","keybinding","keystroke","keycombo","modifier","accelerator"],
+ keywords: [
+ 'kbd',
+ 'keyboard',
+ 'shortcut',
+ 'hotkey',
+ 'keybinding',
+ 'keystroke',
+ 'keycombo',
+ 'modifier',
+ 'accelerator',
+ ],
props: [
{
name: 'keys',
type: 'string',
description:
- 'Keyboard shortcut string. Use "+" to separate keys. Special keys: mod (Cmd on Mac), ctrl, alt, shift, enter, backspace, escape, tab, up, down, left, right, plus. Aliases: esc for escape and return for enter.',
+ 'Keyboard shortcut string. Use "+" to separate keys. Special keys: mod (⌘ on Apple platforms, Ctrl elsewhere), ctrl, alt and shift (Apple symbols on Apple platforms, Ctrl, Alt and Shift text elsewhere), meta (Win elsewhere and before hydration), enter, backspace, escape, tab, up, down, left, right, plus. Aliases: esc for escape and return for enter.',
required: true,
},
{
@@ -68,7 +99,8 @@ export const docs = {
},
usage: {
anatomy,
- description: 'Renders a keyboard shortcut as styled key badges. Use Kbd in tooltips, menus, and help text to show key combinations.',
+ description:
+ 'Renders a keyboard shortcut as styled key badges. Use Kbd in tooltips, menus, and help text to show key combinations.',
bestPractices,
},
};
@@ -82,7 +114,7 @@ export const docsZh = {
name: 'keys',
type: 'string',
description:
- '键盘快捷键字符串。使用 "+" 分隔各按键。特殊按键:mod(Mac 上为 Cmd)、ctrl、alt、shift、enter、backspace、escape、tab、up、down、left、right、plus。别名:esc 等同于 escape,return 等同于 enter。',
+ '键盘快捷键字符串。使用 "+" 分隔各按键。特殊按键:mod(Apple 平台上为 ⌘,其他平台为 Ctrl)、ctrl、alt 和 shift(Apple 平台上为符号,其他平台为 Ctrl、Alt、Shift 文字)、meta(其他平台及水合前为 Win)、enter、backspace、escape、tab、up、down、left、right、plus。别名:esc 等同于 escape,return 等同于 enter。',
required: true,
},
{
@@ -114,7 +146,8 @@ export const docsZh = {
},
usage: {
anatomy,
- description: 'Renders a keyboard shortcut as styled key badges. Use Kbd in tooltips, menus, and help text to show key combinations.',
+ description:
+ 'Renders a keyboard shortcut as styled key badges. Use Kbd in tooltips, menus, and help text to show key combinations.',
bestPractices,
},
};
@@ -125,14 +158,18 @@ export const docsDense = {
'Renders keyboard shortcut as styled key badges. Use in tooltips, menus + help text to show key combinations.',
usage: {
anatomy,
- description: 'Renders a keyboard shortcut as styled key badges. Use Kbd in tooltips, menus, and help text to show key combinations.',
+ description:
+ 'Renders a keyboard shortcut as styled key badges. Use Kbd in tooltips, menus, and help text to show key combinations.',
bestPractices,
},
propDescriptions: {
- keys: 'Shortcut string. "+" separates keys. Special: mod (Cmd on Mac), ctrl, alt, shift, enter, backspace, escape, tab, up, down, left, right, plus. Aliases: esc for escape, return for enter.',
- xstyle: 'StyleX styles for layout customization. Must be stylex.create() value.',
- className: 'CSS class for root element. Prefer xstyle; className for non-StyleX integration.',
- style: 'Inline styles for root element. Prefer xstyle; inline styles bypass StyleX optimization.',
+ keys: 'Shortcut string. "+" separates keys. Special: mod (⌘ on Apple, Ctrl elsewhere), ctrl, alt, shift (Apple symbols on Apple, text elsewhere), meta (Win elsewhere and before hydration), enter, backspace, escape, tab, up, down, left, right, plus. Aliases: esc for escape, return for enter.',
+ xstyle:
+ 'StyleX styles for layout customization. Must be stylex.create() value.',
+ className:
+ 'CSS class for root element. Prefer xstyle; className for non-StyleX integration.',
+ style:
+ 'Inline styles for root element. Prefer xstyle; inline styles bypass StyleX optimization.',
ref: 'Ref forwarded to shortcut group element.',
},
};
diff --git a/packages/core/src/Kbd/Kbd.test.tsx b/packages/core/src/Kbd/Kbd.test.tsx
index 9d9a19df77..bd67db3dd8 100644
--- a/packages/core/src/Kbd/Kbd.test.tsx
+++ b/packages/core/src/Kbd/Kbd.test.tsx
@@ -9,7 +9,8 @@
* so `mod` resolves to "Ctrl" rather than "\u2318" after the layout effect.
*/
-import {render, screen, within} from '@testing-library/react';
+import {act, render, screen, within} from '@testing-library/react';
+import {hydrateRoot} from 'react-dom/client';
import {renderToString} from 'react-dom/server';
import {describe, it, expect, afterEach, vi} from 'vitest';
import {Kbd} from './Kbd';
@@ -57,14 +58,106 @@ describe('Kbd', () => {
expect(screen.getByText('\u2318')).toBeInTheDocument(); // \u2318
});
- it('maps modifier keys to symbols', () => {
+ it('shows Apple modifier symbols for ctrl, alt and shift on Apple platforms', () => {
+ Object.defineProperty(navigator, 'platform', {
+ value: 'MacIntel',
+ configurable: true,
+ });
render(<Kbd keys="ctrl+alt+shift+k" />);
- expect(screen.getByText('\u2303')).toBeInTheDocument(); // \u2303
- expect(screen.getByText('\u2325')).toBeInTheDocument(); // \u2325
- expect(screen.getByText('\u21E7')).toBeInTheDocument(); // \u21E7
+ expect(screen.getByText('\u2303')).toBeInTheDocument(); // ⌃
+ expect(screen.getByText('\u2325')).toBeInTheDocument(); // ⌥
+ expect(screen.getByText('\u21E7')).toBeInTheDocument(); // ⇧
expect(screen.getByText('K')).toBeInTheDocument();
});
+ it.each(['Win32', 'Linux x86_64'])(
+ 'shows the catalog text for ctrl, alt, shift and meta on %s',
+ platform => {
+ Object.defineProperty(navigator, 'platform', {
+ value: platform,
+ configurable: true,
+ });
+ render(<Kbd keys="ctrl+alt+shift+meta+k" />);
+ for (const text of ['Ctrl', 'Alt', 'Shift', 'Win', 'K']) {
+ expect(screen.getByText(text)).toBeInTheDocument();
+ }
+ for (const glyph of ['\u2303', '\u2325', '\u21E7', 'META']) {
+ expect(screen.queryByText(glyph)).not.toBeInTheDocument();
+ }
+ // Spoken names are unchanged.
+ expect(screen.getByRole('img')).toHaveAccessibleName(
+ 'Control + Alt + Shift + META + K',
+ );
+ },
+ );
+
+ it('shows the catalog text for ctrl, alt, shift and meta on the server, even on a Mac', () => {
+ Object.defineProperty(navigator, 'platform', {
+ value: 'MacIntel',
+ configurable: true,
+ });
+ const container = document.createElement('div');
+ container.innerHTML = renderToString(<Kbd keys="ctrl+alt+shift+meta+k" />);
+ document.body.appendChild(container);
+ try {
+ for (const text of ['Ctrl', 'Alt', 'Shift', 'Win']) {
+ expect(within(container).getByText(text)).toBeInTheDocument();
+ }
+ expect(within(container).queryByText('\u2325')).not.toBeInTheDocument();
+ } finally {
+ container.remove();
+ }
+ });
+
+ it('hydrates a server render on a Mac without a mismatch, then shows the symbols', async () => {
+ Object.defineProperty(navigator, 'platform', {
+ value: 'MacIntel',
+ configurable: true,
+ });
+ const container = document.createElement('div');
+ container.innerHTML = renderToString(<Kbd keys="ctrl+alt+shift+meta+k" />);
+ document.body.appendChild(container);
+ const consoleError = vi
+ .spyOn(console, 'error')
+ .mockImplementation(() => {});
+ const recoverableErrors: unknown[] = [];
+ try {
+ expect(within(container).getByText('Win')).toBeInTheDocument();
+ await act(async () => {
+ hydrateRoot(container, <Kbd keys="ctrl+alt+shift+meta+k" />, {
+ onRecoverableError: error => recoverableErrors.push(error),
+ });
+ });
+ expect(recoverableErrors).toEqual([]);
+ expect(consoleError).not.toHaveBeenCalled();
+ for (const glyph of ['\u2303', '\u2325', '\u21E7']) {
+ expect(within(container).getByText(glyph)).toBeInTheDocument();
+ }
+ } finally {
+ container.remove();
+ }
+ });
+
+ it('localizes the modifiers short text', () => {
+ render(
+ <InternationalizationProvider
+ locale="de"
+ overrides={{
+ de: {
+ '@astryx.kbd.key.controlShort': 'Strg',
+ '@astryx.kbd.key.altShort': 'Alt Gr',
+ '@astryx.kbd.key.shiftShort': 'Umschalt',
+ '@astryx.kbd.key.windowsShort': 'Windows',
+ },
+ }}>
+ <Kbd keys="ctrl+alt+shift+meta" />
+ </InternationalizationProvider>,
+ );
+ for (const text of ['Strg', 'Alt Gr', 'Umschalt', 'Windows']) {
+ expect(screen.getByText(text)).toBeInTheDocument();
+ }
+ });
+
it('maps special keys', () => {
render(<Kbd keys="enter" />);
expect(screen.getByText('\u21B5')).toBeInTheDocument(); // \u21B5
@@ -219,7 +312,7 @@ describe('Kbd', () => {
it('renders "plus" as a literal + key', () => {
render(<Kbd keys="shift+plus" />);
- expect(screen.getByText('⇧')).toBeInTheDocument();
+ expect(screen.getByText('Shift')).toBeInTheDocument();
expect(screen.getByText('+')).toBeInTheDocument();
});
@@ -234,11 +327,16 @@ describe('Kbd', () => {
});
it.each([
- {platform: 'Linux', key: 'control', expectedGlyph: 'Ctrl'},
- {platform: 'MacIntel', key: 'command', expectedGlyph: '⌘'},
+ {
+ platform: 'Linux',
+ key: 'control',
+ expectedGlyph: 'Ctrl',
+ shiftGlyph: 'Shift',
+ },
+ {platform: 'MacIntel', key: 'command', expectedGlyph: '⌘', shiftGlyph: '⇧'},
])(
'localizes modifier labels on $platform without changing the glyph',
- ({platform, key, expectedGlyph}) => {
+ ({platform, key, expectedGlyph, shiftGlyph}) => {
Object.defineProperty(navigator, 'platform', {
value: platform,
configurable: true,
@@ -258,7 +356,7 @@ describe('Kbd', () => {
'Modificateur + Majuscule + K',
);
expect(screen.getByText(expectedGlyph)).toBeInTheDocument();
- expect(screen.getByText('⇧')).toBeInTheDocument();
+ expect(screen.getByText(shiftGlyph)).toBeInTheDocument();
rerender(
<InternationalizationProvider locale="en" overrides={overrides}>
<Kbd keys="mod+shift+k" />
diff --git a/packages/core/src/Kbd/Kbd.tsx b/packages/core/src/Kbd/Kbd.tsx
index 037d05bfbe..445219ba84 100644
--- a/packages/core/src/Kbd/Kbd.tsx
+++ b/packages/core/src/Kbd/Kbd.tsx
@@ -67,15 +67,8 @@ const styles = stylex.create({
},
});
-/**
- * Map of modifier key names to display symbols.
- * Note: `mod` is not in this map — it resolves dynamically via platform
- * detection inside the component.
- */
+/** Symbols that every platform shows. Modifier text depends on the platform. */
const KEY_DISPLAY = new Map<string, string>([
- ['ctrl', '\u2303'], // ⌃
- ['alt', '\u2325'], // ⌥
- ['shift', '\u21E7'], // ⇧
['enter', '\u21B5'], // ↵
['backspace', '\u232B'], // ⌫
['tab', '\u21E5'], // ⇥
@@ -86,19 +79,36 @@ const KEY_DISPLAY = new Map<string, string>([
['plus', '+'],
]);
+const APPLE_MODIFIER_DISPLAY = new Map<string, string>([
+ ['mod', '\u2318'], // ⌘
+ ['ctrl', '\u2303'], // ⌃
+ ['alt', '\u2325'], // ⌥
+ ['shift', '\u21E7'], // ⇧
+]);
+
+/** Catalog keys for the modifiers' short text elsewhere and before hydration. */
+const MODIFIER_SHORT_TEXT = new Map<string, string>([
+ ['mod', '@astryx.kbd.key.controlShort'],
+ ['ctrl', '@astryx.kbd.key.controlShort'],
+ ['alt', '@astryx.kbd.key.altShort'],
+ ['shift', '@astryx.kbd.key.shiftShort'],
+ ['meta', '@astryx.kbd.key.windowsShort'],
+]);
+
const KBD_KEY_ALIASES = new Map<string, string>([
['esc', 'escape'],
['return', 'enter'],
]);
-/**
- * Resolves a key name to its display string. Handles the platform-aware
- * `mod` key (⌘ on macOS, Ctrl on other platforms) and falls back to
- * KEY_DISPLAY or uppercased key name.
- */
+/** The server render has no platform, so it uses the non-Apple text. */
function getKeyDisplay(key: string, isMac: boolean, t: TranslatorFn): string {
- if (key === 'mod') {
- return isMac ? '\u2318' : t('@astryx.kbd.key.controlShort');
+ const appleSymbol = isMac ? APPLE_MODIFIER_DISPLAY.get(key) : undefined;
+ if (appleSymbol != null) {
+ return appleSymbol;
+ }
+ const shortText = isMac ? undefined : MODIFIER_SHORT_TEXT.get(key);
+ if (shortText != null) {
+ return t(shortText);
}
if (key === 'escape') {
return t('@astryx.kbd.key.escapeShort');
@@ -146,8 +156,9 @@ export interface KbdProps extends BaseProps<HTMLSpanElement> {
ref?: React.Ref<HTMLSpanElement>;
/**
* Keyboard shortcut string. Use "+" to separate keys.
- * Special keys: mod (Cmd on Mac), ctrl, alt, shift, enter, backspace, escape,
- * tab, up, down, left, and right.
+ * Special keys: mod, ctrl, alt and shift (Apple symbols on Apple platforms,
+ * short text such as "Ctrl" elsewhere and before hydration), meta ("Win"
+ * text elsewhere and before hydration), enter, backspace, escape, tab, up, down, left, and right.
* Aliases: "esc" for "escape" and "return" for "enter".
* Use "plus" to render a literal "+" key (e.g. "shift+plus").
*
diff --git a/packages/core/src/Kbd/__tests__/KbdAudit.a11y.chromium.spec.ts b/packages/core/src/Kbd/__tests__/KbdAudit.a11y.chromium.spec.ts
index 3c1b110e8e..147c2c4ec5 100644
--- a/packages/core/src/Kbd/__tests__/KbdAudit.a11y.chromium.spec.ts
+++ b/packages/core/src/Kbd/__tests__/KbdAudit.a11y.chromium.spec.ts
@@ -52,9 +52,10 @@ type AuditReceipt = {
// What each story shows, in document order: the visible text of every
// badge, then the spoken name of every shortcut. The CI browser is not an
-// Apple platform, so `mod` shows "Ctrl" and is spoken "Control".
+// Apple platform, so `mod` and `ctrl` show "Ctrl", `alt` and `shift` show
+// "Alt" and "Shift", and `mod` is spoken "Control".
const GLYPHS: Record<Story, string[]> = {
- 'modifier-combinations': ['Ctrl', 'K', '⇧', '↵', '⌃', 'C', '⌥', '⇥'],
+ 'modifier-combinations': ['Ctrl', 'K', 'Shift', '↵', 'Ctrl', 'C', 'Alt', '⇥'],
'special-keys': [
'Esc',
'Esc',
@@ -68,8 +69,15 @@ const GLYPHS: Record<Story, string[]> = {
'←',
'→',
],
- 'larger-text': [0, 1, 2].flatMap(() => ['Ctrl', 'K', '⇧', '↵', 'Esc', '↑']),
- 'inline-with-text': ['Ctrl', 'K', 'Ctrl', '⇧', 'P', 'Esc', '↑', '↓', '↵'],
+ 'larger-text': [0, 1, 2].flatMap(() => [
+ 'Ctrl',
+ 'K',
+ 'Shift',
+ '↵',
+ 'Esc',
+ '↑',
+ ]),
+ 'inline-with-text': ['Ctrl', 'K', 'Ctrl', 'Shift', 'P', 'Esc', '↑', '↓', '↵'],
'menu-shortcuts': [
'Ctrl',
'X',
@@ -80,7 +88,7 @@ const GLYPHS: Record<Story, string[]> = {
'Ctrl',
'Z',
'Ctrl',
- '⇧',
+ 'Shift',
'Z',
],
};