@siiway/ui-react 0.1.0 → 0.2.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.
Files changed (108) hide show
  1. package/dist/components/AppShell.d.ts +29 -0
  2. package/dist/components/AppShell.d.ts.map +1 -0
  3. package/dist/components/AppShell.js +220 -0
  4. package/dist/components/AppShell.js.map +1 -0
  5. package/dist/components/AuthShell.d.ts +21 -0
  6. package/dist/components/AuthShell.d.ts.map +1 -0
  7. package/dist/components/AuthShell.js +53 -0
  8. package/dist/components/AuthShell.js.map +1 -0
  9. package/dist/components/ButtonLink.d.ts +11 -0
  10. package/dist/components/ButtonLink.d.ts.map +1 -0
  11. package/dist/components/ButtonLink.js +15 -0
  12. package/dist/components/ButtonLink.js.map +1 -0
  13. package/dist/components/CommandPalette.d.ts +23 -11
  14. package/dist/components/CommandPalette.d.ts.map +1 -1
  15. package/dist/components/CommandPalette.js +33 -3
  16. package/dist/components/CommandPalette.js.map +1 -1
  17. package/dist/components/CopyButton.d.ts +25 -6
  18. package/dist/components/CopyButton.d.ts.map +1 -1
  19. package/dist/components/CopyButton.js +11 -8
  20. package/dist/components/CopyButton.js.map +1 -1
  21. package/dist/components/DetailHeader.d.ts +5 -1
  22. package/dist/components/DetailHeader.d.ts.map +1 -1
  23. package/dist/components/DetailHeader.js +6 -5
  24. package/dist/components/DetailHeader.js.map +1 -1
  25. package/dist/components/FormPage.d.ts +1 -1
  26. package/dist/components/FormPage.d.ts.map +1 -1
  27. package/dist/components/LoadingPage.d.ts +6 -0
  28. package/dist/components/LoadingPage.d.ts.map +1 -0
  29. package/dist/components/LoadingPage.js +25 -0
  30. package/dist/components/LoadingPage.js.map +1 -0
  31. package/dist/components/MenuPanel.d.ts +34 -0
  32. package/dist/components/MenuPanel.d.ts.map +1 -0
  33. package/dist/components/MenuPanel.js +98 -0
  34. package/dist/components/MenuPanel.js.map +1 -0
  35. package/dist/components/PageHeader.d.ts +3 -3
  36. package/dist/components/PageHeader.d.ts.map +1 -1
  37. package/dist/components/PageHeader.js +5 -14
  38. package/dist/components/PageHeader.js.map +1 -1
  39. package/dist/components/PasswordInput.d.ts.map +1 -1
  40. package/dist/components/PasswordInput.js +15 -2
  41. package/dist/components/PasswordInput.js.map +1 -1
  42. package/dist/components/SideNav.d.ts +18 -5
  43. package/dist/components/SideNav.d.ts.map +1 -1
  44. package/dist/components/SideNav.js +30 -4
  45. package/dist/components/SideNav.js.map +1 -1
  46. package/dist/components/StatusPage.d.ts +17 -5
  47. package/dist/components/StatusPage.d.ts.map +1 -1
  48. package/dist/components/StatusPage.js +10 -6
  49. package/dist/components/StatusPage.js.map +1 -1
  50. package/dist/components/ThemeMenu.d.ts +6 -4
  51. package/dist/components/ThemeMenu.d.ts.map +1 -1
  52. package/dist/components/ThemeMenu.js +3 -27
  53. package/dist/components/ThemeMenu.js.map +1 -1
  54. package/dist/components/ThemeSwitch.d.ts +7 -4
  55. package/dist/components/ThemeSwitch.d.ts.map +1 -1
  56. package/dist/components/ThemeSwitch.js +12 -4
  57. package/dist/components/ThemeSwitch.js.map +1 -1
  58. package/dist/components/TopBar.d.ts +6 -2
  59. package/dist/components/TopBar.d.ts.map +1 -1
  60. package/dist/components/TopBar.js +10 -9
  61. package/dist/components/TopBar.js.map +1 -1
  62. package/dist/hooks/useCopy.d.ts +5 -2
  63. package/dist/hooks/useCopy.d.ts.map +1 -1
  64. package/dist/hooks/useCopy.js +29 -4
  65. package/dist/hooks/useCopy.js.map +1 -1
  66. package/dist/hooks/useThemeMode.d.ts +13 -1
  67. package/dist/hooks/useThemeMode.d.ts.map +1 -1
  68. package/dist/hooks/useThemeMode.js +59 -10
  69. package/dist/hooks/useThemeMode.js.map +1 -1
  70. package/dist/index.d.ts +8 -3
  71. package/dist/index.d.ts.map +1 -1
  72. package/dist/index.js +7 -2
  73. package/dist/index.js.map +1 -1
  74. package/dist/provider/UiProvider.d.ts +30 -7
  75. package/dist/provider/UiProvider.d.ts.map +1 -1
  76. package/dist/provider/UiProvider.js +116 -14
  77. package/dist/provider/UiProvider.js.map +1 -1
  78. package/dist/provider/canvas.d.ts +5 -0
  79. package/dist/provider/canvas.d.ts.map +1 -1
  80. package/dist/provider/canvas.js +21 -6
  81. package/dist/provider/canvas.js.map +1 -1
  82. package/dist/provider/context.d.ts +27 -3
  83. package/dist/provider/context.d.ts.map +1 -1
  84. package/dist/provider/context.js +48 -3
  85. package/dist/provider/context.js.map +1 -1
  86. package/package.json +2 -2
  87. package/src/components/AppShell.tsx +337 -0
  88. package/src/components/AuthShell.tsx +104 -0
  89. package/src/components/ButtonLink.tsx +40 -0
  90. package/src/components/CommandPalette.tsx +56 -14
  91. package/src/components/CopyButton.tsx +61 -33
  92. package/src/components/DetailHeader.tsx +12 -6
  93. package/src/components/FormPage.tsx +1 -1
  94. package/src/components/LoadingPage.tsx +41 -0
  95. package/src/components/MenuPanel.tsx +163 -0
  96. package/src/components/PageHeader.tsx +9 -20
  97. package/src/components/PasswordInput.tsx +16 -1
  98. package/src/components/SideNav.tsx +86 -16
  99. package/src/components/StatusPage.tsx +41 -17
  100. package/src/components/ThemeMenu.tsx +12 -44
  101. package/src/components/ThemeSwitch.tsx +20 -10
  102. package/src/components/TopBar.tsx +31 -18
  103. package/src/hooks/useCopy.ts +27 -8
  104. package/src/hooks/useThemeMode.ts +78 -8
  105. package/src/index.ts +17 -1
  106. package/src/provider/UiProvider.tsx +182 -21
  107. package/src/provider/canvas.ts +20 -6
  108. package/src/provider/context.tsx +65 -5
