@estiva-app/ui 0.111.0 → 0.112.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -24,4 +24,13 @@ export declare function isApplePlatform(): boolean;
24
24
  * straight through from wherever it was read.
25
25
  */
26
26
  export declare function shortcutLabel(keys: string, apple?: boolean): string;
27
+ /** Whether a key press is the shortcut `keys` names, in the spelling above (`Mod-K`, `Mod-Shift-O`). */
28
+ export declare function matchesShortcut(event: Pick<KeyboardEvent, 'key' | 'metaKey' | 'ctrlKey' | 'shiftKey' | 'altKey'>, keys: string): boolean;
29
+ /**
30
+ * A key that does something from anywhere on the page while the caller is on
31
+ * screen, such as `Mod-K` for search. The browser's own meaning of the key
32
+ * (Ctrl+O, open a file) is taken over: the press is consumed. Off while
33
+ * `enabled` is false. The latest `onPress` runs, so it need not be stable.
34
+ */
35
+ export declare function useShortcut(keys: string, onPress: () => void, enabled?: boolean): void;
27
36
  //# sourceMappingURL=shortcuts.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"shortcuts.d.ts","sourceRoot":"","sources":["../src/shortcuts.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAEH,oEAAoE;AACpE,wBAAgB,eAAe,IAAI,OAAO,CAGzC;AAED;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,UAAoB,GAAG,MAAM,CAS7E"}
1
+ {"version":3,"file":"shortcuts.d.ts","sourceRoot":"","sources":["../src/shortcuts.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAIH,oEAAoE;AACpE,wBAAgB,eAAe,IAAI,OAAO,CAGzC;AAED;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,UAAoB,GAAG,MAAM,CAS7E;AAED,wGAAwG;AACxG,wBAAgB,eAAe,CAAC,KAAK,EAAE,IAAI,CAAC,aAAa,EAAE,KAAK,GAAG,SAAS,GAAG,SAAS,GAAG,UAAU,GAAG,QAAQ,CAAC,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAUxI;AAED;;;;;GAKG;AACH,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,IAAI,EAAE,OAAO,UAAO,GAAG,IAAI,CAiBnF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@estiva-app/ui",
3
- "version": "0.111.0",
3
+ "version": "0.112.0",
4
4
  "description": "Estiva's design tokens (the contract) and a small set of primitives (a convenience) for every Estiva app.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/registry.json CHANGED
@@ -4,8 +4,8 @@
4
4
  "kind": "package",
5
5
  "repo": "estiva-ui",
6
6
  "package": "@estiva-app/ui",
7
- "packageVersion": "0.111.0",
8
- "exports": 252,
7
+ "packageVersion": "0.112.0",
8
+ "exports": 253,
9
9
  "typeExports": 263,
10
10
  "files": null
11
11
  },
@@ -12526,6 +12526,25 @@
12526
12526
  "app": null,
12527
12527
  "looks": []
12528
12528
  },
