2.1 KB82 lines
Blame
1/**
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
8import {KeyCode, Modifier} from './KeyboardShortcuts';
9import {isMac, isWindows} from './OperatingSystem';
10
11import './Kbd.css';
12
13/** Keyboard key, useful for rendering keyboard shortcuts */
14export function Kbd({keycode, modifiers}: {keycode?: KeyCode; modifiers?: Array<Modifier>}) {
15 return (
16 <span className="kbd-group" title={asEntireString(keycode, modifiers)}>
17 {modifiers
18 ?.filter(modifier => modifier != Modifier.NONE)
19 .map(modifier => (
20 <kbd className="modifier" key={modifier}>
21 {modifierToIcon[modifier]}
22 </kbd>
23 ))}
24 {keycode != null && <kbd>{keycodeToString(keycode)}</kbd>}
25 </span>
26 );
27}
28
29function keycodeToString(keycode: KeyCode): string {
30 switch (keycode) {
31 case KeyCode.QuestionMark:
32 return '?';
33 case KeyCode.SingleQuote:
34 return "'";
35 case KeyCode.Period:
36 return '.';
37 case KeyCode.Escape:
38 return 'Esc';
39 case KeyCode.Plus:
40 return '+';
41 case KeyCode.Minus:
42 return '-';
43 default:
44 return String.fromCharCode(keycode).toUpperCase();
45 }
46}
47
48const modifierToIcon = isMac
49 ? ({
50 [Modifier.ALT]: '⌥',
51 [Modifier.CMD]: '⌘',
52 [Modifier.SHIFT]: '⇧',
53 [Modifier.CTRL]: '⌃',
54 [Modifier.NONE]: '',
55 } as const)
56 : ({
57 [Modifier.ALT]: 'Alt',
58 [Modifier.CMD]: isWindows ? 'Win' : 'Super',
59 [Modifier.SHIFT]: 'Shift',
60 [Modifier.CTRL]: 'Ctrl',
61 [Modifier.NONE]: '',
62 } as const);
63
64const modifierToString = {
65 [Modifier.ALT]: 'Alt',
66 [Modifier.CMD]: 'Command',
67 [Modifier.SHIFT]: 'Shift',
68 [Modifier.CTRL]: 'Control',
69 [Modifier.NONE]: '',
70} as const;
71
72function asEntireString(keycode?: KeyCode, modifiers?: Array<Modifier>): string {
73 const result: Array<string> = [];
74 for (const modifier of modifiers ?? []) {
75 result.push(modifierToString[modifier]);
76 }
77 if (keycode != null) {
78 result.push(keycodeToString(keycode));
79 }
80 return result.join(' + ');
81}
82