@eifi1/ui-kit 0.8.1 → 0.10.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.
- package/README.md +25 -11
- package/dist/components/alert-banner.d.ts +32 -5
- package/dist/components/alert-banner.js +57 -14
- package/dist/components/alert-banner.js.map +1 -1
- package/dist/components/amount-input.d.ts +6 -0
- package/dist/components/breadcrumbs.d.ts +60 -0
- package/dist/components/breadcrumbs.js +88 -0
- package/dist/components/breadcrumbs.js.map +1 -0
- package/dist/components/bulk-action-bar.d.ts +66 -0
- package/dist/components/bulk-action-bar.js +149 -0
- package/dist/components/bulk-action-bar.js.map +1 -0
- package/dist/components/calculator.d.ts +6 -0
- package/dist/components/chip.d.ts +58 -10
- package/dist/components/chip.js +91 -7
- package/dist/components/chip.js.map +1 -1
- package/dist/components/copy-button.d.ts +13 -4
- package/dist/components/copy-button.js +17 -4
- package/dist/components/copy-button.js.map +1 -1
- package/dist/components/data-table-filter-popover.d.ts +1 -1
- package/dist/components/data-table-filters.d.ts +1 -1
- package/dist/components/data-table.d.ts +1 -1
- package/dist/components/data-table.js +122 -91
- package/dist/components/data-table.js.map +1 -1
- package/dist/components/date-picker.d.ts +89 -3
- package/dist/components/date-picker.js +163 -68
- package/dist/components/date-picker.js.map +1 -1
- package/dist/components/description-list.d.ts +43 -6
- package/dist/components/description-list.js +91 -11
- package/dist/components/description-list.js.map +1 -1
- package/dist/components/dialog-frame.d.ts +7 -0
- package/dist/components/dialog-frame.js.map +1 -1
- package/dist/components/disclosure.d.ts +68 -4
- package/dist/components/disclosure.js +33 -15
- package/dist/components/disclosure.js.map +1 -1
- package/dist/components/file-dropzone.d.ts +3 -4
- package/dist/components/file-dropzone.js +2 -1
- package/dist/components/file-dropzone.js.map +1 -1
- package/dist/components/floating-panel.d.ts +29 -2
- package/dist/components/floating-panel.js +16 -2
- package/dist/components/floating-panel.js.map +1 -1
- package/dist/components/full-bleed-dialog.d.ts +23 -4
- package/dist/components/full-bleed-dialog.js +11 -2
- package/dist/components/full-bleed-dialog.js.map +1 -1
- package/dist/components/list.d.ts +174 -0
- package/dist/components/list.js +215 -0
- package/dist/components/list.js.map +1 -0
- package/dist/components/menu-item.d.ts +99 -0
- package/dist/components/menu-item.js +83 -0
- package/dist/components/menu-item.js.map +1 -0
- package/dist/components/modal.d.ts +23 -1
- package/dist/components/modal.js +36 -10
- package/dist/components/modal.js.map +1 -1
- package/dist/components/number-field.d.ts +6 -0
- package/dist/components/number-input.d.ts +6 -0
- package/dist/components/numpad-sheet.d.ts +6 -0
- package/dist/components/page-contents.js +1 -2
- package/dist/components/page-contents.js.map +1 -1
- package/dist/components/page-header.d.ts +37 -0
- package/dist/components/page-header.js +36 -0
- package/dist/components/page-header.js.map +1 -0
- package/dist/components/progress-bar.d.ts +16 -2
- package/dist/components/progress-bar.js +4 -2
- package/dist/components/progress-bar.js.map +1 -1
- package/dist/components/series-chart-labels.d.ts +3 -0
- package/dist/components/series-chart-labels.js +2 -1
- package/dist/components/series-chart-labels.js.map +1 -1
- package/dist/components/series-chart.d.ts +16 -0
- package/dist/components/series-chart.js +137 -3
- package/dist/components/series-chart.js.map +1 -1
- package/dist/components/status-dot.d.ts +49 -0
- package/dist/components/status-dot.js +52 -0
- package/dist/components/status-dot.js.map +1 -0
- package/dist/components/table.d.ts +39 -6
- package/dist/components/table.js +43 -4
- package/dist/components/table.js.map +1 -1
- package/dist/components/text.d.ts +63 -0
- package/dist/components/text.js +23 -0
- package/dist/components/text.js.map +1 -0
- package/dist/components/toast.d.ts +167 -0
- package/dist/components/toast.js +226 -0
- package/dist/components/toast.js.map +1 -0
- package/dist/components/toggle-group.d.ts +29 -1
- package/dist/components/toggle-group.js +52 -3
- package/dist/components/toggle-group.js.map +1 -1
- package/dist/components/tooltip.d.ts +38 -15
- package/dist/components/tooltip.js +85 -47
- package/dist/components/tooltip.js.map +1 -1
- package/dist/components/ui.d.ts +139 -16
- package/dist/components/ui.js +136 -26
- package/dist/components/ui.js.map +1 -1
- package/dist/components/use-table-state.d.ts +1 -1
- package/dist/{data-table-filters-CF1PXqjQ.d.ts → data-table-filters-Dh9uF_S-.d.ts} +33 -2
- package/dist/data-table.d.ts +1 -1
- package/dist/hooks/use-close-transition.d.ts +7 -1
- package/dist/hooks/use-close-transition.js +5 -2
- package/dist/hooks/use-close-transition.js.map +1 -1
- package/dist/hooks/use-copy-to-clipboard.js +1 -1
- package/dist/hooks/use-copy-to-clipboard.js.map +1 -1
- package/dist/hooks/use-overlay-history.js +84 -4
- package/dist/hooks/use-overlay-history.js.map +1 -1
- package/dist/i18n/defaults.d.ts +6 -0
- package/dist/i18n/defaults.js +11 -1
- package/dist/i18n/defaults.js.map +1 -1
- package/dist/i18n/kit-labels.d.ts +11 -0
- package/dist/i18n/kit-labels.js.map +1 -1
- package/dist/i18n/locales/de-CH-informal.d.ts +6 -0
- package/dist/i18n/locales/de-CH.d.ts +6 -0
- package/dist/i18n/locales/de-informal.d.ts +6 -0
- package/dist/i18n/locales/de.d.ts +6 -0
- package/dist/i18n/locales/de.js +31 -1
- package/dist/i18n/locales/de.js.map +1 -1
- package/dist/i18n/locales/es.d.ts +6 -0
- package/dist/i18n/locales/es.js +31 -1
- package/dist/i18n/locales/es.js.map +1 -1
- package/dist/i18n/locales/fr.d.ts +6 -0
- package/dist/i18n/locales/fr.js +31 -1
- package/dist/i18n/locales/fr.js.map +1 -1
- package/dist/i18n/locales/hu.d.ts +6 -0
- package/dist/i18n/locales/hu.js +31 -1
- package/dist/i18n/locales/hu.js.map +1 -1
- package/dist/i18n/locales/it.d.ts +6 -0
- package/dist/i18n/locales/it.js +31 -1
- package/dist/i18n/locales/it.js.map +1 -1
- package/dist/i18n/locales/zh.d.ts +6 -0
- package/dist/i18n/locales/zh.js +31 -1
- package/dist/i18n/locales/zh.js.map +1 -1
- package/dist/index.d.ts +18 -8
- package/dist/index.js +14 -0
- package/dist/index.js.map +1 -1
- package/dist/lib/clipping.d.ts +9 -0
- package/dist/lib/clipping.js +14 -0
- package/dist/lib/clipping.js.map +1 -0
- package/dist/search/command-palette.d.ts +67 -2
- package/dist/search/command-palette.js +147 -33
- package/dist/search/command-palette.js.map +1 -1
- package/dist/search/global-search.d.ts +166 -0
- package/dist/search/global-search.js +293 -0
- package/dist/search/global-search.js.map +1 -0
- package/dist/search/search-index.d.ts +105 -0
- package/dist/search/search-index.js +142 -0
- package/dist/search/search-index.js.map +1 -0
- package/dist/search.d.ts +3 -1
- package/dist/search.js +2 -0
- package/dist/search.js.map +1 -1
- package/dist/wizard/stepper-nav.d.ts +10 -1
- package/dist/wizard/stepper-nav.js +3 -2
- package/dist/wizard/stepper-nav.js.map +1 -1
- package/dist/wizard/types.d.ts +2 -2
- package/dist/wizard/types.js.map +1 -1
- package/dist/wizard/use-wizard.js +1 -1
- package/dist/wizard/use-wizard.js.map +1 -1
- package/dist/wizard/wizard-summary.js +3 -3
- package/dist/wizard/wizard-summary.js.map +1 -1
- package/package.json +25 -12
- package/src/components/alert-banner.tsx +117 -18
- package/src/components/breadcrumbs.tsx +168 -0
- package/src/components/bulk-action-bar.tsx +256 -0
- package/src/components/chip.tsx +164 -13
- package/src/components/copy-button.tsx +29 -7
- package/src/components/data-table.tsx +81 -5
- package/src/components/date-picker.tsx +377 -118
- package/src/components/description-list.tsx +168 -15
- package/src/components/dialog-frame.tsx +7 -0
- package/src/components/disclosure.tsx +116 -28
- package/src/components/file-dropzone.tsx +9 -10
- package/src/components/floating-panel.tsx +46 -2
- package/src/components/full-bleed-dialog.tsx +42 -5
- package/src/components/list.tsx +417 -0
- package/src/components/menu-item.tsx +214 -0
- package/src/components/modal.tsx +80 -17
- package/src/components/page-contents.tsx +4 -4
- package/src/components/page-header.tsx +68 -0
- package/src/components/progress-bar.tsx +27 -3
- package/src/components/series-chart-labels.ts +4 -0
- package/src/components/series-chart.tsx +253 -3
- package/src/components/status-dot.tsx +99 -0
- package/src/components/table.tsx +91 -6
- package/src/components/text.tsx +89 -0
- package/src/components/toast.tsx +441 -0
- package/src/components/toggle-group.tsx +82 -3
- package/src/components/tooltip.tsx +186 -100
- package/src/components/ui.tsx +321 -41
- package/src/hooks/use-close-transition.ts +14 -5
- package/src/hooks/use-copy-to-clipboard.ts +1 -1
- package/src/hooks/use-overlay-history.ts +181 -4
- package/src/i18n/defaults.ts +10 -0
- package/src/i18n/kit-labels.tsx +10 -0
- package/src/i18n/locales/de.ts +30 -0
- package/src/i18n/locales/es.ts +30 -0
- package/src/i18n/locales/fr.ts +30 -0
- package/src/i18n/locales/hu.ts +30 -0
- package/src/i18n/locales/it.ts +30 -0
- package/src/i18n/locales/zh.ts +30 -0
- package/src/index.ts +30 -0
- package/src/lib/clipping.ts +16 -0
- package/src/search/command-palette.tsx +241 -31
- package/src/search/global-search.tsx +525 -0
- package/src/search/search-index.ts +295 -0
- package/src/search.ts +2 -0
- package/src/wizard/stepper-nav.tsx +13 -2
- package/src/wizard/types.ts +2 -2
- package/src/wizard/use-wizard.ts +3 -3
- package/src/wizard/wizard-summary.tsx +14 -10
- package/tokens.css +97 -0
|
@@ -0,0 +1,525 @@
|
|
|
1
|
+
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
|
2
|
+
import type { ReactNode } from "react";
|
|
3
|
+
import { useHref, useInRouterContext, useNavigate } from "react-router";
|
|
4
|
+
import { AlertCircle, Loader2, Search } from "lucide-react";
|
|
5
|
+
import { Tooltip } from "../components/tooltip";
|
|
6
|
+
import { TOPBAR_TRIGGER_CLASS } from "../shell/topbar-controls";
|
|
7
|
+
import { cn } from "../lib/cn";
|
|
8
|
+
import { useKitLabels } from "../i18n/kit-labels";
|
|
9
|
+
import { CommandPalette, DEFAULT_COMMAND_PALETTE_LABELS, useCommandKey } from "./command-palette";
|
|
10
|
+
import type { CommandItem, CommandPaletteDensity, CommandPaletteLabels } from "./command-palette";
|
|
11
|
+
import { createSearchIndex } from "./search-index";
|
|
12
|
+
import type { SearchEntry, SearchIndexOptions } from "./search-index";
|
|
13
|
+
|
|
14
|
+
export interface GlobalSearchLabels {
|
|
15
|
+
/** The trigger's accessible name, and the dialog's. */
|
|
16
|
+
trigger: string;
|
|
17
|
+
/** The field's placeholder — says WHAT can be found, which "Search…" does not. */
|
|
18
|
+
placeholder: string;
|
|
19
|
+
/** The trigger's tooltip, given the shortcut as the platform writes it ("⌘K",
|
|
20
|
+
* "Ctrl K"). A function so a language can put the keys where its grammar wants. */
|
|
21
|
+
shortcut: (keys: string) => string;
|
|
22
|
+
/** Heading of the suggestions shown for an empty query. */
|
|
23
|
+
suggestions: string;
|
|
24
|
+
/** Heading for entries that name no `group`. */
|
|
25
|
+
results: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export const DEFAULT_GLOBAL_SEARCH_LABELS: GlobalSearchLabels = {
|
|
29
|
+
trigger: "Search",
|
|
30
|
+
placeholder: "Search or jump to…",
|
|
31
|
+
shortcut: (keys) => `Search (${keys})`,
|
|
32
|
+
suggestions: "Try",
|
|
33
|
+
results: "Results",
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* A place results come from that is not the static index — a server search, a
|
|
38
|
+
* local-first store too large to hand over whole. Each source is its own group, with its
|
|
39
|
+
* own debounce, its own "Searching…" line and its own failure: the static groups never
|
|
40
|
+
* wait for it, and one source failing never takes another's results with it.
|
|
41
|
+
*/
|
|
42
|
+
export interface GlobalSearchSource {
|
|
43
|
+
/** Stable key — the effect that runs the source is keyed by it, not by identity. */
|
|
44
|
+
id: string;
|
|
45
|
+
/** The group its results are shown under (an entry's own `group` is ignored). */
|
|
46
|
+
group: string;
|
|
47
|
+
/** Called with the trimmed query. Its results are shown AS GIVEN — the source ranked
|
|
48
|
+
* them — and never re-filtered by the index's matcher. `signal` aborts when the query
|
|
49
|
+
* moves on or the palette closes; a stale answer is dropped either way. */
|
|
50
|
+
search: (query: string, signal: AbortSignal) => Promise<readonly SearchEntry[]> | readonly SearchEntry[];
|
|
51
|
+
/** Shortest query it is asked for. Default 2 — one letter matches half a database. */
|
|
52
|
+
minChars?: number;
|
|
53
|
+
/** Quiet period after the last keystroke before it is asked. Default 200ms. */
|
|
54
|
+
debounceMs?: number;
|
|
55
|
+
/** Rows kept. Default: `indexOptions.groupLimit` (8). */
|
|
56
|
+
limit?: number;
|
|
57
|
+
/** Mask every row of this source for session replay, hints (amounts) included. An
|
|
58
|
+
* entry's own `redact` still wins. */
|
|
59
|
+
redact?: boolean;
|
|
60
|
+
/** Told when `search` throws or rejects (not when it is aborted). The group then
|
|
61
|
+
* shows the palette's `error` line instead of rows. */
|
|
62
|
+
onError?: (error: unknown) => void;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** What a custom trigger gets: everything the default button uses. */
|
|
66
|
+
export interface GlobalSearchTriggerProps {
|
|
67
|
+
open: () => void;
|
|
68
|
+
/** Resolved `trigger` label — the accessible name. */
|
|
69
|
+
label: string;
|
|
70
|
+
/** Resolved `shortcut(keys)` — the tooltip. */
|
|
71
|
+
tooltip: string;
|
|
72
|
+
/** "⌘K" on Apple platforms, "Ctrl K" elsewhere. */
|
|
73
|
+
keys: string;
|
|
74
|
+
/** For the trigger's `aria-keyshortcuts`. */
|
|
75
|
+
ariaKeyShortcuts: string;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** A suggestion for the empty query: an entry, the `id` of one in `entries`, or a query
|
|
79
|
+
* to type into the field. */
|
|
80
|
+
export type GlobalSearchSuggestion = SearchEntry | string | { query: string };
|
|
81
|
+
|
|
82
|
+
export interface GlobalSearchProps {
|
|
83
|
+
/**
|
|
84
|
+
* The static index: pages, actions, settings rows — already filtered by the app (by
|
|
85
|
+
* role, by privacy mode). Matched and ranked by {@link createSearchIndex}.
|
|
86
|
+
*
|
|
87
|
+
* Changing it re-runs the open search by itself. Nothing has to be stable: the index is
|
|
88
|
+
* rebuilt only when the entries' TEXT changes (ids, titles, keywords, …), so a list
|
|
89
|
+
* rebuilt on every render — `data = []` while a query is pending, icons as fresh JSX —
|
|
90
|
+
* neither re-indexes nor loops, and the icons and handlers used are always the latest.
|
|
91
|
+
*/
|
|
92
|
+
entries?: readonly SearchEntry[];
|
|
93
|
+
/** The async sources, each streamed into its own group. */
|
|
94
|
+
sources?: readonly GlobalSearchSource[];
|
|
95
|
+
/** What the empty query shows, under the `suggestions` heading. */
|
|
96
|
+
suggestions?: readonly GlobalSearchSuggestion[];
|
|
97
|
+
/**
|
|
98
|
+
* Show each suggested ENTRY under its own `group` instead of all of them under the
|
|
99
|
+
* one `suggestions` heading — keksdose's empty palette listed "Pages" and "Actions"
|
|
100
|
+
* apart, and one "Try" heading over both lost the difference. An entry with no
|
|
101
|
+
* `group` and a query suggestion (`{ query }`) stay under `suggestions`. `groupOrder`
|
|
102
|
+
* orders these groups as it orders the results'. Off by default.
|
|
103
|
+
*/
|
|
104
|
+
suggestionsKeepGroups?: boolean;
|
|
105
|
+
/** Groups listed here come first, in this order; the rest follow in ranking order. */
|
|
106
|
+
groupOrder?: readonly string[];
|
|
107
|
+
/** Ranking and capping — `groupLimit` (default 8) applies to every group. */
|
|
108
|
+
indexOptions?: SearchIndexOptions;
|
|
109
|
+
/**
|
|
110
|
+
* How an entry's `href` is followed on a plain click or ↵. Default: react-router's
|
|
111
|
+
* `navigate` when the search is rendered inside a router, else a full page load.
|
|
112
|
+
*/
|
|
113
|
+
navigate?: (href: string) => void;
|
|
114
|
+
/**
|
|
115
|
+
* The browser URL of an `href`, for the row's real link (middle-/⌘-click opens a tab).
|
|
116
|
+
* Default inside a router: the router's own (`#/page` under a hash router, the
|
|
117
|
+
* basename prefixed under a browser router); outside one, the href itself.
|
|
118
|
+
*/
|
|
119
|
+
hrefFor?: (href: string) => string;
|
|
120
|
+
/** Register ⌘K / Ctrl K. Default true; turn it off for a second, scoped search on a
|
|
121
|
+
* page that already has the app-wide one. */
|
|
122
|
+
shortcut?: boolean;
|
|
123
|
+
/** Controlled open state — so a button anywhere can open it. */
|
|
124
|
+
open?: boolean;
|
|
125
|
+
onOpenChange?: (open: boolean) => void;
|
|
126
|
+
/** Controlled query, as on `CommandPalette` (keksdose binds it to the URL's `q`). */
|
|
127
|
+
query?: string;
|
|
128
|
+
onQueryChange?: (query: string) => void;
|
|
129
|
+
searchOn?: "input" | "submit";
|
|
130
|
+
/** Mask every row for session replay (see `CommandPalette`). A source's or an entry's
|
|
131
|
+
* own `redact` wins. */
|
|
132
|
+
redactLabels?: boolean;
|
|
133
|
+
fullScreenOnPhone?: boolean;
|
|
134
|
+
/** `"button"` (default): the top-bar icon button. `"none"`: no trigger — the shortcut
|
|
135
|
+
* or a controlled `open` opens it. A function renders a trigger of your own. */
|
|
136
|
+
trigger?: "button" | "none" | ((props: GlobalSearchTriggerProps) => ReactNode);
|
|
137
|
+
/** Hide the default trigger below `sm` (kastlan's phone top bar has no room). */
|
|
138
|
+
hideTriggerOnPhone?: boolean;
|
|
139
|
+
/** Class for the default trigger button, merged over `TOPBAR_TRIGGER_CLASS`. */
|
|
140
|
+
triggerClassName?: string;
|
|
141
|
+
/**
|
|
142
|
+
* The default trigger's magnifier, in px. Default 16 (`size-4`), as it always was;
|
|
143
|
+
* 20 matches the kit's other top-bar triggers (`TopbarIconButton` draws `size-5`) and
|
|
144
|
+
* keksdose's top bar, which reached into the button with `[&_svg]:size-5` for it.
|
|
145
|
+
*/
|
|
146
|
+
triggerIconSize?: number;
|
|
147
|
+
/**
|
|
148
|
+
* Whether the trigger's accessible name includes the shortcut: `"plain"` (default)
|
|
149
|
+
* names it "Search"; `"withShortcut"` names it by `labels.shortcut(keys)` —
|
|
150
|
+
* "Search (⌘K)" on Apple platforms, "Search (Ctrl K)" elsewhere — the same text its
|
|
151
|
+
* tooltip shows, so a speech-control user ("click Search") and a sighted keyboard user
|
|
152
|
+
* meet the shortcut in the name itself (keksdose C25). `aria-keyshortcuts` is set
|
|
153
|
+
* either way. Also reaches a custom trigger as `triggerProps.label`.
|
|
154
|
+
*/
|
|
155
|
+
triggerName?: "plain" | "withShortcut";
|
|
156
|
+
/** The palette's row height — `CommandPalette`'s `density`. Default `"compact"`. */
|
|
157
|
+
density?: CommandPaletteDensity;
|
|
158
|
+
labels?: Partial<GlobalSearchLabels>;
|
|
159
|
+
/** Passed through to the palette (`empty`, `loading`, `error`, `hint`, …). */
|
|
160
|
+
paletteLabels?: Partial<CommandPaletteLabels>;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function isApplePlatform(): boolean {
|
|
164
|
+
if (typeof navigator === "undefined") return false;
|
|
165
|
+
const nav = navigator as Navigator & { userAgentData?: { platform?: string } };
|
|
166
|
+
return /mac|iphone|ipad|ipod/i.test(nav.userAgentData?.platform || nav.platform || nav.userAgent);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const pageLoad = (href: string) => window.location.assign(href);
|
|
170
|
+
const identity = (href: string) => href;
|
|
171
|
+
|
|
172
|
+
/** The entries' text, which is all the index reads — see `entries`. */
|
|
173
|
+
function signature(entries: readonly SearchEntry[]): string {
|
|
174
|
+
return entries
|
|
175
|
+
.map((e) =>
|
|
176
|
+
[e.id, e.title, (e.keywords ?? []).join("\u0003"), e.description, e.group, e.hint, e.href, e.weight, e.redact].join(
|
|
177
|
+
"\u0001",
|
|
178
|
+
),
|
|
179
|
+
)
|
|
180
|
+
.join("\u0002");
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** Focus the open palette's field again — after a suggestion typed itself into it, the
|
|
184
|
+
* row that was clicked (and held focus) is gone. */
|
|
185
|
+
function refocusField() {
|
|
186
|
+
requestAnimationFrame(() => {
|
|
187
|
+
const fields = document.querySelectorAll<HTMLInputElement>('[role="dialog"][aria-modal="true"] input[role="combobox"]');
|
|
188
|
+
fields[fields.length - 1]?.focus();
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
interface SourceResult {
|
|
193
|
+
query: string;
|
|
194
|
+
status: "loading" | "done" | "error";
|
|
195
|
+
entries: readonly SearchEntry[];
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* The app-wide ⌘K search, whole: the top-bar trigger, the shortcut, and a
|
|
200
|
+
* {@link CommandPalette} fed from a ranked index ({@link createSearchIndex}) and any
|
|
201
|
+
* number of async sources.
|
|
202
|
+
*
|
|
203
|
+
* Every consumer had built this out of `CommandPalette` by hand, and each copy had the
|
|
204
|
+
* same holes — a substring match, no ranking, no typo tolerance, results in declaration
|
|
205
|
+
* order, one monolithic provider in which the static groups waited on the slowest
|
|
206
|
+
* request. This is that wrapper once:
|
|
207
|
+
*
|
|
208
|
+
* <GlobalSearch
|
|
209
|
+
* entries={pages} // { id, title, keywords, group, href, icon }
|
|
210
|
+
* sources={[{ id: "tx", group: "Transactions", search: (q, signal) => api.search(q, { signal }) }]}
|
|
211
|
+
* suggestions={["page-budget", "action-new-account"]}
|
|
212
|
+
* />
|
|
213
|
+
*
|
|
214
|
+
* Inside a react-router tree it navigates with the router and builds its links with it;
|
|
215
|
+
* outside one, pass `navigate` (or accept full page loads).
|
|
216
|
+
*/
|
|
217
|
+
export function GlobalSearch(props: GlobalSearchProps) {
|
|
218
|
+
// Two components rather than a conditional hook: `useNavigate` throws outside a
|
|
219
|
+
// router, and whether we are in one does not change over a component's life.
|
|
220
|
+
const inRouter = useInRouterContext();
|
|
221
|
+
if (inRouter && (!props.navigate || !props.hrefFor)) return <RoutedGlobalSearch {...props} />;
|
|
222
|
+
return <GlobalSearchImpl {...props} navigate={props.navigate ?? pageLoad} hrefFor={props.hrefFor ?? identity} />;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function RoutedGlobalSearch(props: GlobalSearchProps) {
|
|
226
|
+
const routerNavigate = useNavigate();
|
|
227
|
+
// The router's href for "/" is its base ("#/" under a hash router, "/app/" under a
|
|
228
|
+
// basename); every href is that base plus the path.
|
|
229
|
+
const base = useHref("/").replace(/\/$/, "");
|
|
230
|
+
const navigate = useCallback((href: string) => void routerNavigate(href), [routerNavigate]);
|
|
231
|
+
const hrefFor = useCallback((href: string) => (href.startsWith("/") ? base + href : href), [base]);
|
|
232
|
+
return <GlobalSearchImpl {...props} navigate={props.navigate ?? navigate} hrefFor={props.hrefFor ?? hrefFor} />;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function GlobalSearchImpl({
|
|
236
|
+
entries,
|
|
237
|
+
sources,
|
|
238
|
+
suggestions,
|
|
239
|
+
suggestionsKeepGroups = false,
|
|
240
|
+
groupOrder,
|
|
241
|
+
indexOptions,
|
|
242
|
+
navigate,
|
|
243
|
+
hrefFor,
|
|
244
|
+
shortcut = true,
|
|
245
|
+
open: openProp,
|
|
246
|
+
onOpenChange,
|
|
247
|
+
query: queryProp,
|
|
248
|
+
onQueryChange,
|
|
249
|
+
searchOn,
|
|
250
|
+
redactLabels = false,
|
|
251
|
+
fullScreenOnPhone,
|
|
252
|
+
trigger = "button",
|
|
253
|
+
hideTriggerOnPhone = false,
|
|
254
|
+
triggerClassName,
|
|
255
|
+
triggerIconSize,
|
|
256
|
+
triggerName = "plain",
|
|
257
|
+
density,
|
|
258
|
+
labels,
|
|
259
|
+
paletteLabels,
|
|
260
|
+
}: GlobalSearchProps & { navigate: (href: string) => void; hrefFor: (href: string) => string }) {
|
|
261
|
+
const l = useKitLabels("globalSearch", DEFAULT_GLOBAL_SEARCH_LABELS, labels);
|
|
262
|
+
const pl = useKitLabels("commandPalette", DEFAULT_COMMAND_PALETTE_LABELS, paletteLabels);
|
|
263
|
+
const [ownOpen, setOwnOpen] = useState(false);
|
|
264
|
+
const open = openProp ?? ownOpen;
|
|
265
|
+
const [ownQuery, setOwnQuery] = useState("");
|
|
266
|
+
const queryControlled = queryProp !== undefined;
|
|
267
|
+
const query = queryControlled ? queryProp : ownQuery;
|
|
268
|
+
const q = query.trim();
|
|
269
|
+
|
|
270
|
+
const setOpen = useCallback(
|
|
271
|
+
(next: boolean) => {
|
|
272
|
+
if (openProp === undefined) setOwnOpen(next);
|
|
273
|
+
onOpenChange?.(next);
|
|
274
|
+
},
|
|
275
|
+
[openProp, onOpenChange],
|
|
276
|
+
);
|
|
277
|
+
const setQuery = useCallback(
|
|
278
|
+
(next: string) => {
|
|
279
|
+
if (!queryControlled) setOwnQuery(next);
|
|
280
|
+
onQueryChange?.(next);
|
|
281
|
+
},
|
|
282
|
+
[queryControlled, onQueryChange],
|
|
283
|
+
);
|
|
284
|
+
|
|
285
|
+
// Each open starts blank — unless the owner controls the query (a URL `q`). Adjusted
|
|
286
|
+
// during render, React's pattern for state that follows a prop, so a controlled `open`
|
|
287
|
+
// gets the same reset as the trigger does.
|
|
288
|
+
const [wasOpen, setWasOpen] = useState(open);
|
|
289
|
+
if (wasOpen !== open) {
|
|
290
|
+
setWasOpen(open);
|
|
291
|
+
if (open && !queryControlled) setOwnQuery("");
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
const openSearch = useCallback(() => setOpen(true), [setOpen]);
|
|
295
|
+
const noop = useCallback(() => {}, []);
|
|
296
|
+
useCommandKey(shortcut ? openSearch : noop);
|
|
297
|
+
|
|
298
|
+
/* ── the static index ─────────────────────────────────────────────────── */
|
|
299
|
+
|
|
300
|
+
// Everything below is keyed by CONTENT, never by the identity of what the app passed:
|
|
301
|
+
// inline arrays and `data = []` defaults are the norm, and an identity key would
|
|
302
|
+
// re-index and re-search on every render of the app. Handlers, which can close over
|
|
303
|
+
// anything, are read from refs at the moment a row is chosen — never stale.
|
|
304
|
+
const list = entries ?? EMPTY;
|
|
305
|
+
const sig = signature(list);
|
|
306
|
+
const optionsKey = JSON.stringify(indexOptions ?? {});
|
|
307
|
+
const groupLimit = indexOptions?.groupLimit ?? 8;
|
|
308
|
+
// `sig` and `optionsKey` stand for `list` and `indexOptions`: same text, same index.
|
|
309
|
+
/* eslint-disable react-hooks/exhaustive-deps */
|
|
310
|
+
const index = useMemo(() => createSearchIndex(list, indexOptions), [sig, optionsKey]);
|
|
311
|
+
const byId = useMemo(() => new Map(list.map((e) => [e.id, e])), [sig]);
|
|
312
|
+
|
|
313
|
+
const sourceKey = (sources ?? [])
|
|
314
|
+
.map((s) => [s.id, s.group, s.minChars ?? 2, s.debounceMs ?? 200, s.limit, s.redact].join("\u0001"))
|
|
315
|
+
.join("\u0002");
|
|
316
|
+
const sourceList = useMemo(() => sources ?? [], [sourceKey]);
|
|
317
|
+
|
|
318
|
+
const suggestionsKey = (suggestions ?? [])
|
|
319
|
+
.map((s) => (typeof s === "string" ? `i:${s}` : "query" in s ? `q:${s.query}` : `e:${signature([s])}`))
|
|
320
|
+
.join("\u0002");
|
|
321
|
+
const suggestionList = useMemo(() => suggestions ?? [], [suggestionsKey]);
|
|
322
|
+
|
|
323
|
+
const groupOrderKey = (groupOrder ?? []).join("\u0002");
|
|
324
|
+
const order = useMemo(() => groupOrder ?? [], [groupOrderKey]);
|
|
325
|
+
/* eslint-enable react-hooks/exhaustive-deps */
|
|
326
|
+
|
|
327
|
+
// The live objects, for the moment a row is chosen or a source is asked.
|
|
328
|
+
const live = useRef({ entries: list, sources: sources ?? [], suggestions: suggestions ?? [], navigate });
|
|
329
|
+
useLayoutEffect(() => {
|
|
330
|
+
live.current = { entries: list, sources: sources ?? [], suggestions: suggestions ?? [], navigate };
|
|
331
|
+
});
|
|
332
|
+
|
|
333
|
+
/* ── the async sources ────────────────────────────────────────────────── */
|
|
334
|
+
|
|
335
|
+
const [sourceResults, setSourceResults] = useState<Record<string, SourceResult>>({});
|
|
336
|
+
useEffect(() => {
|
|
337
|
+
const controllers: AbortController[] = [];
|
|
338
|
+
const timers: ReturnType<typeof setTimeout>[] = [];
|
|
339
|
+
const asked = open ? live.current.sources.filter((s) => q.length >= (s.minChars ?? 2)) : [];
|
|
340
|
+
for (const source of asked) {
|
|
341
|
+
const id = source.id;
|
|
342
|
+
const controller = new AbortController();
|
|
343
|
+
controllers.push(controller);
|
|
344
|
+
timers.push(
|
|
345
|
+
setTimeout(async () => {
|
|
346
|
+
const settle = (result: SourceResult) => {
|
|
347
|
+
if (!controller.signal.aborted) setSourceResults((prev) => ({ ...prev, [id]: result }));
|
|
348
|
+
};
|
|
349
|
+
try {
|
|
350
|
+
const found = await source.search(q, controller.signal);
|
|
351
|
+
settle({ query: q, status: "done", entries: found });
|
|
352
|
+
} catch (error) {
|
|
353
|
+
if (controller.signal.aborted) return;
|
|
354
|
+
source.onError?.(error);
|
|
355
|
+
settle({ query: q, status: "error", entries: [] });
|
|
356
|
+
}
|
|
357
|
+
}, source.debounceMs ?? 200),
|
|
358
|
+
);
|
|
359
|
+
}
|
|
360
|
+
return () => {
|
|
361
|
+
timers.forEach(clearTimeout);
|
|
362
|
+
controllers.forEach((c) => c.abort());
|
|
363
|
+
};
|
|
364
|
+
}, [open, q, sourceKey]);
|
|
365
|
+
|
|
366
|
+
/* ── rows ─────────────────────────────────────────────────────────────── */
|
|
367
|
+
|
|
368
|
+
const toItem = useCallback(
|
|
369
|
+
(prefix: string, entry: SearchEntry, group: string, redact = redactLabels): CommandItem => ({
|
|
370
|
+
id: `${prefix}${entry.id}`,
|
|
371
|
+
label: entry.title,
|
|
372
|
+
hint: entry.hint,
|
|
373
|
+
group,
|
|
374
|
+
icon: entry.icon,
|
|
375
|
+
redact: entry.redact ?? redact,
|
|
376
|
+
href: entry.href !== undefined ? hrefFor(entry.href) : undefined,
|
|
377
|
+
onSelect: () => {
|
|
378
|
+
// The entry as the app has it NOW — its handler may close over newer state
|
|
379
|
+
// than the one this row was built from.
|
|
380
|
+
const current = live.current.entries.find((e) => e.id === entry.id) ?? entry;
|
|
381
|
+
if (current.onSelect) current.onSelect();
|
|
382
|
+
else if (current.href !== undefined) live.current.navigate(current.href);
|
|
383
|
+
},
|
|
384
|
+
}),
|
|
385
|
+
[hrefFor, redactLabels],
|
|
386
|
+
);
|
|
387
|
+
|
|
388
|
+
// `toItem` only BUILDS `onSelect` closures here; `live` is read when a row is chosen,
|
|
389
|
+
// which the compiler lint cannot tell from a read during render.
|
|
390
|
+
/* eslint-disable react-hooks/refs */
|
|
391
|
+
const items = useMemo((): CommandItem[] => {
|
|
392
|
+
const ordered = (out: CommandItem[]) => {
|
|
393
|
+
if (!order.length) return out;
|
|
394
|
+
const rank = (group: string) => {
|
|
395
|
+
const i = order.indexOf(group);
|
|
396
|
+
return i === -1 ? order.length : i;
|
|
397
|
+
};
|
|
398
|
+
// Stable: within a rank, groups keep the order their best hit gave them.
|
|
399
|
+
return out
|
|
400
|
+
.map((item, i) => ({ item, i }))
|
|
401
|
+
.sort((a, b) => rank(a.item.group) - rank(b.item.group) || a.i - b.i)
|
|
402
|
+
.map(({ item }) => item);
|
|
403
|
+
};
|
|
404
|
+
|
|
405
|
+
if (!q) {
|
|
406
|
+
const out: CommandItem[] = [];
|
|
407
|
+
const groupOf = (entry: SearchEntry) =>
|
|
408
|
+
suggestionsKeepGroups ? (entry.group ?? l.suggestions) : l.suggestions;
|
|
409
|
+
suggestionList.forEach((s, i) => {
|
|
410
|
+
if (typeof s === "string") {
|
|
411
|
+
const entry = byId.get(s);
|
|
412
|
+
if (entry) out.push(toItem("try:", entry, groupOf(entry)));
|
|
413
|
+
} else if ("query" in s) {
|
|
414
|
+
out.push({
|
|
415
|
+
id: `try:q${i}`,
|
|
416
|
+
label: s.query,
|
|
417
|
+
group: l.suggestions,
|
|
418
|
+
icon: <Search className="size-4" />,
|
|
419
|
+
onSelect: () => {
|
|
420
|
+
// The palette closes before it runs a row; a query suggestion keeps it
|
|
421
|
+
// open and types itself in instead.
|
|
422
|
+
setOpen(true);
|
|
423
|
+
setQuery(s.query);
|
|
424
|
+
refocusField();
|
|
425
|
+
},
|
|
426
|
+
});
|
|
427
|
+
} else out.push(toItem("try:", s, groupOf(s)));
|
|
428
|
+
});
|
|
429
|
+
// One heading has nothing to order; kept groups are ordered like results.
|
|
430
|
+
return suggestionsKeepGroups ? ordered(out) : out;
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
const out = index.search(q).map((hit) => toItem("s:", hit.entry, hit.entry.group ?? l.results));
|
|
434
|
+
for (const source of sourceList) {
|
|
435
|
+
if (q.length < (source.minChars ?? 2)) continue;
|
|
436
|
+
const result = sourceResults[source.id];
|
|
437
|
+
const status = (label: string, icon: ReactNode): CommandItem => ({
|
|
438
|
+
id: `src:${source.id}:status`,
|
|
439
|
+
label,
|
|
440
|
+
group: source.group,
|
|
441
|
+
icon,
|
|
442
|
+
kind: "status",
|
|
443
|
+
onSelect: noop,
|
|
444
|
+
});
|
|
445
|
+
// Anything but an answer to THIS query is still loading — including the previous
|
|
446
|
+
// query's rows, which would otherwise sit under the new query as if they matched.
|
|
447
|
+
if (!result || result.query !== q) {
|
|
448
|
+
out.push(status(pl.loading, <Loader2 className="size-3.5 animate-spin" />));
|
|
449
|
+
} else if (result.status === "error") {
|
|
450
|
+
out.push(status(pl.error ?? DEFAULT_COMMAND_PALETTE_LABELS.error!, <AlertCircle className="size-3.5" />));
|
|
451
|
+
} else {
|
|
452
|
+
for (const entry of result.entries.slice(0, source.limit ?? groupLimit)) {
|
|
453
|
+
out.push(toItem(`src:${source.id}:`, entry, source.group, source.redact ?? redactLabels));
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
return ordered(out);
|
|
459
|
+
}, [q, suggestionList, suggestionsKeepGroups, byId, index, sourceList, sourceResults, order, groupLimit, toItem, l.suggestions, l.results, pl.loading, pl.error, setOpen, setQuery, noop, redactLabels]);
|
|
460
|
+
/* eslint-enable react-hooks/refs */
|
|
461
|
+
|
|
462
|
+
// The palette re-runs its provider on a `revision` change, never on the provider's
|
|
463
|
+
// identity — and `items` is everything the provider answers with.
|
|
464
|
+
const provider = useCallback(() => items, [items]);
|
|
465
|
+
|
|
466
|
+
const resolvedPaletteLabels = useMemo(
|
|
467
|
+
() => ({ dialog: l.trigger, placeholder: l.placeholder, ...paletteLabels }),
|
|
468
|
+
[l.trigger, l.placeholder, paletteLabels],
|
|
469
|
+
);
|
|
470
|
+
|
|
471
|
+
const apple = useMemo(() => isApplePlatform(), []);
|
|
472
|
+
const keys = apple ? "⌘K" : "Ctrl K";
|
|
473
|
+
const triggerLabel = triggerName === "withShortcut" ? l.shortcut(keys) : l.trigger;
|
|
474
|
+
const triggerProps: GlobalSearchTriggerProps = {
|
|
475
|
+
open: openSearch,
|
|
476
|
+
label: triggerLabel,
|
|
477
|
+
tooltip: l.shortcut(keys),
|
|
478
|
+
keys,
|
|
479
|
+
ariaKeyShortcuts: "Meta+K Control+K",
|
|
480
|
+
};
|
|
481
|
+
|
|
482
|
+
return (
|
|
483
|
+
<>
|
|
484
|
+
{typeof trigger === "function"
|
|
485
|
+
? trigger(triggerProps)
|
|
486
|
+
: trigger === "button" && (
|
|
487
|
+
<Tooltip
|
|
488
|
+
label={triggerProps.tooltip}
|
|
489
|
+
side="bottom"
|
|
490
|
+
portal
|
|
491
|
+
className={hideTriggerOnPhone ? "hidden sm:block" : undefined}
|
|
492
|
+
>
|
|
493
|
+
<button
|
|
494
|
+
type="button"
|
|
495
|
+
onClick={openSearch}
|
|
496
|
+
aria-label={triggerLabel}
|
|
497
|
+
aria-keyshortcuts={triggerProps.ariaKeyShortcuts}
|
|
498
|
+
aria-haspopup="dialog"
|
|
499
|
+
className={cn(TOPBAR_TRIGGER_CLASS, triggerClassName)}
|
|
500
|
+
>
|
|
501
|
+
<Search
|
|
502
|
+
className={triggerIconSize === undefined ? "size-4" : undefined}
|
|
503
|
+
style={triggerIconSize === undefined ? undefined : { width: triggerIconSize, height: triggerIconSize }}
|
|
504
|
+
/>
|
|
505
|
+
</button>
|
|
506
|
+
</Tooltip>
|
|
507
|
+
)}
|
|
508
|
+
<CommandPalette
|
|
509
|
+
open={open}
|
|
510
|
+
onClose={() => setOpen(false)}
|
|
511
|
+
search={provider}
|
|
512
|
+
revision={items}
|
|
513
|
+
query={query}
|
|
514
|
+
onQueryChange={setQuery}
|
|
515
|
+
searchOn={searchOn}
|
|
516
|
+
redactLabels={redactLabels}
|
|
517
|
+
fullScreenOnPhone={fullScreenOnPhone}
|
|
518
|
+
density={density}
|
|
519
|
+
labels={resolvedPaletteLabels}
|
|
520
|
+
/>
|
|
521
|
+
</>
|
|
522
|
+
);
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
const EMPTY: readonly SearchEntry[] = [];
|