12529
+ {
12530
+ "name": "useShortcut",
12531
+ "repo": "estiva-ui",
12532
+ "kind": "hook",
12533
+ "importPath": "@estiva-app/ui",
12534
+ "sourceFile": "src/shortcuts.ts",
12535
+ "purpose": "A key that does something from anywhere on the page while the caller is on screen, such as `Mod-K` for search.",
12536
+ "purposeFrom": "comment",
12537
+ "props": [],
12538
+ "variants": [],
12539
+ "ownsBehaviours": [],
12540
+ "status": "stable",
12541
+ "migrationStage": null,
12542
+ "docsId": null,
12543
+ "storyId": null,
12544
+ "docPage": null,
12545
+ "app": null,
12546
+ "looks": []
12547
+ },
12529
12548
  {
12530
12549
  "name": "useSidebarFold",
12531
12550
  "repo": "estiva-ui",
package/src/Kbd.mdx CHANGED
@@ -22,6 +22,11 @@ content and never shrinking.
22
22
  the key that puts the cursor in it.
23
23
  - **In a shortcuts sheet**, where the key is the content rather than a hint.
24
24
 
25
+ The key itself is bound with `useShortcut('Mod-O', onPress, enabled)`, in the
26
+ same spelling `shortcutLabel` reads: it runs from anywhere on the page while
27
+ its caller is on screen, and takes the key from the browser (Ctrl+O no longer
28
+ opens a file). Show the hint with `shortcutLabel` of the same string.
29
+
25
30
  ## Naming the key
26
31
 
27
32
  The label is a word, never a symbol — `Cmd+K`, `Enter`, `Esc`, `Backspace`.
package/src/TopBar.tsx CHANGED
@@ -1,9 +1,9 @@
1
- import { useEffect, useRef, type ReactNode } from 'react'
1
+ import { type ReactNode } from 'react'
2
2
  import { Button as BaseButton } from '@base-ui/react/button'
3
3
  import { cn } from './cn'
4
4
  import { Kbd } from './Kbd'
5
5
  import { FIELD_SHELL_CLASSES } from './looks'
6
- import { shortcutLabel } from './shortcuts'
6
+ import { shortcutLabel, useShortcut } from './shortcuts'
7
7
 
8
8
  /**
9
9
  * The 52px top bar, in three manners:
@@ -58,24 +58,9 @@ export interface TopBarProps {
58
58
 
59
59
  export function TopBar({ variant = 'solid', menu, logo, search, onSearch, searchPlaceholder = 'Search…', right, className }: TopBarProps) {
60
60
  const floating = variant === 'floating'
61
- // The latest handler, so the key listener is set once rather than on every render.
62
- const searchRef = useRef(onSearch)
63
- useEffect(() => {
64
- searchRef.current = onSearch
65
- })
66
- const searches = onSearch !== undefined
67
- useEffect(() => {
68
- if (!searches) return
69
- const onKey = (event: KeyboardEvent) => {
70
- if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'k') {
71
- event.preventDefault()
72
- searchRef.current?.()
73
- }
74
- }
75
- // @estiva-escape(no-hand-rolled-behaviour): Ctrl+K opens search from anywhere on the page, which is a page-wide shortcut and not a floating part; no part listens for a key across the page
76
- window.addEventListener('keydown', onKey)
77
- return () => window.removeEventListener('keydown', onKey)
78
- }, [searches])
61
+ // Ctrl+K opens search from anywhere on the page, and Ctrl+Shift+K as it always has.
62
+ useShortcut('Mod-K', () => onSearch?.(), onSearch !== undefined)
63
+ useShortcut('Mod-Shift-K', () => onSearch?.(), onSearch !== undefined)
79
64
  const centre =
80
65
  search ??
81
66
  (onSearch && (
package/src/index.ts CHANGED
@@ -176,4 +176,4 @@ export { SectionLabel } from './SectionLabel'
176
176
  export { Tabs, type TabDef, type TabsProps } from './Tabs'
177
177
  export { Toast, ToastProvider, useToast, type ToastOptions, type ToastProps, type ToastType } from './Toast'
178
178
  export { cn } from './cn'
179
- export { isApplePlatform, shortcutLabel } from './shortcuts'
179
+ export { isApplePlatform, shortcutLabel, useShortcut } from './shortcuts'
@@ -48,20 +48,20 @@ describe('the registry builds', () => {
48
48
  expect(registry.entries.map((one) => one.name).sort()).toEqual(values.map((one) => one.name).sort())
49
49
  })
50
50
 
51
- it('counts 252 names over 129 files: 167 components, 78 helpers and 7 hooks (CornerMenu, the "…" over a row’s or a card’s corner with Show as and Remove (TOPI-5), on 10 November; ConversationHeading, which place a comment is on in a list mixing several places (TOPI-2), on 9 November; FollowSwitch, LevelIcon and WhoFollowsDialog, how you follow a place and who follows it (TEA-6), on 6 November; goneWords and GONE_CLOSED, what stands in a gone comment’s place and under its thread in every app (ONE-9), on 6 November; DeletedNotice and NoAccessNotice, the cards on a deleted file and on one you cannot open (ALO-4), on 3 November; useFormBusy, whether a Form around it is sending, read by the editor’s DocumentField from the main entry, in the review of 2 November; useLeftAt, sendsInLayout, useSeenOnScreen, showInConversation and showInConversationWhenDrawn, where a conversation scrolls, what was seen and a link landing on a comment, moved from Peek for every app, on 2 November; useRememberedOpen, the fold a section remembers, read by the app, and NAV_TREE_PENDING_MS and isPlainClick, Peek’s Folder timer and plain-click check, moved in, on 2 November; FormDialog, MoveDialog and ArchiveDialog, the dialogs Peek wired by hand, on 2 November; ConversationPlace, the line saying where a comment was said, and DocumentField, a rich-text field of a form, moved from Peek, on 2 November; ArchivedNotice, the card on an archived file, from Peek, Ship and Leaf, on 31 October; caretOnOpen, the box at a thread’s foot taking the caret when a ConversationLayout opens it, without scrolling, on 31 October; the conversation from Peek for every app, with PageHeader and PinnedComment, on 31 October, and ResolutionNote and ResolutionHistory gone with the resolved looks not picked, on 1 November; useSidebarFold, a folded sidebar kept folded in every app, on 31 October; cardShapeMemory, a card’s last shape on this device, lifted from Peek and Ship for Leaf, and ReferenceCards and useReferenceCards gone with their deprecated page, in the widget review, on 30 October; inTheBox, a card or part in a box being written in, on the files’ fill and in words, on 29 October; archivedLine, the line on an archived file in every app (PEEKM-2), on 23 October; keepCommentBoxWarm, a box built ahead, exported as 0.84.0 promised (PEEKM-1), on 21 October;linkedFrom and linkStateFrom, one card for a file in every app (5ebf2756), on 21 October; ComposeBox, ComposeKeys and COMPOSE_EDITOR_CLASSES gone into CommentBox’s own frame (one box), on 21 October; LinkPlaces with linkPlaceAt and staysChip, a link in a document drawn where it sits (WBD-4), on 20 October; DocumentEditor, one document editor for every app, and PersonReference, `@` in a document (WBD-3), on 20 October; toggleTableHeaderRow, a table’s header row on and off (LEAF-12), on 19 October;EntryShell, the screen while nobody is signed in, moved from Peek (AUT-3), on 17 October; CommentBox with commentBoxRows, and ReactionRow with AddReactionButton and whoReacted, the shared comment box and reaction row (COMM-2), on 17 October; the link widgets — LinkChip, LinkRow, LinkCard, CardUnder, PartCard, LinkPreview and their parts, with useCanHover, chosenOf, loadingShapeOf and unavailableMemory — from the Widgets 2 prototype, on 16 October; InlineText, a title or the line under it edited where it stands (SUM-4), on 16 October; ComposeBox with ComposeKeys and its classes, CommentHighlights with its five helpers, and keepSelection and releaseSelection, from the Leaf prototype (LEAF-4), on 16 October;NavTree, NavTreeSection, the composer triggers and UnreadDot joined on 2 October; BlockHandle and EditorBlockHandle (RIC-18) on 2 October, moveBlock and blockDropCursor, the drop in the gutter, on 5 October, MembersPill and MembersDialog, moved from Peek (SHI-31), on 6 October, ShowMore on 7 October, AppProvider on 8 October, and KindIcon, thingKindOf and PastedImages with its two helpers, moved from Peek, on 8 October; CodeBlockColours, the coloured code block of the editor, on 9 October; Checklist, Callout, isChecklistTick and calloutLook (RIC-19) on 13 October; EditorTableControls and its four actions (RIC-21) on 13 October; ReferenceCards, useReferenceCards and its three helpers, the card a chip in a document asks for, on 14 October; LinkChips and its two helpers, a URL in a document read as its chip, on 14 October; ReferenceMenu, ReferenceMenuView and three helpers, the menu of a chip while writing, on 14 October; PastedMarkdown, markdown pasted as the blocks it spells (LEAF-10), on 15 October; turnIntoRows, turnListInto and turnQuoteInto, the block menu’s Turn into for a list and a quote (LEAF-11), on 15 October)', () => {
51
+ it('counts 253 names over 129 files: 167 components, 78 helpers and 8 hooks (useShortcut, a key that works from anywhere on the page, for Peek’s Ctrl/Cmd+O to Add to Open work (TOPI-7), on 10 November; CornerMenu, the "…" over a row’s or a card’s corner with Show as and Remove (TOPI-5), on 10 November; ConversationHeading, which place a comment is on in a list mixing several places (TOPI-2), on 9 November; FollowSwitch, LevelIcon and WhoFollowsDialog, how you follow a place and who follows it (TEA-6), on 6 November; goneWords and GONE_CLOSED, what stands in a gone comment’s place and under its thread in every app (ONE-9), on 6 November; DeletedNotice and NoAccessNotice, the cards on a deleted file and on one you cannot open (ALO-4), on 3 November; useFormBusy, whether a Form around it is sending, read by the editor’s DocumentField from the main entry, in the review of 2 November; useLeftAt, sendsInLayout, useSeenOnScreen, showInConversation and showInConversationWhenDrawn, where a conversation scrolls, what was seen and a link landing on a comment, moved from Peek for every app, on 2 November; useRememberedOpen, the fold a section remembers, read by the app, and NAV_TREE_PENDING_MS and isPlainClick, Peek’s Folder timer and plain-click check, moved in, on 2 November; FormDialog, MoveDialog and ArchiveDialog, the dialogs Peek wired by hand, on 2 November; ConversationPlace, the line saying where a comment was said, and DocumentField, a rich-text field of a form, moved from Peek, on 2 November; ArchivedNotice, the card on an archived file, from Peek, Ship and Leaf, on 31 October; caretOnOpen, the box at a thread’s foot taking the caret when a ConversationLayout opens it, without scrolling, on 31 October; the conversation from Peek for every app, with PageHeader and PinnedComment, on 31 October, and ResolutionNote and ResolutionHistory gone with the resolved looks not picked, on 1 November; useSidebarFold, a folded sidebar kept folded in every app, on 31 October; cardShapeMemory, a card’s last shape on this device, lifted from Peek and Ship for Leaf, and ReferenceCards and useReferenceCards gone with their deprecated page, in the widget review, on 30 October; inTheBox, a card or part in a box being written in, on the files’ fill and in words, on 29 October; archivedLine, the line on an archived file in every app (PEEKM-2), on 23 October; keepCommentBoxWarm, a box built ahead, exported as 0.84.0 promised (PEEKM-1), on 21 October;linkedFrom and linkStateFrom, one card for a file in every app (5ebf2756), on 21 October; ComposeBox, ComposeKeys and COMPOSE_EDITOR_CLASSES gone into CommentBox’s own frame (one box), on 21 October; LinkPlaces with linkPlaceAt and staysChip, a link in a document drawn where it sits (WBD-4), on 20 October; DocumentEditor, one document editor for every app, and PersonReference, `@` in a document (WBD-3), on 20 October; toggleTableHeaderRow, a table’s header row on and off (LEAF-12), on 19 October;EntryShell, the screen while nobody is signed in, moved from Peek (AUT-3), on 17 October; CommentBox with commentBoxRows, and ReactionRow with AddReactionButton and whoReacted, the shared comment box and reaction row (COMM-2), on 17 October; the link widgets — LinkChip, LinkRow, LinkCard, CardUnder, PartCard, LinkPreview and their parts, with useCanHover, chosenOf, loadingShapeOf and unavailableMemory — from the Widgets 2 prototype, on 16 October; InlineText, a title or the line under it edited where it stands (SUM-4), on 16 October; ComposeBox with ComposeKeys and its classes, CommentHighlights with its five helpers, and keepSelection and releaseSelection, from the Leaf prototype (LEAF-4), on 16 October;NavTree, NavTreeSection, the composer triggers and UnreadDot joined on 2 October; BlockHandle and EditorBlockHandle (RIC-18) on 2 October, moveBlock and blockDropCursor, the drop in the gutter, on 5 October, MembersPill and MembersDialog, moved from Peek (SHI-31), on 6 October, ShowMore on 7 October, AppProvider on 8 October, and KindIcon, thingKindOf and PastedImages with its two helpers, moved from Peek, on 8 October; CodeBlockColours, the coloured code block of the editor, on 9 October; Checklist, Callout, isChecklistTick and calloutLook (RIC-19) on 13 October; EditorTableControls and its four actions (RIC-21) on 13 October; ReferenceCards, useReferenceCards and its three helpers, the card a chip in a document asks for, on 14 October; LinkChips and its two helpers, a URL in a document read as its chip, on 14 October; ReferenceMenu, ReferenceMenuView and three helpers, the menu of a chip while writing, on 14 October; PastedMarkdown, markdown pasted as the blocks it spells (LEAF-10), on 15 October; turnIntoRows, turnListInto and turnQuoteInto, the block menu’s Turn into for a list and a quote (LEAF-11), on 15 October)', () => {
52
52
  // The reconciliation GATES.md §24 explains. If this changes, that changes.
53
53
  // The `EDITOR_EXTENSIONS` count as components by their names; they are
54
54
  // editor extensions, documented on SelectionToolbar's, BlockNodes' and
55
55
  // ComposerTriggers' pages.
56
56
  const kinds = registry.entries.reduce<Record<string, number>>((all, one) => ({ ...all, [one.kind]: (all[one.kind] ?? 0) + 1 }), {})
57
- expect(kinds).toEqual({ component: 167, helper: 78, hook: 7 })
57
+ expect(kinds).toEqual({ component: 167, helper: 78, hook: 8 })
58
58
  expect(new Set(registry.entries.map((one) => one.sourceFile)).size).toBe(129)
59
59
  })
60
60
 
61
61
  it('gives every entry a purpose, from its own page or from the comment above it', () => {
62
62
  expect(registry.entries.filter((one) => one.purpose.trim() === '')).toEqual([])
63
63
  expect(registry.entries.filter((one) => one.purposeFrom === 'page').length).toBe(116)
64
- expect(registry.entries.filter((one) => one.purposeFrom === 'comment').length).toBe(136)
64
+ expect(registry.entries.filter((one) => one.purposeFrom === 'comment').length).toBe(137)
65
65
  })
66
66
 
67
67
  it('takes a name with a page of its own from the page, and a name without one from the code', () => {
@@ -289,6 +289,7 @@ describe('the ids point at something', () => {
289
289
  'useFormBusy',
290
290
  'useLeftAt',
291
291
  'useSeenOnScreen',
292
+ 'useShortcut',
292
293
  ])
293
294
  expect(without.every((one) => one.kind !== 'component')).toBe(true)
294
295
  })
@@ -0,0 +1,99 @@
1
+ // @vitest-environment jsdom
2
+ import { afterEach, describe, expect, it, vi } from 'vitest'
3
+ import { cleanup, renderHook } from '@testing-library/react'
4
+ import { useShortcut } from './shortcuts'
5
+
6
+ afterEach(cleanup)
7
+
8
+ const press = (init: KeyboardEventInit) => {
9
+ const event = new KeyboardEvent('keydown', { bubbles: true, cancelable: true, ...init })
10
+ window.dispatchEvent(event)
11
+ return event
12
+ }
13
+
14
+ describe('useShortcut', () => {
15
+ it.each([
16
+ ['Ctrl+O', { ctrlKey: true, key: 'o' }],
17
+ ['Cmd+O', { metaKey: true, key: 'o' }],
18
+ ['Ctrl+O with Caps Lock', { ctrlKey: true, key: 'O' }],
19
+ ])('runs on %s and keeps the browser from opening a file', (_name, init) => {
20
+ const onPress = vi.fn()
21
+ renderHook(() => useShortcut('Mod-O', onPress))
22
+ const event = press(init)
23
+ expect(onPress).toHaveBeenCalledTimes(1)
24
+ expect(event.defaultPrevented).toBe(true)
25
+ })
26
+
27
+ it.each([
28
+ ['O alone', { key: 'o' }],
29
+ ['Ctrl+P', { ctrlKey: true, key: 'p' }],
30
+ ])('leaves %s to the page', (_name, init) => {
31
+ const onPress = vi.fn()
32
+ renderHook(() => useShortcut('Mod-O', onPress))
33
+ expect(press(init).defaultPrevented).toBe(false)
34
+ expect(onPress).not.toHaveBeenCalled()
35
+ })
36
+
37
+ it('needs the Shift it names, and leaves one it does not name to the browser', () => {
38
+ const named = vi.fn()
39
+ const plain = vi.fn()
40
+ renderHook(() => useShortcut('Mod-Shift-O', named))
41
+ renderHook(() => useShortcut('Mod-O', plain))
42
+ press({ ctrlKey: true, key: 'o' })
43
+ expect(named).not.toHaveBeenCalled()
44
+ expect(plain).toHaveBeenCalledTimes(1)
45
+ press({ ctrlKey: true, shiftKey: true, key: 'O' })
46
+ expect(named).toHaveBeenCalledTimes(1)
47
+ expect(plain).toHaveBeenCalledTimes(1)
48
+ })
49
+
50
+ it('runs once for a held key, not for each repeat', () => {
51
+ const onPress = vi.fn()
52
+ renderHook(() => useShortcut('Mod-O', onPress))
53
+ press({ ctrlKey: true, key: 'o' })
54
+ press({ ctrlKey: true, key: 'o', repeat: true })
55
+ press({ ctrlKey: true, key: 'o', repeat: true })
56
+ expect(onPress).toHaveBeenCalledTimes(1)
57
+ })
58
+
59
+ it('leaves a press something on the page already took', () => {
60
+ const onPress = vi.fn()
61
+ renderHook(() => useShortcut('Mod-O', onPress))
62
+ const taken = new KeyboardEvent('keydown', { bubbles: true, cancelable: true, ctrlKey: true, key: 'o' })
63
+ taken.preventDefault()
64
+ window.dispatchEvent(taken)
65
+ expect(onPress).not.toHaveBeenCalled()
66
+ })
67
+
68
+ it('takes a minus as the key', () => {
69
+ const onPress = vi.fn()
70
+ renderHook(() => useShortcut('Mod--', onPress))
71
+ press({ ctrlKey: true, key: '-' })
72
+ expect(onPress).toHaveBeenCalledTimes(1)
73
+ })
74
+
75
+ it('does nothing, and leaves the key to the browser, while off', () => {
76
+ const onPress = vi.fn()
77
+ renderHook(() => useShortcut('Mod-O', onPress, false))
78
+ expect(press({ ctrlKey: true, key: 'o' }).defaultPrevented).toBe(false)
79
+ expect(onPress).not.toHaveBeenCalled()
80
+ })
81
+
82
+ it('stops listening once its caller leaves the screen', () => {
83
+ const onPress = vi.fn()
84
+ const { unmount } = renderHook(() => useShortcut('Mod-O', onPress))
85
+ unmount()
86
+ expect(press({ ctrlKey: true, key: 'o' }).defaultPrevented).toBe(false)
87
+ expect(onPress).not.toHaveBeenCalled()
88
+ })
89
+
90
+ it('runs the latest handler', () => {
91
+ const first = vi.fn()
92
+ const second = vi.fn()
93
+ const { rerender } = renderHook(({ run }) => useShortcut('Mod-O', run), { initialProps: { run: first } })
94
+ rerender({ run: second })
95
+ press({ ctrlKey: true, key: 'o' })
96
+ expect(first).not.toHaveBeenCalled()
97
+ expect(second).toHaveBeenCalledTimes(1)
98
+ })
99
+ })
package/src/shortcuts.ts CHANGED
@@ -16,6 +16,8 @@
16
16
  * only the app knows which platform it is looking at.
17
17
  */
18
18
 
19
+ import { useEffect, useRef } from 'react'
20
+
19
21
  /** Whether this machine calls the modifier Cmd rather than Ctrl. */
20
22
  export function isApplePlatform(): boolean {
21
23
  if (typeof navigator === 'undefined') return false
@@ -38,3 +40,41 @@ export function shortcutLabel(keys: string, apple = isApplePlatform()): string {
38
40
  })
39
41
  .join('+')
40
42
  }
