An open source design system that's fully customizable and agent ready
TypeScript
fix(Kbd): SSR-safe platform detection for mod key (#1066)
Cindy Zhang6a9b3fbb65ef
diff --git a/packages/core/src/Kbd/XDSKbd.test.tsx b/packages/core/src/Kbd/XDSKbd.test.tsxindex b0d421b1a8..b85ac05782 100644--- a/packages/core/src/Kbd/XDSKbd.test.tsx+++ b/packages/core/src/Kbd/XDSKbd.test.tsx@@ -4,13 +4,24 @@* @output Tests for XDSKbd component** Note: Tests run in jsdom which reports a non-Mac platform,- * so `mod` resolves to "Ctrl" rather than "⌘".+ * so `mod` resolves to "Ctrl" rather than "\u2318" after the layout effect.*/import {render, screen} from '@testing-library/react';import {XDSKbd} from './XDSKbd';describe('XDSKbd', () => {+ const originalPlatform = navigator.platform;++ afterEach(() => {+ // Restore platform after any test that spoofs it \u2014 ensures no+ // test pollution even if an assertion fails mid-test.+ Object.defineProperty(navigator, 'platform', {+ value: originalPlatform,+ configurable: true,+ });+ });+it('renders a single key', () => {render(<XDSKbd keys="k" />);const kbd = screen.getByText('K');@@ -25,22 +36,32 @@ describe('XDSKbd', () => {});it('renders mod as Ctrl on non-Mac platforms', () => {- // jsdom is a non-Mac environment, so mod → Ctrl+ // jsdom is a non-Mac environment, so mod \u2192 Ctrlrender(<XDSKbd keys="mod" />);expect(screen.getByText('Ctrl')).toBeInTheDocument();});+ it('renders mod as \u2318 on Mac platforms', () => {+ Object.defineProperty(navigator, 'platform', {+ value: 'MacIntel',+ configurable: true,+ });++ render(<XDSKbd keys="mod" />);+ expect(screen.getByText('\u2318')).toBeInTheDocument(); // \u2318+ });+it('maps modifier keys to symbols', () => {render(<XDSKbd keys="ctrl+alt+shift+k" />);- expect(screen.getByText('\u2303')).toBeInTheDocument(); // ⌃- expect(screen.getByText('\u2325')).toBeInTheDocument(); // ⌥- expect(screen.getByText('\u21E7')).toBeInTheDocument(); // ⇧+ expect(screen.getByText('\u2303')).toBeInTheDocument(); // \u2303+ expect(screen.getByText('\u2325')).toBeInTheDocument(); // \u2325+ expect(screen.getByText('\u21E7')).toBeInTheDocument(); // \u21E7expect(screen.getByText('K')).toBeInTheDocument();});it('maps special keys', () => {render(<XDSKbd keys="enter" />);- expect(screen.getByText('\u21B5')).toBeInTheDocument(); // ↵+ expect(screen.getByText('\u21B5')).toBeInTheDocument(); // \u21B5});it('renders escape as text', () => {diff --git a/packages/core/src/Kbd/XDSKbd.tsx b/packages/core/src/Kbd/XDSKbd.tsxindex 44b4057bae..d027f85a0d 100644--- a/packages/core/src/Kbd/XDSKbd.tsx+++ b/packages/core/src/Kbd/XDSKbd.tsx@@ -1,3 +1,5 @@+'use client';+/*** @file XDSKbd.tsx* @input Uses React, StyleX, theme tokens@@ -9,6 +11,7 @@* - /packages/core/src/Kbd/index.ts*/+import {useState, useLayoutEffect} from 'react';import * as stylex from '@stylexjs/stylex';import type {StyleXStyles} from '@stylexjs/stylex';import {xdsClassName, mergeProps} from '../utils';@@ -49,25 +52,10 @@ const styles = stylex.create({},});-/**- * Lazy platform detection — SSR-safe, cached after first call.- * Returns true on macOS, iPhone, iPad, iPod; false elsewhere (including SSR).- */-let _isMac: boolean | null = null;-function isMac(): boolean {- if (_isMac === null) {- _isMac =- typeof navigator !== 'undefined' &&- /Mac|iPhone|iPad|iPod/.test(- navigator.platform ?? navigator.userAgent ?? '',- );- }- return _isMac;-}-/*** Map of modifier key names to display symbols.- * Note: `mod` is not in this map — it resolves dynamically via `getKeyDisplay`.+ * Note: `mod` is not in this map — it resolves dynamically via platform+ * detection inside the component.*/const KEY_DISPLAY: Record<string, string> = {ctrl: '\u2303', // ⌃@@ -88,13 +76,29 @@ const KEY_DISPLAY: Record<string, string> = {* `mod` key (⌘ on macOS, Ctrl on other platforms) and falls back to* KEY_DISPLAY or uppercased key name.*/-function getKeyDisplay(key: string): string {+function getKeyDisplay(key: string, isMac: boolean): string {if (key === 'mod') {- return isMac() ? '\u2318' : 'Ctrl';+ return isMac ? '\u2318' : 'Ctrl';}return KEY_DISPLAY[key] ?? key.toUpperCase();}+/**+ * Detects whether the current platform is macOS/iOS.+ * Prefers the User-Agent Client Hints API when available (modern Chrome/Edge),+ * falls back to navigator.platform (deprecated but universally supported).+ */+function detectMac(): boolean {+ if (typeof navigator === 'undefined') return false;+ // Prefer User-Agent Client Hints API (not deprecated)+ const uaData = 'userAgentData' in navigator ? navigator.userAgentData : null;+ if (uaData && typeof uaData === 'object' && 'platform' in uaData) {+ return /mac/i.test((uaData as {platform: string}).platform ?? '');+ }+ // Fallback: navigator.platform (deprecated but still shipped everywhere)+ return /Mac|iPhone|iPad|iPod/.test(navigator.platform ?? '');+}+export interface XDSKbdProps {/*** Keyboard shortcut string. Use "+" to separate keys.@@ -138,12 +142,23 @@ export interface XDSKbdProps {* A general-purpose component for rendering keyboard shortcuts* anywhere in the system — tooltips, menus, documentation, etc.*+ * Platform-aware: `mod` renders as ⌘ on macOS and Ctrl elsewhere.+ * SSR-safe — defers platform detection to a layout effect to avoid+ * hydration mismatches. Uses useLayoutEffect so the platform-correct+ * symbol is set before the browser paints (no visible flicker).+ ** @example* ```* <XDSKbd keys="mod+k" />* ```*/export function XDSKbd({keys, xstyle, className, style}: XDSKbdProps) {+ const [isMac, setIsMac] = useState(false);++ useLayoutEffect(() => {+ setIsMac(detectMac());+ }, []);+const parts = keys.split('+').map(key => key.trim().toLowerCase());return (@@ -157,7 +172,7 @@ export function XDSKbd({keys, xstyle, className, style}: XDSKbdProps) {aria-hidden="true">{parts.map((key, i) => (<kbd key={i} {...stylex.props(styles.kbd)}>- {getKeyDisplay(key)}+ {getKeyDisplay(key, isMac)}</kbd>))}</span>