@@ -0,0 +1,337 @@
1
+ // An app's frame: a sidebar beside the page, which below a width becomes a
2
+ // drawer that slides in over it. Prism's layout, which Vellum and Glint built
3
+ // with Fluent's OverlayDrawer and a width check in JavaScript. This one is CSS,
4
+ // so it renders on the server; only focus and closing need the browser.
5
+ //
6
+ // While a drawer, the sidebar is inert until opened, and again as soon as it
7
+ // starts to close. Open, it is a modal dialog: focus moves into it and Tab
8
+ // wraps around in it, the page behind is
9
+ // inert, and Escape, the backdrop, a link in it, AppShellClose or the window
10
+ // growing past the width close it, with focus back where it was, or on the
11
+ // page when that has gone from view.
12
+
13
+ import { Button, makeStyles, mergeClasses, tokens } from "@fluentui/react-components";
14
+ import { DismissRegular } from "@fluentui/react-icons";
15
+ import {
16
+ createContext,
17
+ useCallback,
18
+ useContext,
19
+ useEffect,
20
+ useRef,
21
+ useSyncExternalStore,
22
+ type KeyboardEvent,
23
+ type MouseEvent,
24
+ type ReactNode,
25
+ } from "react";
26
+ import { useCanvasClass } from "../provider/canvas.js";
27
+ import { useUiStrings } from "../provider/context.js";
28
+
29
+ const SLIDE = "transform 0.2s ease-out";
30
+
31
+ // Below each width the sidebar is a drawer. Griffel needs its media queries
32
+ // written out, so each width has its classes.
33
+ const useStyles = makeStyles({
34
+ shell: {
35
+ display: "flex",
36
+ height: "100vh",
37
+ overflow: "hidden",
38
+ // A phone's collapsing address bar: the visible height, where supported.
39
+ "@supports (height: 100dvh)": { height: "100dvh" },
40
+ },
41
+ sidebar: {
42
+ display: "flex",
43
+ flexDirection: "column",
44
+ flexShrink: 0,
45
+ boxSizing: "border-box",
46
+ borderRight: `1px solid ${tokens.colorNeutralStroke2}`,
47
+ ":focus-visible": { outline: "none" },
48
+ },
49
+ drawer768: {
50
+ "@media (max-width: 768px)": {
51
+ position: "fixed",
52
+ top: 0,
53
+ bottom: 0,
54
+ left: 0,
55
+ zIndex: 200,
56
+ transform: "translateX(-100%)",
57
+ visibility: "hidden",
58
+ // Hidden once it has slid out, not before.
59
+ transition: `${SLIDE}, visibility 0s linear 0.2s`,
60
+ },
61
+ },
62
+ drawer960: {
63
+ "@media (max-width: 960px)": {
64
+ position: "fixed",
65
+ top: 0,
66
+ bottom: 0,
67
+ left: 0,
68
+ zIndex: 200,
69
+ transform: "translateX(-100%)",
70
+ visibility: "hidden",
71
+ transition: `${SLIDE}, visibility 0s linear 0.2s`,
72
+ },
73
+ },
74
+ open768: {
75
+ "@media (max-width: 768px)": { transform: "none", visibility: "visible", transition: SLIDE },
76
+ },
77
+ open960: {
78
+ "@media (max-width: 960px)": { transform: "none", visibility: "visible", transition: SLIDE },
79
+ },
80
+ still: {
81
+ "@media (prefers-reduced-motion: reduce)": { transition: "none" },
82
+ },
83
+ backdrop: {
84
+ position: "fixed",
85
+ inset: 0,
86
+ zIndex: 199,
87
+ background: "rgba(0, 0, 0, 0.5)",
88
+ },
89
+ above768: { "@media (min-width: 769px)": { display: "none" } },
90
+ above960: { "@media (min-width: 961px)": { display: "none" } },
91
+ column: {
92
+ flex: 1,
93
+ display: "flex",
94
+ flexDirection: "column",
95
+ minWidth: 0,
96
+ },
97
+ header: { flexShrink: 0 },
98
+ main: {
99
+ flex: 1,
100
+ overflowY: "auto",
101
+ display: "flex",
102
+ flexDirection: "column",
103
+ // Focused only when the drawer closes and its opener has gone.
104
+ ":focus-visible": { outline: "none" },
105
+ },
106
+ });
107
+
108
+ // Whether the window is below the width, kept up to date; on the server, and
109
+ // while hydrating, it isn't (the CSS draws the drawer either way).
110
+ function useBelow(query: string): boolean {
111
+ const subscribe = useCallback(
112
+ (onChange: () => void) => {
113
+ const media = window.matchMedia(query);
114
+ media.addEventListener("change", onChange);
115
+ return () => media.removeEventListener("change", onChange);
116
+ },
117
+ [query],
118
+ );
119
+ return useSyncExternalStore(
120
+ subscribe,
121
+ () => window.matchMedia(query).matches,
122
+ () => false,
123
+ );
124
+ }
125
+
126
+ // Something focus can go back to: still in the page and drawn.
127
+ function canFocus(element: HTMLElement | null): element is HTMLElement {
128
+ return !!element && element.isConnected && element.getClientRects().length > 0;
129
+ }
130
+
131
+ const TABBABLE =
132
+ 'a[href], button:not([disabled]), input:not([disabled]):not([type="hidden"]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';
133
+
134
+ // What Tab reaches in the drawer, in order.
135
+ function tabbables(root: HTMLElement): HTMLElement[] {
136
+ return Array.from(root.querySelectorAll<HTMLElement>(TABBABLE)).filter(
137
+ (element) => element.tabIndex >= 0 && canFocus(element),
138
+ );
139
+ }
140
+
141
+ interface ShellState {
142
+ drawerBelow: 768 | 960;
143
+ close: () => void;
144
+ }
145
+
146
+ const ShellContext = createContext<ShellState | null>(null);
147
+
148
+ export interface AppShellProps {
149
+ /** The sidebar, top to bottom: the brand, search, the navigation, an account menu. */
150
+ sidebar: ReactNode;
151
+ /** The page, in the scrolling area beside the sidebar: the `main` landmark. */
152
+ children: ReactNode;
153
+ /** Above the page, such as a `TopBar` whose menu button opens the drawer. */
154
+ header?: ReactNode;
155
+ /** Show `header` only where the sidebar is a drawer, as the bar that opens it. */
156
+ headerOnlyWithDrawer?: boolean;
157
+ /** Whether the drawer is open. */
158
+ open: boolean;
159
+ /** Called to open or close the drawer: with false on Escape, the backdrop,
160
+ * a link in the drawer, `AppShellClose`, or the window growing past
161
+ * `drawerBelow`. */
162
+ onOpenChange: (open: boolean) => void;
163
+ /** The width from which down the sidebar is a drawer: 960 (the default) or
164
+ * 768. `TopBar`'s `menuBelow` has the same default; change both together. */
165
+ drawerBelow?: 768 | 960;
166
+ /** The sidebar's width in px. Defaults to 240. */
167
+ sidebarWidth?: number;
168
+ }
169
+
170
+ export function AppShell({
171
+ sidebar,
172
+ children,
173
+ header,
174
+ headerOnlyWithDrawer,
175
+ open,
176
+ onOpenChange,
177
+ drawerBelow = 960,
178
+ sidebarWidth = 240,
179
+ }: AppShellProps) {
180
+ const styles = useStyles();
181
+ const strings = useUiStrings();
182
+ const canvas = useCanvasClass();
183
+ const aside = useRef<HTMLElement>(null);
184
+ const column = useRef<HTMLDivElement>(null);
185
+ const main = useRef<HTMLElement>(null);
186
+ const query = `(max-width: ${drawerBelow}px)`;
187
+ const narrow = drawerBelow === 768;
188
+ const isDrawer = useBelow(query);
189
+ const modal = open && isDrawer;
190
+
191
+ // A closed drawer is inert at once, though it takes a moment to slide out.
192
+ // Set here, not as a prop: React 18 and 19 read `inert` differently.
193
+ useEffect(() => {
194
+ const drawer = aside.current;
195
+ if (isDrawer && !open) drawer?.setAttribute("inert", "");
196
+ else drawer?.removeAttribute("inert");
197
+ }, [isDrawer, open]);
198
+
199
+ // Open as a drawer, including an open sidebar the window narrows under:
200
+ // focus in, the page inert, and back out on close.
201
+ useEffect(() => {
202
+ if (!modal) return;
203
+ const before = document.activeElement as HTMLElement | null;
204
+ const drawer = aside.current;
205
+ const page = column.current;
206
+ const fallback = main.current;
207
+ drawer?.focus();
208
+ page?.setAttribute("inert", "");
209
+ return () => {
210
+ page?.removeAttribute("inert");
211
+ const active = document.activeElement;
212
+ if (!drawer?.contains(active) && active !== document.body) return;
213
+ // The opener may have gone from view, such as a header shown only
214
+ // with the drawer, after the window grew.
215
+ if (canFocus(before)) before.focus();
216
+ else fallback?.focus();
217
+ };
218
+ }, [modal]);
219
+
220
+ // A window that grows past the width has no drawer to keep open.
221
+ useEffect(() => {
222
+ if (!open) return;
223
+ const media = window.matchMedia(query);
224
+ const onChange = () => {
225
+ if (!media.matches) onOpenChange(false);
226
+ };
227
+ media.addEventListener("change", onChange);
228
+ return () => media.removeEventListener("change", onChange);
229
+ }, [open, query, onOpenChange]);
230
+
231
+ const onKeyDown = (event: KeyboardEvent) => {
232
+ if (!modal) return;
233
+ if (event.key === "Escape") {
234
+ event.stopPropagation();
235
+ onOpenChange(false);
236
+ return;
237
+ }
238
+ // Tab wraps around in the drawer, so it never reaches the browser's bar.
239
+ if (event.key !== "Tab" || !aside.current) return;
240
+ const stops = tabbables(aside.current);
241
+ const first = stops[0];
242
+ const last = stops[stops.length - 1];
243
+ const active = document.activeElement;
244
+ if (!first || !last) {
245
+ event.preventDefault();
246
+ } else if (event.shiftKey && (active === first || active === aside.current)) {
247
+ event.preventDefault();
248
+ last.focus();
249
+ } else if (!event.shiftKey && active === last) {
250
+ event.preventDefault();
251
+ first.focus();
252
+ }
253
+ };
254
+ // A link followed from the drawer leaves it behind.
255
+ const onClick = (event: MouseEvent) => {
256
+ if (open && (event.target as Element).closest("a[href]")) onOpenChange(false);
257
+ };
258
+
259
+ return (
260
+ <ShellContext.Provider value={{ drawerBelow, close: () => onOpenChange(false) }}>
261
+ <div className={mergeClasses(styles.shell, canvas)}>
262
+ {open && (
263
+ <div
264
+ className={mergeClasses(styles.backdrop, narrow ? styles.above768 : styles.above960)}
265
+ onClick={() => onOpenChange(false)}
266
+ />
267
+ )}
268
+ <aside
269
+ ref={aside}
270
+ tabIndex={-1}
271
+ role={modal ? "dialog" : undefined}
272
+ aria-modal={modal ? true : undefined}
273
+ aria-label={modal ? strings.navigation : undefined}
274
+ className={mergeClasses(
275
+ styles.sidebar,
276
+ canvas,
277
+ narrow ? styles.drawer768 : styles.drawer960,
278
+ open && (narrow ? styles.open768 : styles.open960),
279
+ styles.still,
280
+ )}
281
+ style={{ width: sidebarWidth }}
282
+ onKeyDown={onKeyDown}
283
+ onClick={onClick}
284
+ >
285
+ {sidebar}
286
+ </aside>
287
+ <div ref={column} className={styles.column}>
288
+ {header != null && (
289
+ <div
290
+ className={mergeClasses(
291
+ styles.header,
292
+ headerOnlyWithDrawer && (narrow ? styles.above768 : styles.above960),
293
+ )}
294
+ >
295
+ {header}
296
+ </div>
297
+ )}
298
+ <main ref={main} tabIndex={-1} className={styles.main}>
299
+ {children}
300
+ </main>
301
+ </div>
302
+ </div>
303
+ </ShellContext.Provider>
304
+ );
305
+ }
306
+
307
+ const useCloseStyles = makeStyles({
308
+ close: { flexShrink: 0 },
309
+ above768: { "@media (min-width: 769px)": { display: "none" } },
310
+ above960: { "@media (min-width: 961px)": { display: "none" } },
311
+ });
312
+
313
+ /** A button that closes the drawer, shown only while the sidebar is one. Put
314
+ * it at the end of the sidebar's first row, by the brand. */
315
+ export function AppShellClose({
316
+ label,
317
+ }: {
318
+ /** Defaults to the library's "Close navigation". */ label?: string;
319
+ }) {
320
+ const styles = useCloseStyles();
321
+ const strings = useUiStrings();
322
+ const shell = useContext(ShellContext);
323
+ if (!shell) return null;
324
+ return (
325
+ <Button
326
+ appearance="subtle"
327
+ size="small"
328
+ icon={<DismissRegular />}
329
+ aria-label={label ?? strings.closeNavigation}
330
+ className={mergeClasses(
331
+ styles.close,
332
+ shell.drawerBelow === 768 ? styles.above768 : styles.above960,
333
+ )}
334
+ onClick={shell.close}
335
+ />
336
+ );
337
+ }
@@ -0,0 +1,104 @@
1
+ // A sign-in page's frame: the site at the top left and a narrow column on the
2
+ // canvas for the form, with room for notices above it and legal links at the
3
+ // foot. No card: Prism's sign-in, register, consent and two-factor pages, and
4
+ // Glint's sign-in, laid out alike.
5
+
6
+ import { Text, makeStyles, mergeClasses } from "@fluentui/react-components";
7
+ import type { ReactNode } from "react";
8
+ import { useCanvasClass } from "../provider/canvas.js";
9
+ import { BrandMark } from "./BrandMark.js";
10
+
11
+ const useStyles = makeStyles({
12
+ page: {
13
+ minHeight: "100vh",
14
+ display: "flex",
15
+ flexDirection: "column",
16
+ boxSizing: "border-box",
17
+ },
18
+ header: {
19
+ display: "flex",
20
+ alignItems: "center",
21
+ gap: "10px",
22
+ minHeight: "64px",
23
+ padding: "0 32px",
24
+ "@media (max-width: 480px)": { padding: "0 20px" },
25
+ },
26
+ main: {
27
+ flex: 1,
28
+ display: "flex",
29
+ flexDirection: "column",
30
+ alignItems: "center",
31
+ gap: "20px",
32
+ padding: "8vh 20px 48px",
33
+ "@media (max-width: 480px)": { paddingTop: "24px" },
34
+ },
35
+ // Gone when what's above renders nothing, so it leaves no gap.
36
+ above: {
37
+ width: "100%",
38
+ ":empty": { display: "none" },
39
+ },
40
+ column: {
41
+ width: "100%",
42
+ display: "flex",
43
+ flexDirection: "column",
44
+ boxSizing: "border-box",
45
+ },
46
+ footer: {
47
+ padding: "0 20px 16px",
48
+ },
49
+ });
50
+
51
+ export interface AuthShellProps {
52
+ /** The form and what goes with it, stacked in the column. */
53
+ children: ReactNode;
54
+ /** The site at the top left. Leave it out while it isn't known yet. */
55
+ brand?: { name: string; iconUrl?: string };
56
+ /** Above the column, as wide as it: notices, such as planned maintenance,
57
+ * which matter most to someone who can't sign in. */
58
+ above?: ReactNode;
59
+ /** At the foot of the page, such as legal links. */
60
+ footer?: ReactNode;
61
+ /** The column's width in px. Defaults to 400; a consent screen may want 440. */
62
+ maxWidth?: number;
63
+ /** The space between the column's children in px. Defaults to 20. */
64
+ gap?: number;
65
+ }
66
+
67
+ export function AuthShell({
68
+ children,
69
+ brand,
70
+ above,
71
+ footer,
72
+ maxWidth = 400,
73
+ gap = 20,
74
+ }: AuthShellProps) {
75
+ const styles = useStyles();
76
+ const canvas = useCanvasClass();
77
+ return (
78
+ <div className={mergeClasses(styles.page, canvas)}>
79
+ {brand ? (
80
+ <header className={styles.header}>
81
+ {/* No alt text: the name is written beside it. */}
82
+ <BrandMark iconUrl={brand.iconUrl} />
83
+ <Text weight="semibold" size={400}>
84
+ {brand.name}
85
+ </Text>
86
+ </header>
87
+ ) : (
88
+ // The same space, with no empty banner landmark.
89
+ <div className={styles.header} />
90
+ )}
91
+ <main className={styles.main}>
92
+ {above != null && (
93
+ <div className={styles.above} style={{ maxWidth }}>
94
+ {above}
95
+ </div>
96
+ )}
97
+ <div className={styles.column} style={{ maxWidth, gap }}>
98
+ {children}
99
+ </div>
100
+ </main>
101
+ {footer != null && <footer className={styles.footer}>{footer}</footer>}
102
+ </div>
103
+ );
104
+ }
@@ -0,0 +1,40 @@
1
+ // A link drawn as a Fluent button, for a button whose only job is to open a
2
+ // page: as a link, it opens in a new tab on a middle-click, shows its address
3
+ // on hover, and reads as a link to screen readers. It goes through the app's
4
+ // router like any library link.
5
+
6
+ import {
7
+ mergeClasses,
8
+ useButtonStyles_unstable,
9
+ useButton_unstable,
10
+ type ButtonProps,
11
+ } from "@fluentui/react-components";
12
+ import type { ReactElement, ReactNode } from "react";
13
+ import { UiLink } from "../provider/context.js";
14
+
15
+ export function ButtonLink({
16
+ to,
17
+ appearance,
18
+ size,
19
+ icon,
20
+ className,
21
+ children,
22
+ }: {
23
+ to: string;
24
+ appearance?: ButtonProps["appearance"];
25
+ size?: ButtonProps["size"];
26
+ icon?: ReactElement;
27
+ className?: string;
28
+ children: ReactNode;
29
+ }) {
30
+ // Fluent's own state and classes for a button drawn as an anchor. Only the
31
+ // classes are used: the anchor is the router's.
32
+ const state = useButton_unstable({ as: "a", appearance, size, icon, children }, null);
33
+ useButtonStyles_unstable(state);
34
+ return (
35
+ <UiLink to={to} className={mergeClasses(state.root.className, className)}>
36
+ {state.icon && <span className={state.icon.className}>{icon}</span>}
37
+ {children}
38
+ </UiLink>
39
+ );
40
+ }
@@ -1,7 +1,7 @@
1
1
  // Ctrl K search, as Prism and Vellum both have it: a dialog pinned near the
