@estiva-app/ui 0.110.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.110.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,9 +4,9 @@
4
4
  "kind": "package",
5
5
  "repo": "estiva-ui",
6
6
  "package": "@estiva-app/ui",
7
- "packageVersion": "0.110.0",
8
- "exports": 251,
9
- "typeExports": 260,
7
+ "packageVersion": "0.112.0",
8
+ "exports": 253,
9
+ "typeExports": 263,
10
10
  "files": null
11
11
  },
12
12
  "storybook": {
@@ -3380,6 +3380,40 @@
3380
3380
  "app": null,
3381
3381
  "looks": []
3382
3382
  },
3383
+ {
3384
+ "name": "CornerMenu",
3385
+ "repo": "estiva-ui",
3386
+ "kind": "component",
3387
+ "importPath": "@estiva-app/ui",
3388
+ "sourceFile": "src/CornerMenu.tsx",
3389
+ "purpose": "The \"…\" over the top-right corner of a row or a card in a list the person arranges: Show as Row or Card, and Remove.",
3390
+ "purposeFrom": "page",
3391
+ "props": [
3392
+ {
3393
+ "name": "children",
3394
+ "takes": "anything",
3395
+ "required": true,
3396
+ "note": "The row or the card the \"…\" floats over."
3397
+ },
3398
+ {
3399
+ "name": "menu",
3400
+ "takes": "CornerMenuOptions",
3401
+ "required": false,
3402
+ "note": "The \"…\" and its menu. Without it only `children` are drawn: where the person cannot arrange the list."
3403
+ }
3404
+ ],
3405
+ "variants": [],
3406
+ "ownsBehaviours": [],
3407
+ "status": "stable",
3408
+ "migrationStage": null,
3409
+ "docsId": "links-references-cornermenu--docs",
3410
+ "storyId": "links-references-cornermenu--card-and-row",
3411
+ "docPage": "src/CornerMenu.mdx",
3412
+ "app": null,
3413
+ "looks": [
3414
+ "-right-2 -top-2 rounded-md border border-border-strong bg-bg-elevated opacity-0 shadow-sm transition-opacity focus-within:opacity-100 [@media(hover:none)]:opacity-100"
3415
+ ]
3416
+ },
3383
3417
  {
3384
3418
  "name": "deleteBlock",
3385
3419
  "repo": "estiva-ui",
@@ -12492,6 +12526,25 @@
12492
12526
  "app": null,
12493
12527
  "looks": []
12494
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
+ },
12495
12548
  {
12496
12549
  "name": "useSidebarFold",
12497
12550
  "repo": "estiva-ui",
@@ -0,0 +1,60 @@
1
+ import { Meta, Canvas, Controls } from '@storybook/addon-docs/blocks'
2
+ import * as CornerMenuStories from './CornerMenu.stories'
3
+
4
+ <Meta of={CornerMenuStories} />
5
+
6
+ # CornerMenu
7
+
8
+ The "…" over the top-right corner of a row or a card in a list the person arranges: Show as Row or Card, and Remove.
9
+
10
+ <Canvas of={CornerMenuStories.CardAndRow} />
11
+
12
+ ## When
13
+
14
+ - **with `menu`** — an item in a list the person may arrange: it shows as one line or as its card, and they can take it off.
15
+ - **no `menu`** — the same list to someone who may not arrange it: the child alone, no "…".
16
+
17
+ The "…" floats over the item's top-right corner, where `AttachedCard`'s ✕ sits, and takes no room of its own. It shows when the pointer is over the item, while it has focus or its menu is open, and always on a screen that cannot hover, so a tap reaches it.
18
+
19
+ <Canvas of={CornerMenuStories.Open} />
20
+
21
+ ## When not
22
+
23
+ - A card whose only action is taking it off → **AttachedCard** `onRemove`, the round ✕.
24
+ - A link alone on its line in a document being written → **ReferenceMenu**, which offers the same Show as in the editor.
25
+ - More than these actions on a row of a list in the sidebar → **NavItem** `menu`.
26
+
27
+ ## How
28
+
29
+ ```tsx
30
+ import { AttachedCard, CornerMenu, LinkRow } from '@estiva-app/ui'
31
+
32
+ <CornerMenu menu={canArrange ? { name: title, look, onLook: setLook, onRemove: remove } : undefined}>
33
+ {look === 'card' ? <AttachedCard link={link} /> : <LinkRow link={link} />}
34
+ </CornerMenu>
35
+ ```
36
+
37
+ - `name` is required: the "…" is announced as "More options for {name}".
38
+ - `onLook` is called only with the look not in use; choosing the one in use closes the menu and asks for nothing.
39
+ - Pass the card **no** `onRemove`: Remove is in the menu, and a card with both would draw the ✕ beside the "…".
40
+ - It is at most 480px wide, as `AttachedCard`, so the "…" sits on the card's corner.
41
+
42
+ ## What it owns
43
+
44
+ | It does | So you never write |
45
+ |---|---|
46
+ | Floats the "…" over the item's top-right corner, taking no room | a positioned wrapper and a button |
47
+ | Reveals it on hover, focus and while its menu is open, and always shows it on touch | a hover or touch check |
48
+ | The menu: Show as Row or Card, the look in use ticked, and checked for a screen reader, then Remove | the words and the tick |
49
+
50
+ ## Keys
51
+
52
+ | Key | Does |
53
+ |---|---|
54
+ | Tab | Reaches the "…", and shows it |
55
+ | Enter | Opens the menu |
56
+ | Escape | Closes the menu |
57
+
58
+ ## Props
59
+
60
+ <Controls of={CornerMenuStories.NoMenu} />
@@ -0,0 +1,62 @@
1
+ import type { Meta, StoryObj } from '@storybook/react-vite'
2
+ import { useState } from 'react'
3
+ import { userEvent, within } from 'storybook/test'
4
+ import { AttachedCard } from './AttachedCard'
5
+ import { Button } from './Button'
6
+ import { CornerMenu, type CornerMenuLook } from './CornerMenu'
7
+ import { LinkRow } from './LinkRow'
8
+ import { ITEM, ITEM_NO_SUMMARY, ready } from './linked.examples'
9
+
10
+ const meta = {
11
+ title: 'Links & references/CornerMenu',
12
+ component: CornerMenu,
13
+ parameters: { layout: 'padded' },
14
+ args: { children: null },
15
+ } satisfies Meta<typeof CornerMenu>
16
+
17
+ export default meta
18
+ type Story = StoryObj<typeof meta>
19
+
20
+ /** One item, a row or a card as its menu says, and gone once removed. */
21
+ function Item({ start, linked }: { start: CornerMenuLook; linked: typeof ITEM }) {
22
+ const [look, setLook] = useState(start)
23
+ const [removed, setRemoved] = useState(false)
24
+ if (removed) return <Button onClick={() => setRemoved(false)}>Put it back</Button>
25
+ const link = ready(linked)
26
+ return (
27
+ <CornerMenu menu={{ name: linked.title, look, onLook: setLook, onRemove: () => setRemoved(true) }}>
28
+ {look === 'card' ? <AttachedCard link={link} /> : <LinkRow link={link} />}
29
+ </CornerMenu>
30
+ )
31
+ }
32
+
33
+ /** A card and a row in one list: point at either and its "…" shows over its top-right corner, taking no room. Show as Row or Card changes it; Remove takes it off. */
34
+ export const CardAndRow: Story = {
35
+ render: () => (
36
+ <div className="flex flex-col gap-3">
37
+ <Item start="card" linked={ITEM} />
38
+ <Item start="row" linked={ITEM_NO_SUMMARY} />
39
+ </div>
40
+ ),
41
+ }
42
+
43
+ /** The menu open on a card: Show as, the look in use selected, then Remove. */
44
+ export const Open: Story = {
45
+ render: () => (
46
+ <div className="h-96">
47
+ <Item start="card" linked={ITEM} />
48
+ </div>
49
+ ),
50
+ play: async ({ canvasElement }) => {
51
+ await userEvent.click(within(canvasElement).getByRole('button', { name: `More options for ${ITEM.title}` }))
52
+ },
53
+ }
54
+
55
+ /** Where the person cannot arrange the list: no `menu`, no "…". */
56
+ export const NoMenu: Story = {
57
+ render: () => (
58
+ <CornerMenu>
59
+ <AttachedCard link={ready(ITEM)} />
60
+ </CornerMenu>
61
+ ),
62
+ }
@@ -0,0 +1,93 @@
1
+ // @vitest-environment jsdom
2
+ /** What the CornerMenu page claims, pinned: the "…" is named for the item, is drawn only with a menu, and its menu shows and changes the look and removes. */
3
+ import { cleanup, render, screen, waitFor } from '@testing-library/react'
4
+ import userEvent from '@testing-library/user-event'
5
+ import { afterEach, describe, expect, it, vi } from 'vitest'
6
+ import { CornerMenu, type CornerMenuOptions } from './CornerMenu'
7
+
8
+ afterEach(cleanup)
9
+
10
+ function options(over: Partial<CornerMenuOptions> = {}): CornerMenuOptions {
11
+ return { name: 'Item one', look: 'row', onLook: vi.fn(), onRemove: vi.fn(), ...over }
12
+ }
13
+
14
+ async function openMenu(menu: CornerMenuOptions) {
15
+ const user = userEvent.setup()
16
+ render(
17
+ <CornerMenu menu={menu}>
18
+ <span>Item one</span>
19
+ </CornerMenu>,
20
+ )
21
+ await user.click(screen.getByRole('button', { name: 'More options for Item one' }))
22
+ await screen.findByRole('menu')
23
+ return user
24
+ }
25
+
26
+ describe('CornerMenu', () => {
27
+ it('draws its child and a "…" named for the item', () => {
28
+ render(
29
+ <CornerMenu menu={options()}>
30
+ <span>Item one</span>
31
+ </CornerMenu>,
32
+ )
33
+ expect(screen.getByText('Item one')).toBeTruthy()
34
+ expect(screen.getByRole('button', { name: 'More options for Item one' })).toBeTruthy()
35
+ })
36
+
37
+ it('without a menu, where the person cannot arrange the list, draws its child and no "…"', () => {
38
+ render(
39
+ <CornerMenu>
40
+ <span>Item one</span>
41
+ </CornerMenu>,
42
+ )
43
+ expect(screen.getByText('Item one')).toBeTruthy()
44
+ expect(screen.queryAllByRole('button')).toHaveLength(0)
45
+ })
46
+
47
+ it('opens Show as with Row and Card, the look in use checked, then Remove', async () => {
48
+ await openMenu(options({ look: 'card' }))
49
+ expect(screen.getByRole('group', { name: 'Show as' })).toBeTruthy()
50
+ expect(screen.getByRole('menuitemradio', { name: 'Card', checked: true })).toBeTruthy()
51
+ expect(screen.getByRole('menuitemradio', { name: 'Row', checked: false })).toBeTruthy()
52
+ expect(screen.getByRole('menuitem', { name: 'Remove' })).toBeTruthy()
53
+ })
54
+
55
+ it('choosing Card on a row asks for the card, and closes the menu', async () => {
56
+ const menu = options({ look: 'row' })
57
+ const user = await openMenu(menu)
58
+ await user.click(screen.getByRole('menuitemradio', { name: 'Card' }))
59
+ expect(menu.onLook).toHaveBeenCalledWith('card')
60
+ expect(menu.onLook).toHaveBeenCalledTimes(1)
61
+ await waitFor(() => expect(screen.queryByRole('menu')).toBeNull())
62
+ })
63
+
64
+ it('choosing the look already in use asks for nothing', async () => {
65
+ const menu = options({ look: 'row' })
66
+ const user = await openMenu(menu)
67
+ await user.click(screen.getByRole('menuitemradio', { name: 'Row' }))
68
+ expect(menu.onLook).not.toHaveBeenCalled()
69
+ })
70
+
71
+ it('Remove removes the item', async () => {
72
+ const menu = options()
73
+ const user = await openMenu(menu)
74
+ await user.click(screen.getByRole('menuitem', { name: 'Remove' }))
75
+ expect(menu.onRemove).toHaveBeenCalledTimes(1)
76
+ expect(menu.onLook).not.toHaveBeenCalled()
77
+ })
78
+
79
+ it('opens from the keyboard: Tab reaches the "…", Enter opens it, Escape closes it', async () => {
80
+ const user = userEvent.setup()
81
+ render(
82
+ <CornerMenu menu={options()}>
83
+ <span>Item one</span>
84
+ </CornerMenu>,
85
+ )
86
+ await user.tab()
87
+ expect(document.activeElement).toBe(screen.getByRole('button', { name: 'More options for Item one' }))
88
+ await user.keyboard('{Enter}')
89
+ expect(await screen.findByRole('menuitem', { name: 'Remove' })).toBeTruthy()
90
+ await user.keyboard('{Escape}')
91
+ await waitFor(() => expect(screen.queryByRole('menu')).toBeNull())
92
+ })
93
+ })
@@ -0,0 +1,81 @@
1
+ /**
2
+ * The "…" that floats over a row's or a card's top-right corner in a list the
3
+ * person arranges, and the menu it opens: Show as Row or Card, the one in use
4
+ * ticked, then Remove (Miky, 6 Nov, the topics level-up prototype).
5
+ *
6
+ * It sits where `AttachedCard`'s ✕ sits and takes no room of its own: shown
7
+ * while the pointer is over the item, while the "…" has focus or its menu is
8
+ * open, and always on a screen that cannot hover, so a tap reaches it. "Show
9
+ * as", "Row" and "Card" are the words `ReferenceMenu` uses for the same choice.
10
+ *
11
+ * Without `menu` it draws only its child, in the same box: where the person
12
+ * cannot arrange the list, the app passes nothing and no "…" is drawn.
13
+ */
14
+ import type { ReactNode } from 'react'
15
+ import { IconCheck, IconDotsVertical } from '@tabler/icons-react'
16
+ import { IconButton } from './IconButton'
17
+ import { Menu, MenuItem, MenuSection, MenuSeparator } from './Menu'
18
+
19
+ /** How an item in a list shows: one line, or its card. */
20
+ export type CornerMenuLook = 'row' | 'card'
21
+
22
+ const LOOKS: { look: CornerMenuLook; label: string }[] = [
23
+ { look: 'row', label: 'Row' },
24
+ { look: 'card', label: 'Card' },
25
+ ]
26
+
27
+ export interface CornerMenuOptions {
28
+ /** The item's name: the "…" is "More options for {name}". */
29
+ name: string
30
+ /** How it shows now: ticked under Show as. */
31
+ look: CornerMenuLook
32
+ /** Show as Row or Card was chosen: the other look than `look`. Choosing the one in use calls nothing. */
33
+ onLook: (look: CornerMenuLook) => void
34
+ /** Remove was chosen. */
35
+ onRemove: () => void
36
+ }
37
+
38
+ export interface CornerMenuProps {
39
+ /** The row or the card the "…" floats over. */
40
+ children: ReactNode
41
+ /** The "…" and its menu. Without it only `children` are drawn: where the person cannot arrange the list. */
42
+ menu?: CornerMenuOptions
43
+ }
44
+
45
+ export function CornerMenu({ children, menu }: CornerMenuProps) {
46
+ return (
47
+ // At most 480px, as `AttachedCard`, so the "…" sits on the card's corner and not at the column's edge.
48
+ <div className="group/corner relative max-w-[480px]">
49
+ {children}
50
+ {menu && (
51
+ <div className="absolute -right-2 -top-2 z-10 rounded-md border border-border-strong bg-bg-elevated opacity-0 shadow-sm transition-opacity group-hover/corner:opacity-100 focus-within:opacity-100 has-[[aria-expanded=true]]:opacity-100 [@media(hover:none)]:opacity-100">
52
+ <Menu
53
+ align="right"
54
+ trigger={
55
+ <IconButton tooltip="More options" aria-label={`More options for ${menu.name}`}>
56
+ <IconDotsVertical size={16} stroke={1.5} />
57
+ </IconButton>
58
+ }
59
+ >
60
+ <MenuSection label="Show as">
61
+ {LOOKS.map(({ look, label }) => (
62
+ <MenuItem
63
+ key={look}
64
+ role="menuitemradio"
65
+ aria-checked={menu.look === look}
66
+ label={label}
67
+ trailing={menu.look === look ? <IconCheck size={16} aria-hidden /> : undefined}
68
+ onClick={() => {
69
+ if (menu.look !== look) menu.onLook(look)
70
+ }}
71
+ />
72
+ ))}
73
+ </MenuSection>
74
+ <MenuSeparator />
75
+ <MenuItem label="Remove" onClick={menu.onRemove} />
76
+ </Menu>
77
+ </div>
78
+ )}
79
+ </div>
80
+ )
81
+ }
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
@@ -129,6 +129,7 @@ export { LinkRow, LinkUnavailable, type LinkRowProps, type LinkUnavailableProps
129
129
  export { LinkCard, LinkCardLoading, type LinkCardProps, type LinkCardLoadingProps } from './LinkCard'
130
130
  export { LinkPreview, LinkPreviewOpen, useCanHover, type LinkPreviewProps } from './LinkPreview'
131
131
  export { AttachedCard, type AttachedCardMemory, type AttachedCardProps } from './AttachedCard'
132
+ export { CornerMenu, type CornerMenuLook, type CornerMenuOptions, type CornerMenuProps } from './CornerMenu'
132
133
  export { PartCard, type PartCardProps, type PartCardState } from './PartCard'
133
134
  export { Person, type PersonProps } from './Person'
134
135
  export { Rail, type RailProps } from './Rail'
@@ -175,4 +176,4 @@ export { SectionLabel } from './SectionLabel'
175
176
  export { Tabs, type TabDef, type TabsProps } from './Tabs'
176
177
  export { Toast, ToastProvider, useToast, type ToastOptions, type ToastProps, type ToastType } from './Toast'
177
178
  export { cn } from './cn'
178
- 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 251 names over 128 files: 166 components, 78 helpers and 7 hooks (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: 166, helper: 78, hook: 7 })
58
- expect(new Set(registry.entries.map((one) => one.sourceFile)).size).toBe(128)
57
+ expect(kinds).toEqual({ component: 167, helper: 78, hook: 8 })
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
- expect(registry.entries.filter((one) => one.purposeFrom === 'page').length).toBe(115)
64
- expect(registry.entries.filter((one) => one.purposeFrom === 'comment').length).toBe(136)
63
+ expect(registry.entries.filter((one) => one.purposeFrom === 'page').length).toBe(116)
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
+ })