@estiva-app/ui 0.111.0 → 0.113.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.113.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.113.0",
8
+ "exports": 253,
9
9
  "typeExports": 263,
10
10
  "files": null
11
11
  },
@@ -7660,6 +7660,12 @@
7660
7660
  "required": false,
7661
7661
  "note": "With `unread`: the warning badge in the dot's place."
7662
7662
  },
7663
+ {
7664
+ "name": "preview",
7665
+ "takes": "anything",
7666
+ "required": false,
7667
+ "note": "More about the row, in the package's `PreviewCard` while the row itself is pointed at — never the rows under it — such as a short list of what is new there."
7668
+ },
7663
7669
  {
7664
7670
  "name": "children",
7665
7671
  "takes": "anything",
@@ -12526,6 +12532,25 @@
12526
12532
  "app": null,
12527
12533
  "looks": []
12528
12534
  },
12535
+ {
12536
+ "name": "useShortcut",
12537
+ "repo": "estiva-ui",
12538
+ "kind": "hook",
12539
+ "importPath": "@estiva-app/ui",
12540
+ "sourceFile": "src/shortcuts.ts",
12541
+ "purpose": "A key that does something from anywhere on the page while the caller is on screen, such as `Mod-K` for search.",
12542
+ "purposeFrom": "comment",
12543
+ "props": [],
12544
+ "variants": [],
12545
+ "ownsBehaviours": [],
12546
+ "status": "stable",
12547
+ "migrationStage": null,
12548
+ "docsId": null,
12549
+ "storyId": null,
12550
+ "docPage": null,
12551
+ "app": null,
12552
+ "looks": []
12553
+ },
12529
12554
  {
12530
12555
  "name": "useSidebarFold",
12531
12556
  "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/NavItem.mdx CHANGED
@@ -59,6 +59,14 @@ count — a muted mono number whose tooltip says what it counts.
59
59
 
60
60
  <Canvas of={NavItemStories.LabelTooltip} />
61
61
 
62
+ - More about the row than a sentence (a short list of what is new there) is
63
+ `preview`: it opens the **PreviewCard** while the row itself is pointed at,
64
+ the ⋮ included, and never while a row under it is. Unlike `tooltip`, the
65
+ pointer can move into it. A screen with no hover never shows it either, so
66
+ the row must still make sense without it.
67
+
68
+ <Canvas of={NavItemStories.RowPreview} />
69
+
62
70
  - Something new on the row is `unread`: its words and icon brighten, the
63
71
  label is set in medium, and the **UnreadDot** sits at the right.
64
72
  `urgent` with it draws the warning badge in the dot's place. Say "unread"
@@ -128,6 +128,21 @@ export const LabelTooltip: Story = {
128
128
  args: { icon: placeholder, action: REMOVE, tooltip: 'One sentence saying what this item is about, shown while its label is pointed at.' },
129
129
  }
130
130
 
131
+ /** `preview`: rest the pointer on the row and a card opens beside it, holding content you can move into; the rows under it open nothing. */
132
+ export const RowPreview: Story = {
133
+ args: {
134
+ icon: placeholder,
135
+ unread: true,
136
+ preview: (
137
+ <div className="flex flex-col gap-1 p-2 text-caption text-text-secondary">
138
+ <span>Line one of what the card holds.</span>
139
+ <span>Line two of what the card holds.</span>
140
+ </div>
141
+ ),
142
+ children: <NavItem href="#two" label="Item two" icon={placeholder} />,
143
+ },
144
+ }
145
+
131
146
  /** A hint and a button: point at it and the chip shows, then the button — a row whose state is a word (here, archived) and which can be taken off the list. */
132
147
  export const WithActionAndHint: Story = {
133
148
  args: { label: 'An item whose label runs much longer than the column has room for', icon: placeholder, action: REMOVE, hint: <Chip type="neutral" label="Archived" /> },
@@ -15,6 +15,43 @@ afterEach(cleanup)
15
15
 
16
16
  const arrow = (name: RegExp) => screen.getByRole('button', { name })
17
17
 
18
+ /*
19
+ Real timers, as PreviewCard's own test: Base UI's hover card never opens under Vitest's fake timers in jsdom. The
20
+ waits are findBy/waitFor polling the screen, not sleeps.
21
+ */
22
+ describe('NavItem with a preview', () => {
23
+ it('opens the card while the row is pointed at, and closes it when the pointer moves to a row under it', async () => {
24
+ const user = userEvent.setup()
25
+ render(
26
+ <NavItem href="#one" label="Item one" unread preview={<span>What is new</span>} menu={<span />}>
27
+ <NavItem href="#two" label="Item two" />
28
+ </NavItem>,
29
+ )
30
+ await user.hover(screen.getByText('Item one'))
31
+ expect(await screen.findByText('What is new')).toBeTruthy()
32
+ await user.unhover(screen.getByText('Item one'))
33
+ await user.hover(screen.getByText('Item two'))
34
+ await waitFor(() => expect(screen.queryByText('What is new')).toBeNull())
35
+ })
36
+
37
+ it('a row with a preview opens the card alone: the label’s tooltip does not stand up beside it', async () => {
38
+ const user = userEvent.setup()
39
+ render(<NavItem href="#one" label="Item one" tooltip="About item one" preview={<span>What is new</span>} />)
40
+ await user.hover(screen.getByText('Item one'))
41
+ // The tooltip's 300ms is shorter than the card's 350ms: had it been drawn, it would be up by now.
42
+ expect(await screen.findByText('What is new')).toBeTruthy()
43
+ expect(screen.queryByText('About item one')).toBeNull()
44
+ })
45
+
46
+ it('a plain row with a preview opens it too', async () => {
47
+ const user = userEvent.setup()
48
+ render(<NavItem href="#one" label="Item one" preview={<span>What is new</span>} />)
49
+ expect(screen.queryByText('What is new')).toBeNull()
50
+ await user.hover(screen.getByText('Item one'))
51
+ expect(await screen.findByText('What is new')).toBeTruthy()
52
+ })
53
+ })
54
+
18
55
  describe('NavItem with rows under it', () => {
19
56
  const tree = (props: Partial<Parameters<typeof NavItem>[0]> = {}) => (
20
57
  <NavItem href="#one" label="Item one" {...props}>
package/src/NavItem.tsx CHANGED
@@ -8,6 +8,7 @@ import { useOpenFor } from './CollapsibleSection'
8
8
  import { COLLAPSIBLE_PANEL_CLASSES, COUNT_TEXT_CLASSES, SIDEBAR_ROW_CLASSES, SIDEBAR_ROW_TEXT_CLASSES } from './looks'
9
9
  import { IconButton } from './IconButton'
10
10
  import { Menu } from './Menu'
11
+ import { PreviewCard } from './PreviewCard'
11
12
  import type { SectionAction } from './SectionHeader'
12
13
  import { UnreadDot } from './UnreadDot'
13
14
  import { WithTooltip } from './Tooltip'
@@ -80,6 +81,13 @@ export interface NavItemProps extends Omit<ComponentPropsWithoutRef<'a'>, 'href'
80
81
  unread?: boolean
81
82
  /** With `unread`: the warning badge in the dot's place. */
82
83
  urgent?: boolean
84
+ /**
85
+ * More about the row, in the package's `PreviewCard` while the row itself is pointed at — never the rows under it —
86
+ * such as a short list of what is new there. Unlike `tooltip`, it holds content the pointer can move into. The card
87
+ * opens on the whole row, the ⋮ included, so a dot the ⋮ steps aside for is not lost as the pointer arrives. With a
88
+ * preview the label draws no `tooltip`: one surface per hover. Absent, no card.
89
+ */
90
+ preview?: ReactNode
83
91
  /** Rows under this one, folding under it: `NavItem`s. While the row is pointed at or focused, its icon becomes the arrow. */
84
92
  children?: ReactNode
85
93
  /** With `children`: open unless told otherwise. */
@@ -117,6 +125,7 @@ export function NavItem({
117
125
  tooltip,
118
126
  unread = false,
119
127
  urgent = false,
128
+ preview,
120
129
  children,
121
130
  defaultOpen = true,
122
131
  open: openProp,
@@ -184,9 +193,10 @@ export function NavItem({
184
193
  {icon}
185
194
  </span>
186
195
  )}
187
- {tooltip?.trim() ? (
196
+ {tooltip?.trim() && preview == null ? (
188
197
  // On the label alone, not the row: the ⋮ and the action keep their
189
- // own tooltips, and the two never stand up at once.
198
+ // own tooltips, and the two never stand up at once. A row with a
199
+ // preview card says more there, so the label has no tooltip beside it.
190
200
  <WithTooltip label={tooltip} inline wrapperClassName="flex min-w-0 flex-1">
191
201
  <span className={cn('flex-1 truncate', unread && 'font-medium')}>{label}</span>
192
202
  </WithTooltip>
@@ -236,7 +246,14 @@ export function NavItem({
236
246
  ) : null}
237
247
  </a>
238
248
  )
239
- if (!besides && hint == null) return row
249
+ // The card's lines are rows with their own padding, so the card keeps only a 4px edge (the content's rhythm is the caller's).
250
+ const card = (trigger: ReactNode) =>
251
+ preview == null ? trigger : (
252
+ <PreviewCard content={preview} contentClassName="gap-0.5 p-1" wrapperClassName="block w-full shrink-0">
253
+ {trigger}
254
+ </PreviewCard>
255
+ )
256
+ if (!besides && hint == null) return card(row)
240
257
  const name = menuLabel ?? `More options for ${label}`
241
258
  const line = (
242
259
  <div className="group/nav relative shrink-0">
@@ -287,10 +304,10 @@ export function NavItem({
287
304
  )}
288
305
  </div>
289
306
  )
290
- if (!hasRows) return line
307
+ if (!hasRows) return card(line)
291
308
  return (
292
309
  <Collapsible.Root open={open} onOpenChange={setOpen} className="flex shrink-0 flex-col">
293
- {line}
310
+ {card(line)}
294
311
  {/* CollapsibleSection's slide, the same way: Base UI measures the panel
295
312
  and the height transitions, none under prefers-reduced-motion. */}
296
313
  <Collapsible.Panel
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
+ }
@@ -66,7 +66,7 @@ fork freely, owe nothing back, mention it on the package's ticket.
66
66
  |---|---|
67
67
  | A list of verbs from a trigger | **Menu** — Escape, outside-click and the arrow keys come with it |
68
68
  | A panel of *content* from a trigger — a field, a toolbar, a small form | **Popover** — the menu's surface without a menu's keyboard |
69
- | More of a thing on hover | **PreviewCard** — unlike a tooltip, you can point at it |
69
+ | More of a thing on hover | **PreviewCard** — unlike a tooltip, you can point at it; on a sidebar row, **NavItem** `preview` opens it |
70
70
  | A hint on hover or on keyboard focus | **Tooltip** / **WithTooltip** — one `TooltipProvider` at the app root shares the delay |
71
71
  | A strip of controls that act on one thing | **Toolbar** — one Tab stop for the row, arrow keys along it |
72
72
  | Reactions to choose from | **ReactionPicker** — the row; **Reaction** is the pill it produces |