Skip to content

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

TypeScript

fix(core): normalize Kbd esc and return aliases (#5657)

Harjoth Khara7cce14f5c8f3
diff --git a/.changeset/kbd-key-aliases.md b/.changeset/kbd-key-aliases.md
new file mode 100644
index 0000000000..b41e34df34
--- /dev/null
+++ b/.changeset/kbd-key-aliases.md
@@ -0,0 +1,9 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Kbd: render the `esc` and `return` aliases with the same glyphs and accessible names as `escape` and `enter`
+
+This partial fix for #5403 normalizes the two unambiguous aliases already accepted by `useHotkeys`. Kbd now renders `esc` as `Esc` with the accessible name `Escape`, and `return` as `↵` with the accessible name `Enter`. Its lookup tables now also avoid prototype-chain collisions when rendering arbitrary key names. The platform-specific rendering contract for `meta` and display choice for `space` remain unresolved in #5403 pending separate API and design decisions.
+
+@harjothkhara
diff --git a/apps/storybook/stories/Kbd.stories.tsx b/apps/storybook/stories/Kbd.stories.tsx
index 3e45a2172a..c6891f0c4b 100644
--- a/apps/storybook/stories/Kbd.stories.tsx
+++ b/apps/storybook/stories/Kbd.stories.tsx
@@ -12,7 +12,7 @@ const meta: Meta<typeof Kbd> = {
keys: {
control: 'text',
description:
- 'Keyboard shortcut string. Use "+" to separate keys. Special keys: mod, ctrl, alt, shift, enter, backspace, escape, tab, up, down, left, right.',
+ 'Keyboard shortcut string. Use "+" to separate keys. Special keys: mod, ctrl, alt, shift, enter, backspace, escape, tab, up, down, left, right, plus. Aliases: esc for escape and return for enter.',
},
},
};
@@ -76,12 +76,14 @@ export const SpecialKeys: Story = {
Escape:
</Text>
<Kbd keys="escape" />
+ <Kbd keys="esc" />
</div>
<div style={{display: 'flex', gap: '16px', alignItems: 'center'}}>
<Text type="label" style={{width: '100px'}}>
Enter:
</Text>
<Kbd keys="enter" />
+ <Kbd keys="return" />
</div>
<div style={{display: 'flex', gap: '16px', alignItems: 'center'}}>
<Text type="label" style={{width: '100px'}}>
@@ -192,8 +194,8 @@ export const InlineWithText: Story = {
Press <Kbd keys="escape" /> to close the dialog.
</Text>
<Text type="body">
- Navigate with <Kbd keys="up" /> and <Kbd keys="down" /> arrow
- keys, then press <Kbd keys="enter" /> to select.
+ Navigate with <Kbd keys="up" /> and <Kbd keys="down" /> arrow keys, then
+ press <Kbd keys="enter" /> to select.
</Text>
</div>
),
diff --git a/packages/cli/assets/templates/blocks/components/Kbd/KbdModifierCombos.tsx b/packages/cli/assets/templates/blocks/components/Kbd/KbdModifierCombos.tsx
index 76bd49a8a0..cf9375549c 100644
--- a/packages/cli/assets/templates/blocks/components/Kbd/KbdModifierCombos.tsx
+++ b/packages/cli/assets/templates/blocks/components/Kbd/KbdModifierCombos.tsx
@@ -21,9 +21,11 @@ export default function KbdModifierCombos() {
<Kbd keys="mod+shift+p" />
</HStack>
<HStack gap={4}>
- <Text type="body">Special keys:</Text>
+ <Text type="body">Special keys and aliases:</Text>
<Kbd keys="escape" />
+ <Kbd keys="esc" />
<Kbd keys="enter" />
+ <Kbd keys="return" />
<Kbd keys="backspace" />
<Kbd keys="tab" />
<Kbd keys="space" />
diff --git a/packages/core/src/Kbd/Kbd.doc.mjs b/packages/core/src/Kbd/Kbd.doc.mjs
index b3492bad23..c8e142a1b3 100644
--- a/packages/core/src/Kbd/Kbd.doc.mjs
+++ b/packages/core/src/Kbd/Kbd.doc.mjs
@@ -27,7 +27,7 @@ export const docs = {
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.',
+ '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.',
required: true,
},
{
@@ -72,7 +72,7 @@ export const docsZh = {
name: 'keys',
type: 'string',
description:
- '键盘快捷键字符串。使用 "+" 分隔各按键。特殊按键:mod(Mac 上为 Cmd)、ctrl、alt、shift、enter、backspace、escape、tab、up、down、left、right。',
+ '键盘快捷键字符串。使用 "+" 分隔各按键。特殊按键:mod(Mac 上为 Cmd)、ctrl、alt、shift、enter、backspace、escape、tab、up、down、left、right、plus。别名:esc 等同于 escape,return 等同于 enter。',
required: true,
},
{
@@ -122,7 +122,7 @@ export const docsDense = {
],
},
propDescriptions: {
- keys: 'Shortcut string. "+" separates keys. Special: mod (Cmd on Mac), ctrl, alt, shift, enter, backspace, escape, tab, up, down, left, right.',
+ 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.',
diff --git a/packages/core/src/Kbd/Kbd.test.tsx b/packages/core/src/Kbd/Kbd.test.tsx
index 65fc7e0725..9240a6e6b5 100644
--- a/packages/core/src/Kbd/Kbd.test.tsx
+++ b/packages/core/src/Kbd/Kbd.test.tsx
@@ -10,13 +10,14 @@
*/
import {render, screen} from '@testing-library/react';
-import {describe, it, expect, afterEach} from 'vitest';
+import {describe, it, expect, afterEach, vi} from 'vitest';
import {Kbd} from './Kbd';
describe('Kbd', () => {
const originalPlatform = navigator.platform;
afterEach(() => {
+ vi.restoreAllMocks();
// Restore platform after any test that spoofs it \u2014 ensures no
// test pollution even if an assertion fails mid-test.
Object.defineProperty(navigator, 'platform', {
@@ -72,6 +73,61 @@ describe('Kbd', () => {
expect(screen.getByText('Esc')).toBeInTheDocument();
});
+ it.each([
+ {alias: 'esc', display: 'Esc', label: 'Escape'},
+ {alias: 'return', display: '\u21B5', label: 'Enter'},
+ ])('normalizes the $alias key alias', ({alias, display, label}) => {
+ render(<Kbd keys={alias} />);
+ expect(screen.getByText(display)).toBeInTheDocument();
+ expect(screen.getByRole('img')).toHaveAttribute('aria-label', label);
+ });
+
+ it.each([
+ {alias: 'esc', canonical: 'escape'},
+ {alias: 'return', canonical: 'enter'},
+ ])('$alias renders identically to $canonical', ({alias, canonical}) => {
+ const {container, rerender} = render(<Kbd keys={canonical} />);
+ const text = container.textContent;
+ const label = screen.getByRole('img').getAttribute('aria-label');
+ rerender(<Kbd keys={alias} />);
+ expect(container.textContent).toBe(text);
+ expect(screen.getByRole('img').getAttribute('aria-label')).toBe(label);
+ });
+
+ it.each([
+ {keys: 'ctrl + ESC', display: 'Esc', label: 'Control + Escape'},
+ {keys: 'shift + RETURN', display: '\u21B5', label: 'Shift + Enter'},
+ ])('normalizes aliases inside the $keys combo', ({keys, display, label}) => {
+ render(<Kbd keys={keys} />);
+ expect(screen.getByText(display)).toBeInTheDocument();
+ expect(screen.getByRole('img')).toHaveAttribute('aria-label', label);
+ });
+
+ it('keeps child keys unique after alias normalization', () => {
+ const consoleError = vi
+ .spyOn(console, 'error')
+ .mockImplementation(() => {});
+ const {container} = render(
+ <Kbd keys="escape+esc+ESC+enter+return+return" />,
+ );
+ expect(consoleError).not.toHaveBeenCalled();
+ expect(
+ Array.from(container.querySelectorAll('kbd'), key => key.textContent),
+ ).toEqual(['Esc', 'Esc', 'Esc', '↵', '↵', '↵']);
+ });
+
+ it.each(['constructor', '__proto__'])(
+ 'renders the unknown %s key without consulting object prototypes',
+ key => {
+ render(<Kbd keys={key} />);
+ expect(screen.getByText(key.toUpperCase())).toBeInTheDocument();
+ expect(screen.getByRole('img')).toHaveAttribute(
+ 'aria-label',
+ key.toUpperCase(),
+ );
+ },
+ );
+
it('exposes a spoken accessible name and hides the glyphs (obs-1)', () => {
render(<Kbd keys="mod+shift+k" />);
// The wrapper carries a screen-reader name built from spoken key labels
diff --git a/packages/core/src/Kbd/Kbd.tsx b/packages/core/src/Kbd/Kbd.tsx
index 20fc5ce20a..2a751e09d3 100644
--- a/packages/core/src/Kbd/Kbd.tsx
+++ b/packages/core/src/Kbd/Kbd.tsx
@@ -4,8 +4,8 @@
/**
* @file Kbd.tsx
- * @input Uses React, StyleX, theme tokens
- * @output Exports Kbd component and KbdProps
+ * @input Uses React, StyleX, theme tokens, shortcut key names and aliases
+ * @output Exports Kbd component and KbdProps with canonical shortcut labels
* @position Core implementation; renders styled keyboard shortcut indicators
*
* SYNC: When modified, update:
@@ -61,20 +61,25 @@ const styles = stylex.create({
* Note: `mod` is not in this map — it resolves dynamically via platform
* detection inside the component.
*/
-const KEY_DISPLAY: Record<string, string> = {
- ctrl: '\u2303', // ⌃
- alt: '\u2325', // ⌥
- shift: '\u21E7', // ⇧
- enter: '\u21B5', // ↵
- backspace: '\u232B', // ⌫
- escape: 'Esc',
- tab: '\u21E5', // ⇥
- up: '\u2191',
- down: '\u2193',
- left: '\u2190',
- right: '\u2192',
- plus: '+',
-};
+const KEY_DISPLAY = new Map<string, string>([
+ ['ctrl', '\u2303'], // ⌃
+ ['alt', '\u2325'], // ⌥
+ ['shift', '\u21E7'], // ⇧
+ ['enter', '\u21B5'], // ↵
+ ['backspace', '\u232B'], // ⌫
+ ['escape', 'Esc'],
+ ['tab', '\u21E5'], // ⇥
+ ['up', '\u2191'],
+ ['down', '\u2193'],
+ ['left', '\u2190'],
+ ['right', '\u2192'],
+ ['plus', '+'],
+]);
+
+const KBD_KEY_ALIASES = new Map<string, string>([
+ ['esc', 'escape'],
+ ['return', 'enter'],
+]);
/**
* Resolves a key name to its display string. Handles the platform-aware
@@ -85,7 +90,7 @@ function getKeyDisplay(key: string, isMac: boolean): string {
if (key === 'mod') {
return isMac ? '\u2318' : 'Ctrl';
}
- return KEY_DISPLAY[key] ?? key.toUpperCase();
+ return KEY_DISPLAY.get(key) ?? key.toUpperCase();
}
/**
@@ -93,26 +98,26 @@ function getKeyDisplay(key: string, isMac: boolean): string {
* (⌘, ⇧, ↵, …) that assistive tech cannot announce meaningfully, so the
* accessible name for the shortcut is built from these words instead.
*/
-const KEY_LABEL: Record<string, string> = {
- ctrl: 'Control',
- alt: 'Alt',
- shift: 'Shift',
- enter: 'Enter',
- backspace: 'Backspace',
- escape: 'Escape',
- tab: 'Tab',
- up: 'Up arrow',
- down: 'Down arrow',
- left: 'Left arrow',
- right: 'Right arrow',
- plus: 'Plus',
-};
+const KEY_LABEL = new Map<string, string>([
+ ['ctrl', 'Control'],
+ ['alt', 'Alt'],
+ ['shift', 'Shift'],
+ ['enter', 'Enter'],
+ ['backspace', 'Backspace'],
+ ['escape', 'Escape'],
+ ['tab', 'Tab'],
+ ['up', 'Up arrow'],
+ ['down', 'Down arrow'],
+ ['left', 'Left arrow'],
+ ['right', 'Right arrow'],
+ ['plus', 'Plus'],
+]);
function getKeyLabel(key: string, isMac: boolean): string {
if (key === 'mod') {
return isMac ? 'Command' : 'Control';
}
- return KEY_LABEL[key] ?? key.toUpperCase();
+ return KEY_LABEL.get(key) ?? key.toUpperCase();
}
function subscribeToPlatformChanges(): () => void {
@@ -127,7 +132,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.
+ * Special keys: mod (Cmd on Mac), ctrl, alt, shift, 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").
*
* @example
@@ -163,11 +170,24 @@ export function Kbd({keys, ref, xstyle, className, style, ...rest}: KbdProps) {
getServerPlatformSnapshot,
);
- const parts = keys.split('+').map(key => key.trim().toLowerCase());
+ const keyOccurrences = new Map<string, number>();
+ const parts = keys
+ .split('+')
+ .map(key => key.trim().toLowerCase())
+ .map(sourceKey => {
+ const occurrence = keyOccurrences.get(sourceKey) ?? 0;
+ keyOccurrences.set(sourceKey, occurrence + 1);
+ return {
+ key: KBD_KEY_ALIASES.get(sourceKey) ?? sourceKey,
+ reactKey: `${sourceKey}:${occurrence}`,
+ };
+ });
// Screen-reader name: the joined spoken labels (e.g. "Command + K"), since
// the visual glyphs below are announced meaninglessly by assistive tech.
- const accessibleName = parts.map(key => getKeyLabel(key, isMac)).join(' + ');
+ const accessibleName = parts
+ .map(({key}) => getKeyLabel(key, isMac))
+ .join(' + ');
return (
<span
@@ -181,8 +201,8 @@ export function Kbd({keys, ref, xstyle, className, style, ...rest}: KbdProps) {
className,
style,
)}>
- {parts.map(key => (
- <kbd key={key} aria-hidden="true" {...stylex.props(styles.kbd)}>
+ {parts.map(({key, reactKey}) => (
+ <kbd key={reactKey} aria-hidden="true" {...stylex.props(styles.kbd)}>
{getKeyDisplay(key, isMac)}
</kbd>
))}