43
+
44
+ /** Whether a key press is the shortcut `keys` names, in the spelling above (`Mod-K`, `Mod-Shift-O`). */
45
+ export function matchesShortcut(event: Pick<KeyboardEvent, 'key' | 'metaKey' | 'ctrlKey' | 'shiftKey' | 'altKey'>, keys: string): boolean {
46
+ // The key is what follows the last joining '-', so `Mod--` is Mod and '-'.
47
+ const at = keys.lastIndexOf('-', keys.length - 2)
48
+ const key = keys.slice(at + 1)
49
+ const mods = new Set(at < 0 ? [] : keys.slice(0, at).split('-'))
50
+ // Mod is Cmd or Ctrl on any machine, as the top bar's Ctrl+K always took either. Shift and Alt are exact: Mod-O is
51
+ // not Ctrl+Shift+O, which the browser keeps.
52
+ if (mods.has('Mod') ? !(event.metaKey || event.ctrlKey) : event.metaKey || event.ctrlKey) return false
53
+ if (mods.has('Shift') !== event.shiftKey || mods.has('Alt') !== event.altKey) return false
54
+ return event.key.toLowerCase() === key.toLowerCase()
55
+ }
56
+
57
+ /**
58
+ * A key that does something from anywhere on the page while the caller is on
59
+ * screen, such as `Mod-K` for search. The browser's own meaning of the key
60
+ * (Ctrl+O, open a file) is taken over: the press is consumed. Off while
61
+ * `enabled` is false. The latest `onPress` runs, so it need not be stable.
62
+ */
63
+ export function useShortcut(keys: string, onPress: () => void, enabled = true): void {
64
+ const pressRef = useRef(onPress)
65
+ useEffect(() => {
66
+ pressRef.current = onPress
67
+ })
68
+ useEffect(() => {
69
+ if (!enabled) return
70
+ const onKey = (event: KeyboardEvent) => {
71
+ // Once per press, not per auto-repeat; and not a press something on the page already took, or an IME's.
72
+ if (event.repeat || event.defaultPrevented || event.isComposing || !matchesShortcut(event, keys)) return
73
+ event.preventDefault()
74
+ pressRef.current()
75
+ }
76
+ // @estiva-escape(no-hand-rolled-behaviour): the one listener for a page-wide shortcut, which no floating part owns; every app's shortcut goes through this hook
77
+ window.addEventListener('keydown', onKey)
78
+ return () => window.removeEventListener('keydown', onKey)
79
+ }, [keys, enabled])
80
+ }