2
2
  // top of the screen (so the list grows downwards and the field stays put), a
3
3
  // field, grouped results and the keys to use them. ↑ ↓ move, Enter opens,
4
- // Esc closes. The app does the searching: it holds the query and gives the
4
+ // Esc closes. The app does the searching: it hears the query and gives the
5
5
  // groups to show.
6
6
 
7
7
  import {
@@ -12,6 +12,7 @@ import {
12
12
  makeStyles,
13
13
  mergeClasses,
14
14
  tokens,
15
+ useIsomorphicLayoutEffect,
15
16
  } from "@fluentui/react-components";
16
17
  import { ArrowEnterLeftRegular, DismissRegular, SearchRegular } from "@fluentui/react-icons";
17
18
  import {
@@ -185,9 +186,11 @@ const useStyles = makeStyles({
185
186
  },
186
187
  });
187
188
 
188
- export interface CommandItem {
189
+ export interface CommandItem<T = unknown> {
189
190
  /** Unique within the palette. */
190
191
  id: string;
192
+ /** Anything of yours, handed back with the row to `onSelect`: what the row stands for. */
193
+ data?: T;
191
194
  /** The row's text. Wrap matched words in `<mark>` to highlight them. */
192
195
  title: ReactNode;
193
196
  /** One line under the title: where the result is, what matched. */
@@ -203,31 +206,41 @@ export interface CommandItem {
203
206
  action?: ReactNode;
204
207
  }
205
208
 
206
- export interface CommandGroup {
209
+ export interface CommandGroup<T = unknown> {
207
210
  /** The group's heading. With none, the items follow the group before. */
208
211
  label?: ReactNode;
209
212
  /** A button beside the heading, such as "Clear" for recent searches. */
210
213
  action?: ReactNode;
211
214
  /** The group's rows. A group without any isn't shown. */
212
- items: CommandItem[];
215
+ items: CommandItem<T>[];
213
216
  }
214
217
 
215
- export interface CommandPaletteProps {
218
+ export interface CommandPaletteProps<T = unknown> {
216
219
  /** Whether the palette is open. */
217
220
  open: boolean;
218
221
  /** Called with the new state, as when Esc or the close button closes it. */
219
222
  onOpenChange: (open: boolean) => void;
220
- /** The field's text. Clear it when you open the palette if each search should start anew. */
221
- query: string;
222
- /** Called with the field's text as the reader types. */
223
+ /**
224
+ * The field's text, if you hold it: clear it as you open the palette to
225
+ * start a new search. Leave it out and the palette holds it, emptying the
226
+ * field each time it opens.
227
+ */
228
+ query?: string;
229
+ /**
230
+ * Called with the field's text as it changes. Without `query`, that
231
+ * includes the empty field of each opening.
232
+ */
223
233
  onQueryChange: (query: string) => void;
224
234
  /**
225
235
  * What to show for the query: `{ label?, action?, items }` each. `action`
226
236
  * is a button beside the label, such as "Clear".
227
237
  */
228
- groups: CommandGroup[];
229
- /** Called on Enter, or a click on a row. Close the palette here when the row leads away. */
230
- onSelect: (item: CommandItem) => void;
238
+ groups: CommandGroup<T>[];
239
+ /**
240
+ * Called on Enter, or a click on a row, with the row and its `data`. Close
241
+ * the palette here when the row leads away.
242
+ */
243
+ onSelect: (item: CommandItem<T>) => void;
231
244
  /** The field's placeholder and accessible name. */
232
245
  placeholder: string;
233
246
  /** Shows a spinner in the field while results are on their way. */
@@ -238,7 +251,7 @@ export interface CommandPaletteProps {
238
251
  status?: ReactNode;
239
252
  }
240
253
 
241
- export function CommandPalette({
254
+ export function CommandPalette<T = unknown>({
242
255
  open,
243
256
  onOpenChange,
244
257
  query,
@@ -249,7 +262,7 @@ export function CommandPalette({
249
262
  loading,
250
263
  empty,
251
264
  status,
252
- }: CommandPaletteProps) {
265
+ }: CommandPaletteProps<T>) {
253
266
  const styles = useStyles();
254
267
  const strings = useUiStrings();
255
268
  const listId = useId();
@@ -275,6 +288,34 @@ export function CommandPalette({
275
288
  );
276
289
  const active = flat[activeIndex];
277
290
 
291
+ // Each opening starts at the top row. Without `query`, the palette holds
292
+ // the text, and each opening starts a new search: the field empties as the
293
+ // palette opens, and the app hears of it before the palette paints, to give
294
+ // the groups for the empty text.
295
+ const controlled = query !== undefined;
296
+ const [ownQuery, setOwnQuery] = useState("");
297
+ const text = controlled ? query : ownQuery;
298
+ const [wasOpen, setWasOpen] = useState(false);
299
+ const [emptied, setEmptied] = useState(0);
300
+ if (open !== wasOpen) {
301
+ setWasOpen(open);
302
+ if (open) {
303
+ setActiveId(null);
304
+ if (!controlled) {
305
+ setOwnQuery("");
306
+ setEmptied(emptied + 1);
307
+ }
308
+ }
309
+ }
310
+ // Once per emptying: not again when Strict Mode reruns the effect, nor on
311
+ // every render, as onQueryChange may be a new function each time.
312
+ const reported = useRef(0);
313
+ useIsomorphicLayoutEffect(() => {
314
+ if (reported.current === emptied) return;
315
+ reported.current = emptied;
316
+ onQueryChange("");
317
+ }, [emptied]);
318
+
278
319
  useEffect(() => {
279
320
  if (!active) return;
280
321
  listRef.current
@@ -314,8 +355,9 @@ export function CommandPalette({
314
355
  placeholder={placeholder}
315
356
  autoComplete="off"
316
357
  spellCheck={false}
317
- value={query}
358
+ value={text}
318
359
  onChange={(e) => {
360
+ if (!controlled) setOwnQuery(e.target.value);
319
361
  onQueryChange(e.target.value);
320
362
  setActiveId(null);
321
363
  }}