@tristan2828/ui-foundation 4.86.0 → 4.87.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 CHANGED
@@ -18,7 +18,7 @@ than installing this by hand:
18
18
 
19
19
  | Import | What |
20
20
  |---|---|
21
- | `@tristan2828/ui-foundation` | `AppShell`, `DataTable`, `EntityView` (with `EditableValue`, `editInPlace`, printing its notes and `usePrinting`, `KeyStats`, `IconAction`), `EntityForm`, `Markdown` (with `countTasks`, `toggleTaskAt`), `RichTextEditor`, `ErrorState`, `MultiChoice`, `MultiReference`, `ListEditor`, `PasswordInput`, `RouteErrorBoundary`, `FoundationProviders`, `DataEnvironmentBanner`, `LoginRoute`, `RegisterRoute`, `useAuth`, `useTableUrlState`, `useRecordUpdate`, `useDebouncedValue`, `createQueryClient`, `cn`; types `Page`, `AppError`, `QuerySpec`. For timed screens (`docs/foundation/timed-screens.md`): `SessionView`, `useSessionClock`, `useWakeLock`, `useMuted`, `usePrefersReducedMotion`, and the audio cues `unlockAudio`, `chime`, `sequence`, `cancelCues`, `onCuesRecovered`, `cuesInSync`, `keepAudioAlive`, `say`, `hush`, `vibrate`, `canVibrate`. For the page standards (`docs/foundation/design-language.md` "Parts of the page standards"): `ValueList`, `ListHeader`, `Timeline`, `NeedsYou`, `Freshness`, `PartEmpty`. For a list's tools (`docs/foundation/cell-patterns.md` 25 and 26): `FilterBar`, `FilterSelect`, `RelatedTable`, and DataTable's `views`, `columnsMenu`, `rowActions`, `phoneRow`, `limit` and `viewAll`. For reminders (`docs/foundation/reminders.md`): `AllowReminders`, `usePushPermission`. For a record opened in a dialog over its list (`docs/foundation/add-an-entity.md`): `RecordDialogRoute`, `RecordLink`, `useOpenRecord`, `useRecordDialog`, `recordDialogState`, and for a new record over it `useNewRecordDialog`. A small form in a dialog: `FormDialog`. For the form standard (`docs/foundation/add-an-entity.md` "Forms"): `FormSection`, `OptionSelect`, `countFormErrors`, `fieldRows`; from `/ui/field`, `Field` takes `size`, `solo` and `kind`, and `FieldLabel` takes `required`. From `/ui/dialog`, `DialogContent` takes `size` and `dirty`, and `DiscardChangesDialog` is the "Discard your changes?" prompt |
21
+ | `@tristan2828/ui-foundation` | `AppShell`, `DataTable`, `EntityView` (with `EditableValue`, `editInPlace`, printing its notes and `usePrinting`, `KeyStats`, `IconAction`), `EntityForm`, `Markdown` (with `countTasks`, `toggleTaskAt`), `RichTextEditor`, `ErrorState`, `MultiChoice`, `MultiReference`, `ListEditor`, `PasswordInput`, `RouteErrorBoundary`, `FoundationProviders`, `DataEnvironmentBanner`, `LoginRoute`, `RegisterRoute`, `useAuth`, `useTableUrlState`, `useRecordUpdate`, `useDebouncedValue`, `createQueryClient`, `cn`; types `Page`, `AppError`, `QuerySpec`. For timed screens (`docs/foundation/timed-screens.md`): `SessionView`, `useSessionClock`, `useWakeLock`, `useMuted`, `usePrefersReducedMotion`, and the audio cues `unlockAudio`, `chime`, `sequence`, `cancelCues`, `onCuesRecovered`, `cuesInSync`, `keepAudioAlive`, `say`, `hush`, `vibrate`, `canVibrate`. For the page standards (`docs/foundation/design-language.md` "Parts of the page standards"): `ValueList`, `ListHeader`, `Timeline`, `NeedsYou`, `Freshness`, `PartEmpty`. For a list's tools (`docs/foundation/cell-patterns.md` 25 and 26): `FilterBar`, `FilterSelect`, `RelatedTable`, and DataTable's `views`, `columnsMenu`, `rowActions`, `phoneRow`, `limit` and `viewAll`. For reminders (`docs/foundation/reminders.md`): `AllowReminders`, `usePushPermission`. For a record opened in a dialog over its list (`docs/foundation/add-an-entity.md`): `RecordDialogRoute`, `RecordLink`, `useOpenRecord`, `useRecordDialog`, `recordDialogState`, and for a new record over it `useNewRecordDialog`. A small form in a dialog: `FormDialog`. For the trail and search in `AppShell`'s bar (`docs/foundation/design-language.md` "The sidebar and the phone's bar"): `usePageTrail`, `useRecentRecord`, `PageTrail`; types `AppShellSearch`, `SearchRecord`, `RecentRecord`. For the form standard (`docs/foundation/add-an-entity.md` "Forms"): `FormSection`, `OptionSelect`, `countFormErrors`, `fieldRows`; from `/ui/field`, `Field` takes `size`, `solo` and `kind`, and `FieldLabel` takes `required`. From `/ui/dialog`, `DialogContent` takes `size` and `dirty`, and `DiscardChangesDialog` is the "Discard your changes?" prompt |
22
22
  | `@tristan2828/ui-foundation/ui/<name>` | shadcn primitives: badge, button, calendar, card, checkbox, combobox, dialog, empty, field, input, input-group, label, popover, select, separator, sheet, sidebar, skeleton, sonner, spinner, switch, table, textarea, tooltip |
23
23
  | `@tristan2828/ui-foundation/gateway` | `safeFetch`, `toAppError`, `networkError` — for an app's `src/api/gateway/` only |
24
24
  | `@tristan2828/ui-foundation/mocks` | MSW: `authHandlers`, `environmentHandlers`, `resetMockAuth`, `getMockCurrentUser`, `MOCK_USER`, `exposeMswForE2E` |
@@ -4,27 +4,27 @@
4
4
  ## Index
5
5
 
6
6
  - [The reference files](#the-reference-files) · lines 43–65
7
- - [Before anything: the entity plan](#before-anything-the-entity-plan) · lines 67–812
7
+ - [Before anything: the entity plan](#before-anything-the-entity-plan) · lines 67–826
8
8
  - Step 1: Add `<Entity>` to `openapi.yaml` · lines 109–116
9
9
  - Step 2: `npm run gen:api` · lines 117–118
10
10
  - Step 3: Add gateway tests in `tests/gateway/<entity>.test.ts`, derived from the spec · lines 119–130
11
11
  - Step 4: Add MSW handlers in `src/mocks/<entity>.ts` · lines 131–140
12
12
  - Step 5: Add a gateway module in `src/api/gateway/<entity>.ts` · lines 141–145
13
- - Step 6: Copy the reference files, one for one, not just the two screens · lines 146–699
14
- - Step 7: Register routes · lines 700–715
15
- - Step 8: Add Playwright specs for all three screens · lines 716–794
16
- - Step 9: Register the nav entry and route names · lines 795–809
17
- - Step 10: `npm run verify`. · lines 810–812
18
- - [How a list opens a record](#how-a-list-opens-a-record) · lines 814–1072
19
- - [The record view](#the-record-view) · lines 963–1002
20
- - [Forms](#forms) · lines 1004–1045
21
- - [Dialogs](#dialogs) · lines 1047–1072
22
- - [What not to copy](#what-not-to-copy) · lines 1074–1100
23
- - [After a commit, in the backend](#after-a-commit-in-the-backend) · lines 1102–1119
24
- - [Deleting](#deleting) · lines 1121–1150
25
- - [Fields only a script writes](#fields-only-a-script-writes) · lines 1152–1173
26
- - [Searching one part of the app](#searching-one-part-of-the-app) · lines 1175–1184
27
- - [What a chat is told about an entity](#what-a-chat-is-told-about-an-entity) · lines 1187–1226
13
+ - Step 6: Copy the reference files, one for one, not just the two screens · lines 146–713
14
+ - Step 7: Register routes · lines 714–729
15
+ - Step 8: Add Playwright specs for all three screens · lines 730–808
16
+ - Step 9: Register the nav entry and route names · lines 809–823
17
+ - Step 10: `npm run verify`. · lines 824–826
18
+ - [How a list opens a record](#how-a-list-opens-a-record) · lines 828–1086
19
+ - [The record view](#the-record-view) · lines 977–1016
20
+ - [Forms](#forms) · lines 1018–1059
21
+ - [Dialogs](#dialogs) · lines 1061–1086
22
+ - [What not to copy](#what-not-to-copy) · lines 1088–1114
23
+ - [After a commit, in the backend](#after-a-commit-in-the-backend) · lines 1116–1133
24
+ - [Deleting](#deleting) · lines 1135–1164
25
+ - [Fields only a script writes](#fields-only-a-script-writes) · lines 1166–1187
26
+ - [Searching one part of the app](#searching-one-part-of-the-app) · lines 1189–1198
27
+ - [What a chat is told about an entity](#what-a-chat-is-told-about-an-entity) · lines 1201–1240
28
28
 
29
29
  <!-- /index -->
30
30
 
@@ -426,6 +426,20 @@ is a filled-in example while the Widgets demo is still here).
426
426
  in `actions`, Delete as an `IconAction` (`icon={Trash2Icon}
427
427
  label="Delete" tone="destructive"`, the dialog's trigger through
428
428
  `render`).
429
+ - **The way back is a trail.** `back={{ to: '/widgets', label:
430
+ 'Widgets', trail: [{ label: 'Inventory', href: '/inventory' }, {
431
+ label: 'Widgets', href: '/widgets' }] }}`: the crumbs above the
432
+ record, from the module down to its list; the record's title follows
433
+ them. In `AppShell` it is the trail in the bar ("The sidebar and the
434
+ phone's bar" in design-language.md), and the page has no back link;
435
+ on a phone the header's back arrow goes to the list. Without `trail`
436
+ the view keeps its "← Widgets" link. `to` and `label` are still the
437
+ not-found state's way out. Any other page below a nav entry (a
438
+ record's sub-page, a step of a task) names its trail with
439
+ `usePageTrail([...crumbs, { label: 'This page' }])` in place of a
440
+ back link. Once the record has loaded, call
441
+ `useRecentRecord({ title, to: `/widgets/${id}`, detail: 'Widget' })`
442
+ too, so search lists it before you type.
429
443
  - **The browser tab** reads the record's title once it loads
430
444
  ("Wireless Mouse · <app>"): `EntityView` sets it from `title`, and
431
445
  puts the nav's ("Widgets · <app>") back while loading, on an error
@@ -33,7 +33,7 @@
33
33
  - [Picking at random](#picking-at-random) · lines 1357–1388
34
34
  - [Filling in what's missing](#filling-in-whats-missing) · lines 1390–1457
35
35
  - [Values edited in place: the presets' looks](#values-edited-in-place-the-presets-looks) · lines 1459–1484
36
- - [The sidebar and the phone's bar](#the-sidebar-and-the-phones-bar) · lines 1486–1532
36
+ - [The sidebar and the phone's bar](#the-sidebar-and-the-phones-bar) · lines 1486–1559
37
37
 
38
38
  <!-- /index -->
39
39
 
@@ -1486,8 +1486,10 @@ both themes and every palette.
1486
1486
  ## The sidebar and the phone's bar
1487
1487
 
1488
1488
  `AppShell`'s navigation (4.80), all set in the app's `nav` and
1489
- `bottomBar`; an app that sets none of it looks as it did, except the
1490
- current entry's bar and the phone's back arrow, which every app gets.
1489
+ `bottomBar`, and (4.87) the trail and search in the bar; an app that
1490
+ sets none of it looks as it did, except the current entry's bar, the
1491
+ phone's back arrow and the nav entry's name in the bar, which every app
1492
+ gets.
1491
1493
 
1492
1494
  ```tsx
1493
1495
  const nav: NavEntry[] = [
@@ -1530,3 +1532,28 @@ const bottomBar: BottomBarItem[] = [
1530
1532
  one tile per entry, the icon in `--link` over the label, bordered,
1531
1533
  44px tall at least; the tile holding the page has a `--primary`
1532
1534
  border. The entries' own pages are left to the module.
1535
+ - **The trail in the bar** (`usePageTrail`, `EntityView`'s
1536
+ `back.trail`): between the menu button and the search box, from 48rem
1537
+ up, `PageTrail` at 14px: every crumb but the last a
1538
+ link in the muted text tone, the page itself in the foreground, a `›`
1539
+ between them, the middle folded into "…" when it doesn't fit. A page
1540
+ that names none shows its nav entry's ("Finance › Accounts" for one of
1541
+ Finance's pages, "Home" on the hub). On a phone the trail is hidden and
1542
+ the back arrow goes to its closest crumb above the page that links.
1543
+ It replaces a page's own back link; the bar sits outside `<main>`, so
1544
+ the page's links are still the only ones in it.
1545
+ - **Search in the bar** (`search={{ placeholder, findRecords, recent }}`):
1546
+ a box from 48rem up, 14rem wide (16rem from 64rem), bordered in
1547
+ `--input` on the page's background, the placeholder in the muted
1548
+ tone and the shortcut (Ctrl K, ⌘K on a Mac) in a `kbd` at its end; a
1549
+ search button on a phone. Both, and the shortcut, open a palette: a
1550
+ dialog 32rem wide at 12% from the top, the field over a list of
1551
+ options under caption headings in the muted tone. Before typing:
1552
+ Recent (the records opened lately on this device, `useRecentRecord`),
1553
+ then the nav's first pages. Typing: Pages (a module's own named
1554
+ "Finance · Accounts", the closest name first), then the app's records
1555
+ under their `kind`, a `detail` in the caption size at the end. The
1556
+ highlighted option has `bg-muted`, its detail in the foreground; a
1557
+ spinner while records are found, "Couldn't search records" (the pages
1558
+ still listed) when the search fails, "Nothing found for …" when
1559
+ nothing matches.
@@ -135,6 +135,30 @@ export declare function navBackTarget(nav: readonly NavEntry[], pathname: string
135
135
  label: string;
136
136
  to: string;
137
137
  } | undefined;
138
+ /**
139
+ * The bar's trail for a page that names none of its own (#N5): the active
140
+ * entry, after the entry it sits under when it's one of a module's own
141
+ * pages ("Finance / Accounts"). The entry is the trail's last crumb even
142
+ * on a page below it. Nothing on a page no entry covers.
143
+ */
144
+ export declare function navTrail(nav: readonly NavEntry[], pathname: string): {
145
+ label: string;
146
+ href?: string;
147
+ }[];
148
+ /**
149
+ * Where a phone's back arrow goes once a page has put up a trail of its
150
+ * own (`usePageTrail`): the closest crumb above the page that links
151
+ * somewhere, on a page below a nav entry (or one no entry covers), and
152
+ * otherwise the entry (`navBackTarget`). An entry's own page keeps the
153
+ * menu button, whatever its trail.
154
+ */
155
+ export declare function trailBackTarget(nav: readonly NavEntry[], pathname: string, trail: readonly {
156
+ label: string;
157
+ href?: string;
158
+ }[] | null): {
159
+ label: string;
160
+ to: string;
161
+ } | undefined;
138
162
  /**
139
163
  * One item of `AppShell`'s `bottomBar`, the phone's bar of shortcuts: a
140
164
  * page, or one of the nav's sections by its label, which opens a sheet of
@@ -133,6 +133,36 @@ export function navBackTarget(nav, pathname) {
133
133
  const trimmed = pathname.length > 1 ? pathname.replace(/\/+$/, '') : pathname;
134
134
  return trimmed === path ? undefined : { label: item.label, to: item.to };
135
135
  }
136
+ /**
137
+ * The bar's trail for a page that names none of its own (#N5): the active
138
+ * entry, after the entry it sits under when it's one of a module's own
139
+ * pages ("Finance / Accounts"). The entry is the trail's last crumb even
140
+ * on a page below it. Nothing on a page no entry covers.
141
+ */
142
+ export function navTrail(nav, pathname) {
143
+ const item = activeNavItem(nav, pathname);
144
+ if (!item)
145
+ return [];
146
+ const parent = navItems(nav).find((other) => childItems(other).includes(item));
147
+ return parent ? [{ label: parent.label, href: parent.to }, { label: item.label }] : [{ label: item.label }];
148
+ }
149
+ /**
150
+ * Where a phone's back arrow goes once a page has put up a trail of its
151
+ * own (`usePageTrail`): the closest crumb above the page that links
152
+ * somewhere, on a page below a nav entry (or one no entry covers), and
153
+ * otherwise the entry (`navBackTarget`). An entry's own page keeps the
154
+ * menu button, whatever its trail.
155
+ */
156
+ export function trailBackTarget(nav, pathname, trail) {
157
+ const fromNav = navBackTarget(nav, pathname);
158
+ if (!fromNav && activeNavItem(nav, pathname))
159
+ return undefined;
160
+ const above = trail
161
+ ?.slice(0, -1)
162
+ .reverse()
163
+ .find((crumb) => crumb.href);
164
+ return above?.href ? { label: above.label, to: above.href } : fromNav;
165
+ }
136
166
  /** The nav's section with this label, if there is one. */
137
167
  export function bottomBarSection(nav, label) {
138
168
  return nav.find((entry) => isNavSection(entry) && entry.label === label);
@@ -1,9 +1,11 @@
1
1
  import { type ReactNode } from 'react';
2
2
  import { type BottomBarItem, type NavEntry } from './app-shell-nav.js';
3
3
  import { type AppShellVersion } from './app-shell-version.js';
4
+ import { type AppShellSearch } from './search-palette.js';
4
5
  import type { IconComponent } from './icon-component.js';
5
6
  export type { BottomBarItem, NavChild, NavEntry, NavItem, NavItemGroup, NavSection } from './app-shell-nav.js';
6
7
  export type { AppShellVersion } from './app-shell-version.js';
8
+ export type { AppShellSearch, RecentRecord, SearchRecord } from './search-palette.js';
7
9
  export type AppShellProps = {
8
10
  /**
9
11
  * Shown at the top of the sidebar (hidden on the collapsed icon rail), and
@@ -70,5 +72,14 @@ export type AppShellProps = {
70
72
  * takes its place. The shell pads its content so nothing sits under the bar.
71
73
  */
72
74
  bottomBar?: readonly BottomBarItem[];
75
+ /**
76
+ * Search in the header (#N6): a box ("Search", or `placeholder`) from
77
+ * md up and a button on a phone, both opening a palette (Ctrl K, ⌘K on
78
+ * a Mac) that finds the nav's pages by name and, with `findRecords`,
79
+ * the app's records, listed under their kinds; Enter opens the one
80
+ * highlighted. Before you type it lists the records opened lately
81
+ * (`useRecentRecord`), `recent` of them. No search, no box.
82
+ */
83
+ search?: AppShellSearch;
73
84
  };
74
- export declare function AppShell({ title, logo: Logo, nav, sidebarExtra, defaultSidebarOpen, version, bottomBar, }: AppShellProps): import("react").JSX.Element;
85
+ export declare function AppShell({ title, logo: Logo, nav, sidebarExtra, defaultSidebarOpen, version, bottomBar, search, }: AppShellProps): import("react").JSX.Element;
@@ -1,18 +1,22 @@
1
1
  import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { ChevronLeftIcon, ChevronRightIcon, LogOutIcon, MoonIcon, PaletteIcon, Rows3Icon, SunIcon } from 'lucide-react';
3
3
  import { useTheme } from 'next-themes';
4
- import { useEffect, useId, useState } from 'react';
4
+ import { useCallback, useEffect, useId, useMemo, useState } from 'react';
5
5
  import { Link, Navigate, Outlet, useLocation } from 'react-router';
6
6
  import { useAuth } from '../../auth/use-auth.js';
7
7
  import { BottomBar, BOTTOM_BAR_PADDING } from './app-shell-bottom-bar.js';
8
- import { activeNavTo, childItems, childrenOpen, isNavItemGroup, navBackTarget, navGroups, navPageLabel, navTooltip, withChildren, } from './app-shell-nav.js';
8
+ import { activeNavTo, childItems, childrenOpen, isNavItemGroup, navGroups, navPageLabel, navTooltip, navTrail, trailBackTarget, withChildren, } from './app-shell-nav.js';
9
9
  import { versionHref, versionLabel } from './app-shell-version.js';
10
10
  import { ErrorState } from './error-state.js';
11
+ import { PageTrail } from './page-trail.js';
12
+ import { PageTrailContext } from './page-trail-context.js';
13
+ import { SearchPalette } from './search-palette.js';
11
14
  import { useErrorReporter } from '../../error-reporting/error-reporting-context.js';
12
15
  import { ReportRoutePattern } from '../../error-reporting/error-reporting-provider.js';
13
16
  import { useShellDocumentTitle } from '../../hooks/use-document-title.js';
14
17
  import { usePalette } from '../../hooks/use-palette.js';
15
18
  import { useRows } from '../../hooks/use-rows.js';
19
+ import { clearRecentRecords } from '../../lib/search-palette.js';
16
20
  import { isPaletteName, PALETTE_LABELS, PALETTES } from '../../lib/palettes.js';
17
21
  import { isRowsName, ROWS, ROWS_LABELS } from '../../lib/rows.js';
18
22
  import { cn } from 'cn';
@@ -185,7 +189,7 @@ function PhoneBack({ back }) {
185
189
  function AppShellSkeleton() {
186
190
  return (_jsxs("div", { className: "flex h-screen w-full gap-4 p-4", "data-state": "loading", children: [_jsx(Skeleton, { className: "h-full w-56 shrink-0" }), _jsxs("div", { className: "flex-1 space-y-4 pt-2", children: [_jsx(Skeleton, { className: "h-8 w-64" }), _jsx(Skeleton, { className: "h-40 w-full" })] })] }));
187
191
  }
188
- export function AppShell({ title, logo: Logo, nav, sidebarExtra, defaultSidebarOpen = true, version, bottomBar, }) {
192
+ export function AppShell({ title, logo: Logo, nav, sidebarExtra, defaultSidebarOpen = true, version, bottomBar, search, }) {
189
193
  const { user, status, error, retry, logout } = useAuth();
190
194
  const location = useLocation();
191
195
  const reporter = useErrorReporter();
@@ -195,6 +199,11 @@ export function AppShell({ title, logo: Logo, nav, sidebarExtra, defaultSidebarO
195
199
  // component then renders starts a second navigation that wins.
196
200
  const [isLoggingOut, setIsLoggingOut] = useState(false);
197
201
  useShellDocumentTitle(title, navPageLabel(nav, location.pathname));
202
+ // The trail a page put up (usePageTrail, #N5), for the bar.
203
+ const [pageTrail, setPageTrail] = useState(null);
204
+ const set = useCallback((owner, crumbs) => setPageTrail({ owner, crumbs }), []);
205
+ const clear = useCallback((owner) => setPageTrail((current) => (current?.owner === owner ? null : current)), []);
206
+ const trailSlot = useMemo(() => ({ set, clear }), [set, clear]);
198
207
  if (status === 'loading') {
199
208
  return _jsx(AppShellSkeleton, {});
200
209
  }
@@ -215,14 +224,19 @@ export function AppShell({ title, logo: Logo, nav, sidebarExtra, defaultSidebarO
215
224
  return _jsx(Navigate, { to: "/login", replace: true, state: isLoggingOut ? undefined : { from } });
216
225
  }
217
226
  const activeTo = activeNavTo(nav, location.pathname);
218
- const back = navBackTarget(nav, location.pathname);
227
+ const ownTrail = pageTrail?.crumbs ?? null;
228
+ const back = trailBackTarget(nav, location.pathname, ownTrail);
229
+ const trail = ownTrail ?? navTrail(nav, location.pathname);
219
230
  const groups = navGroups(nav);
220
231
  const renderGroup = (group, groupIndex) => group.collapsible && group.label !== undefined ? (_jsx(CollapsibleNavGroup, { group: { ...group, label: group.label }, activeTo: activeTo }, `${group.placement ?? 'top'}:${groupIndex}:${group.label}`)) : (_jsxs(SidebarGroup, { children: [group.label !== undefined && _jsx(SidebarGroupLabel, { children: group.label }), _jsx(SidebarGroupContent, { children: _jsx(NavMenu, { items: group.items, activeTo: activeTo }) })] }, `${group.placement ?? 'top'}:${groupIndex}:${group.label ?? ''}`));
221
232
  return (_jsxs(TooltipProvider, { children: [reporter && _jsx(ReportRoutePattern, { reporter: reporter }), _jsxs(SidebarProvider, { defaultOpen: storedSidebarOpen(defaultSidebarOpen), children: [_jsx(CloseMobileSidebarOnNavigate, {}), _jsx("nav", { "aria-label": "Primary", children: _jsxs(Sidebar, { collapsible: "icon", children: [_jsx(SidebarHeader, { children: _jsxs("div", { className: "flex items-center gap-2 px-2 group-data-[collapsible=icon]:justify-center group-data-[collapsible=icon]:px-0", children: [Logo && (_jsx(Logo, { "aria-hidden": "true", className: "size-5 shrink-0 text-sidebar-foreground group-data-[collapsible=icon]:size-4" })), _jsx("span", { className: "truncate text-sm font-semibold text-sidebar-foreground group-data-[collapsible=icon]:hidden", children: title })] }) }), _jsxs(SidebarContent, { children: [groups.filter((group) => !group.placement).map(renderGroup), sidebarExtra, groups.some((group) => group.placement) && (_jsx("div", { "data-slot": "nav-foot", className: "mt-auto flex flex-col", children: groups.filter((group) => group.placement).map(renderGroup) }))] }), _jsxs(SidebarFooter, { children: [version && _jsx(VersionEntry, { version: version }), _jsxs("div", { className: "flex items-center justify-between gap-2 px-2 group-data-[collapsible=icon]:justify-center group-data-[collapsible=icon]:px-0", children: [_jsx("span", { className: "truncate type-caption text-sidebar-foreground/70 group-data-[collapsible=icon]:hidden", children: user.name }), _jsx(Button, { variant: "ghost", size: "icon-sm", "aria-label": "Log out", onClick: () => {
222
233
  setIsLoggingOut(true);
234
+ // The records opened lately are this person's: the
235
+ // next to sign in on this device doesn't see them.
236
+ clearRecentRecords();
223
237
  // A failed request still ends the session on screen
224
238
  // (AuthProvider), so this stays a deliberate logout: a
225
239
  // clean /login, never the previous user's page as `from`.
226
240
  logout().catch(() => { });
227
- }, children: _jsx(LogOutIcon, {}) })] })] })] }) }), _jsxs(SidebarInset, { className: "min-w-0", children: [_jsxs("header", { className: "flex h-14 shrink-0 items-center gap-2 border-b border-border px-4", children: [back && _jsx(PhoneBack, { back: back }), _jsx(SidebarTrigger, { className: cn(back && bottomBar?.length && 'max-md:hidden') }), _jsx("div", { className: "flex-1" }), _jsx(LookControl, {})] }), _jsx("div", { className: cn('flex-1 p-6', bottomBar?.length && BOTTOM_BAR_PADDING), children: _jsx(Outlet, {}) })] }), bottomBar && bottomBar.length > 0 && _jsx(BottomBar, { items: bottomBar, nav: nav, activeTo: activeTo })] }), _jsx(Toaster, { position: "top-center" })] }));
241
+ }, children: _jsx(LogOutIcon, {}) })] })] })] }) }), _jsx(PageTrailContext.Provider, { value: trailSlot, children: _jsxs("div", { "data-slot": "app-shell-column", className: "flex w-full min-w-0 flex-1 flex-col bg-background", children: [_jsxs("header", { className: "flex h-14 shrink-0 items-center gap-2 border-b border-border px-4", children: [back && _jsx(PhoneBack, { back: back }), _jsx(SidebarTrigger, { className: cn(back && bottomBar?.length && 'max-md:hidden') }), _jsx("div", { "data-slot": "app-shell-trail", className: "min-w-0 flex-1", children: trail.length > 0 && _jsx(PageTrail, { crumbs: trail, "aria-label": "You are here", className: "max-md:hidden" }) }), search && _jsx(SearchPalette, { search: search, nav: nav }), _jsx(LookControl, {})] }), _jsx(SidebarInset, { className: "min-w-0", children: _jsx("div", { className: cn('flex-1 p-6', bottomBar?.length && BOTTOM_BAR_PADDING), children: _jsx(Outlet, {}) }) })] }) }), bottomBar && bottomBar.length > 0 && _jsx(BottomBar, { items: bottomBar, nav: nav, activeTo: activeTo })] }), _jsx(Toaster, { position: "top-center" })] }));
228
242
  }
@@ -1,6 +1,7 @@
1
1
  import { type ReactNode } from 'react';
2
2
  import type { AppError } from '../../api/contracts.js';
3
3
  import { type EditInPlace, type EditInPlaceList } from './edit-in-place.js';
4
+ import { type PageCrumb } from './page-trail.js';
4
5
  export type EntityViewField = {
5
6
  label: string;
6
7
  /**
@@ -199,10 +200,19 @@ export type EntityViewProps = {
199
200
  /** A `notfound` error (including another user's record) shows "Not found" and a way back, never a retry. */
200
201
  error?: AppError | null;
201
202
  onRetry?: () => void;
202
- /** The entity's list: a link above the title, and the not-found state's way out. */
203
+ /**
204
+ * The entity's list: a link above the title, and the not-found state's
205
+ * way out. With `trail` (#R2), the crumbs above the record, from the top
206
+ * down ("Finance", "Accounts"), the record's title follows them as the
207
+ * page's own crumb and the trail takes the link's place: in AppShell's
208
+ * bar (`usePageTrail`, #N5), or, outside the shell, above the title
209
+ * (PageTrail). A record in a dialog shows neither: the dialog's bar
210
+ * is its way back.
211
+ */
203
212
  back: {
204
213
  to: string;
205
214
  label: string;
215
+ trail?: readonly PageCrumb[];
206
216
  };
207
217
  };
208
218
  export declare function EntityView({ title, documentTitle, titleEdit, leading, subtitle, badges, actions, notice, strip, sections, footer, layout, mobileOrder, railLabel, railFields, emptyFields, emptyText, printLabel, printLook, isLoading, error, onRetry, back, }: EntityViewProps): import("react").JSX.Element;
@@ -96,10 +96,19 @@ import { EditableValue, LeaveGuard } from './editable-value.js';
96
96
  import { EmptyText } from './empty-value.js';
97
97
  import { EMPTY_DASH, isEmptyValue } from '../../lib/empty-value.js';
98
98
  import { useRecordDialog } from './record-dialog-context.js';
99
+ import { PageTrail } from './page-trail.js';
100
+ import { usePageTrail } from './page-trail-context.js';
99
101
  import { entityViewTabSlug } from '../../lib/entity-view-tab.js';
100
102
  // The view's empty text and whether fields cards fold their empty ones,
101
103
  // for every section without threading them through each layout.
102
104
  const EmptyContext = createContext({ text: EMPTY_DASH, fold: false });
105
+ // The record's trail (#R2): the crumbs above it, then its own title
106
+ // once it has loaded; the list's crumb is the last until then.
107
+ function recordTrail(back, title) {
108
+ if (!back.trail)
109
+ return null;
110
+ return title ? [...back.trail, { label: title }] : [...back.trail];
111
+ }
103
112
  function BackLink({ back }) {
104
113
  return (_jsxs(Link, { to: back.to, className: "inline-flex w-fit items-center gap-1 rounded-sm type-label text-muted-foreground outline-none hover:text-foreground focus-visible:ring-3 focus-visible:ring-ring/50", children: [_jsx(ArrowLeftIcon, { "aria-hidden": "true", className: "size-4" }), back.label] }));
105
114
  }
@@ -248,6 +257,10 @@ export function EntityView({ title, documentTitle, titleEdit, leading, subtitle,
248
257
  const dialog = useRecordDialog();
249
258
  const editing = useSyncExternalStore(store.subscribe, () => store.editing, () => store.editing);
250
259
  useDocumentTitle(isLoading || error || documentTitle === false ? undefined : (documentTitle ?? title));
260
+ const trail = recordTrail(back, isLoading || error ? undefined : (title ?? (documentTitle || undefined)));
261
+ // In the shell, the trail goes up in its bar; a dialog leaves the bar
262
+ // to the list under it.
263
+ const inShell = usePageTrail(dialog ? null : trail);
251
264
  if (error?.kind === 'notfound') {
252
265
  // A record that doesn't exist and one that belongs to another user are
253
266
  // the same plain 404, so this never says which. Retrying can't help.
@@ -281,7 +294,7 @@ export function EntityView({ title, documentTitle, titleEdit, leading, subtitle,
281
294
  const main = (_jsxs("div", { className: cn(RAIL_LAYOUT.main, railSections.length === 0 && RAIL_LAYOUT.mainAlone), children: [mainSections
282
295
  .filter((section) => !tabbed(section))
283
296
  .map((section) => (_jsx(ViewSection, { section: section }, section.title))), tabList] }));
284
- return (_jsx(EditInPlaceContext.Provider, { value: store, children: _jsx(EmptyContext.Provider, { value: { text: emptyText, fold: emptyFields === 'fold' }, children: _jsxs("div", { className: layout === 'rail' ? RAIL_LAYOUT.page : 'flex max-w-4xl flex-col gap-6', "data-state": "success", "data-layout": layout, children: [editing && _jsx(LeaveGuard, { store: store }), !dialog && _jsx(BackLink, { back: back }), _jsxs("header", { className: "flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between", children: [_jsxs("div", { className: "flex min-w-0 flex-1 items-start gap-3 sm:min-w-64 sm:gap-4", children: [leading && (_jsx("div", { "data-slot": "entity-view-leading", className: "flex shrink-0 items-center", children: leading })), _jsxs("div", { className: "flex min-w-0 flex-1 flex-col gap-2", children: [_jsxs("div", { "data-slot": "entity-view-title-line", className: "flex min-w-0 flex-wrap items-center gap-x-3 gap-y-2", children: [_jsx("h1", { id: dialog?.titleId, className: "min-w-0 max-w-full type-page-title break-words text-foreground", children: titleEdit ? (_jsx(EditableValue, { label: titleEdit.label, edit: titleEdit, layout: "inline", className: "w-full", children: title })) : (title) }), badges && (_jsx("div", { "data-slot": "entity-view-badges", className: "flex flex-wrap items-center gap-1.5", children: badges }))] }), subtitle && (_jsx("div", { "data-slot": "entity-view-subtitle", className: "type-body break-words text-muted-foreground", children: subtitle }))] })] }), (actions || printButton) && (_jsxs("div", { className: "flex min-w-0 flex-wrap items-center gap-2 sm:justify-end", children: [printButton, actions] }))] }), _jsx("div", { role: "status", "data-slot": "entity-view-notice", className: "empty:hidden", children: notice }), strip && _jsx("div", { "data-slot": "entity-view-strip", children: strip }), layout === 'rail' ? (_jsxs("div", { className: RAIL_LAYOUT.columns, children: [mobileOrder === 'main-first' && main, railSections.length > 0 && (_jsx(Rail, { label: railLabel ?? `${title ?? 'Record'} details`, sections: railSections, fields: railFields })), mobileOrder === 'rail-first' && main] })) : (_jsxs(_Fragment, { children: [sections
297
+ return (_jsx(EditInPlaceContext.Provider, { value: store, children: _jsx(EmptyContext.Provider, { value: { text: emptyText, fold: emptyFields === 'fold' }, children: _jsxs("div", { className: layout === 'rail' ? RAIL_LAYOUT.page : 'flex max-w-4xl flex-col gap-6', "data-state": "success", "data-layout": layout, children: [editing && _jsx(LeaveGuard, { store: store }), !dialog && !trail && _jsx(BackLink, { back: back }), !dialog && trail && !inShell && _jsx(PageTrail, { crumbs: trail }), _jsxs("header", { className: "flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between", children: [_jsxs("div", { className: "flex min-w-0 flex-1 items-start gap-3 sm:min-w-64 sm:gap-4", children: [leading && (_jsx("div", { "data-slot": "entity-view-leading", className: "flex shrink-0 items-center", children: leading })), _jsxs("div", { className: "flex min-w-0 flex-1 flex-col gap-2", children: [_jsxs("div", { "data-slot": "entity-view-title-line", className: "flex min-w-0 flex-wrap items-center gap-x-3 gap-y-2", children: [_jsx("h1", { id: dialog?.titleId, className: "min-w-0 max-w-full type-page-title break-words text-foreground", children: titleEdit ? (_jsx(EditableValue, { label: titleEdit.label, edit: titleEdit, layout: "inline", className: "w-full", children: title })) : (title) }), badges && (_jsx("div", { "data-slot": "entity-view-badges", className: "flex flex-wrap items-center gap-1.5", children: badges }))] }), subtitle && (_jsx("div", { "data-slot": "entity-view-subtitle", className: "type-body break-words text-muted-foreground", children: subtitle }))] })] }), (actions || printButton) && (_jsxs("div", { className: "flex min-w-0 flex-wrap items-center gap-2 sm:justify-end", children: [printButton, actions] }))] }), _jsx("div", { role: "status", "data-slot": "entity-view-notice", className: "empty:hidden", children: notice }), strip && _jsx("div", { "data-slot": "entity-view-strip", children: strip }), layout === 'rail' ? (_jsxs("div", { className: RAIL_LAYOUT.columns, children: [mobileOrder === 'main-first' && main, railSections.length > 0 && (_jsx(Rail, { label: railLabel ?? `${title ?? 'Record'} details`, sections: railSections, fields: railFields })), mobileOrder === 'rail-first' && main] })) : (_jsxs(_Fragment, { children: [sections
285
298
  .filter((section) => !tabbed(section))
286
299
  .map((section) => (_jsx(ViewSection, { section: section }, section.title))), tabList] })), footer && (_jsx("footer", { "data-slot": "entity-view-footer", className: "type-caption text-muted-foreground", children: footer }))] }) }) }));
287
300
  }
@@ -0,0 +1,18 @@
1
+ import type { PageCrumb } from './page-trail.js';
2
+ export type PageTrailSlot = {
3
+ /** Shows these crumbs in the bar, for the page holding `owner`. */
4
+ set: (owner: object, crumbs: readonly PageCrumb[]) => void;
5
+ /** Takes them down again, unless a later page has put up its own. */
6
+ clear: (owner: object) => void;
7
+ };
8
+ export declare const PageTrailContext: import("react").Context<PageTrailSlot | null>;
9
+ /**
10
+ * Puts this page's trail in AppShell's bar: from the top (a module, say)
11
+ * down to the page itself, last, every crumb but the last with an `href`.
12
+ * Nothing (`undefined` or `null`) leaves the bar to the nav entry's
13
+ * label. Returns whether there is a bar to show it, so a view outside
14
+ * the shell can draw the trail itself.
15
+ *
16
+ * usePageTrail([{ label: 'Finance', href: '/finance' }, { label: 'Accounts', href: '/finance/accounts' }, { label: 'Update balances' }])
17
+ */
18
+ export declare function usePageTrail(crumbs: readonly PageCrumb[] | null | undefined): boolean;
@@ -0,0 +1,28 @@
1
+ // The trail in AppShell's bar (#N5): a page names where it is with
2
+ // `usePageTrail`, and the shell draws it between the menu button and the
3
+ // search box. Pages that set none get their nav entry's (navTrail).
4
+ import { createContext, useContext, useLayoutEffect } from 'react';
5
+ export const PageTrailContext = createContext(null);
6
+ /**
7
+ * Puts this page's trail in AppShell's bar: from the top (a module, say)
8
+ * down to the page itself, last, every crumb but the last with an `href`.
9
+ * Nothing (`undefined` or `null`) leaves the bar to the nav entry's
10
+ * label. Returns whether there is a bar to show it, so a view outside
11
+ * the shell can draw the trail itself.
12
+ *
13
+ * usePageTrail([{ label: 'Finance', href: '/finance' }, { label: 'Accounts', href: '/finance/accounts' }, { label: 'Update balances' }])
14
+ */
15
+ export function usePageTrail(crumbs) {
16
+ const slot = useContext(PageTrailContext);
17
+ // By value, so a new array each render doesn't put the trail up again.
18
+ const key = crumbs ? JSON.stringify(crumbs.map((crumb) => [crumb.label, crumb.href ?? null])) : null;
19
+ useLayoutEffect(() => {
20
+ if (!slot || key === null)
21
+ return;
22
+ const owner = {};
23
+ const parsed = JSON.parse(key);
24
+ slot.set(owner, parsed.map(([label, href]) => (href === null ? { label } : { label, href })));
25
+ return () => slot.clear(owner);
26
+ }, [slot, key]);
27
+ return slot !== null;
28
+ }
@@ -9,7 +9,7 @@ export type PageTrailProps = {
9
9
  * From the top (the record, or the list it's in) down to the page
10
10
  * itself, last. Any number: one is just the page.
11
11
  */
12
- crumbs: PageCrumb[];
12
+ crumbs: readonly PageCrumb[];
13
13
  /** The trail's name for screen readers. Defaults to "Breadcrumb". */
14
14
  'aria-label'?: string;
15
15
  className?: string;
@@ -63,7 +63,7 @@ export function PageTrail({ crumbs, 'aria-label': ariaLabel, className }) {
63
63
  return;
64
64
  }
65
65
  if (index === last)
66
- items.push(_jsx(BreadcrumbItem, { className: "min-w-0", children: _jsx(BreadcrumbPage, { className: "block truncate", title: crumb.label, children: crumb.label }) }, "page"));
66
+ items.push(_jsx(BreadcrumbItem, { className: "min-w-0", children: _jsx(BreadcrumbPage, { className: "block truncate", title: crumb.label, role: undefined, "aria-disabled": undefined, children: crumb.label }) }, "page"));
67
67
  else
68
68
  items.push(_jsx(BreadcrumbItem, { className: index === 0 ? 'shrink-0' : 'min-w-0', children: _jsx(CrumbLink, { crumb: crumb, inRouter: inRouter }) }, `crumb-${index}`));
69
69
  });
@@ -0,0 +1,29 @@
1
+ import type { NavEntry } from './app-shell-nav.js';
2
+ import { type SearchRecord } from '../../lib/search-palette.js';
3
+ export type { RecentRecord, SearchRecord } from '../../lib/search-palette.js';
4
+ /** AppShell's `search`: what the box says and how it finds records. */
5
+ export type AppShellSearch = {
6
+ /** The box's words and the palette's field's name. Defaults to "Search". */
7
+ placeholder?: string;
8
+ /**
9
+ * Finds the app's records whose title has the text in it, from the
10
+ * app's own search endpoint through its gateway (TanStack Query's
11
+ * `queryClient.fetchQuery`, say). Called once typing pauses, never for
12
+ * text of only spaces; `signal` aborts when the text changes again.
13
+ * The results are listed under their `kind`, in the order given.
14
+ * Without it the palette finds pages only.
15
+ */
16
+ findRecords?: (query: string, options: {
17
+ signal: AbortSignal;
18
+ }) => Promise<readonly SearchRecord[]>;
19
+ /**
20
+ * How many of the records opened lately (useRecentRecord) to list
21
+ * before you type: 5 by default, `false` for none.
22
+ */
23
+ recent?: number | false;
24
+ };
25
+ /** The box (md and up) and the button (a phone) that open the palette, and the palette. */
26
+ export declare function SearchPalette({ search, nav }: {
27
+ search: AppShellSearch;
28
+ nav: readonly NavEntry[];
29
+ }): import("react").JSX.Element;
@@ -0,0 +1,160 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ // Search in AppShell's bar (#N6): a box in the header (a button on a
3
+ // phone) and Ctrl K (⌘K on a Mac) open a palette that finds a page or a
4
+ // record by name, and Enter opens it. Before you type it lists the
5
+ // records you opened lately (useRecentRecord), then the first pages.
6
+ //
7
+ // A combobox over a listbox in a dialog (WAI-ARIA's "combobox with
8
+ // listbox popup"): focus stays in the box, the arrows move the
9
+ // highlighted option (aria-activedescendant), Enter opens it, Esc
10
+ // closes. Hand-rolled because shadcn's Command needs cmdk, which isn't
11
+ // on the package's allowlist; the dialog is the foundation's own.
12
+ import { SearchIcon } from 'lucide-react';
13
+ import { useEffect, useId, useMemo, useRef, useState } from 'react';
14
+ import { useNavigate } from 'react-router';
15
+ import { cn } from 'cn';
16
+ import { useDebouncedValue } from '../../hooks/use-debounced-value.js';
17
+ import { groupRecords, matchPages, readRecentRecords, searchPages, } from '../../lib/search-palette.js';
18
+ import { Button } from '../ui/button.js';
19
+ import { Dialog, DialogContent, DialogDescription, DialogTitle } from '../ui/dialog.js';
20
+ import { Spinner } from '../ui/spinner.js';
21
+ // How long typing pauses before findRecords is asked.
22
+ const SEARCH_DELAY_MS = 150;
23
+ const PAGES_BEFORE_TYPING = 5;
24
+ const PAGES_MATCHED = 6;
25
+ function isMac() {
26
+ return typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent);
27
+ }
28
+ /** The box (md and up) and the button (a phone) that open the palette, and the palette. */
29
+ export function SearchPalette({ search, nav }) {
30
+ const [open, setOpen] = useState(false);
31
+ const placeholder = search.placeholder ?? 'Search';
32
+ const shortcut = isMac() ? '⌘K' : 'Ctrl K';
33
+ // Ctrl K or ⌘K from anywhere, unless something on the page (an
34
+ // editor's link shortcut) has already taken it.
35
+ useEffect(() => {
36
+ const onKeyDown = (event) => {
37
+ if (event.defaultPrevented || event.altKey || event.shiftKey)
38
+ return;
39
+ if (event.key.toLowerCase() !== 'k' || !(event.ctrlKey || event.metaKey))
40
+ return;
41
+ event.preventDefault();
42
+ setOpen((current) => !current);
43
+ };
44
+ window.addEventListener('keydown', onKeyDown);
45
+ return () => window.removeEventListener('keydown', onKeyDown);
46
+ }, []);
47
+ return (_jsxs(_Fragment, { children: [_jsxs("button", { type: "button", "data-slot": "app-shell-search", "aria-keyshortcuts": "Control+K Meta+K", "aria-haspopup": "dialog", onClick: () => setOpen(true), className: "hidden h-8 w-56 shrink-0 items-center gap-2 rounded-lg border border-input bg-background px-2.5 text-sm text-muted-foreground transition-colors outline-none hover:bg-muted hover:text-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 md:flex lg:w-64", children: [_jsx(SearchIcon, { "aria-hidden": "true", className: "size-4 shrink-0" }), _jsx("span", { className: "min-w-0 flex-1 truncate text-left", children: placeholder }), _jsx("kbd", { className: "shrink-0 rounded-sm border border-border px-1 font-mono text-xs text-muted-foreground", children: shortcut })] }), _jsx(Button, { variant: "ghost", size: "icon-sm", "data-slot": "app-shell-search-button", "aria-label": placeholder, "aria-haspopup": "dialog", className: "md:hidden", onClick: () => setOpen(true), children: _jsx(SearchIcon, {}) }), _jsx(Dialog, { open: open, onOpenChange: setOpen, children: open && _jsx(Palette, { search: search, nav: nav, placeholder: placeholder, onClose: () => setOpen(false) }) })] }));
48
+ }
49
+ function Palette({ search, nav, placeholder, onClose, }) {
50
+ const navigate = useNavigate();
51
+ const id = useId();
52
+ const listId = `${id}-list`;
53
+ const [query, setQuery] = useState('');
54
+ const [active, setActive] = useState(0);
55
+ const [found, setFound] = useState(null);
56
+ // Read once, as the palette opens: the record you just left is there.
57
+ const [recent] = useState(() => search.recent === false ? [] : readRecentRecords().slice(0, search.recent ?? 5));
58
+ const pages = useMemo(() => searchPages(nav), [nav]);
59
+ const text = query.trim();
60
+ const debounced = useDebouncedValue(text, SEARCH_DELAY_MS);
61
+ const findRecords = search.findRecords;
62
+ // The latest findRecords without re-asking when only its identity changes.
63
+ const findRef = useRef(findRecords);
64
+ useEffect(() => {
65
+ findRef.current = findRecords;
66
+ }, [findRecords]);
67
+ const canFind = findRecords !== undefined;
68
+ useEffect(() => {
69
+ const find = findRef.current;
70
+ if (!find || !debounced)
71
+ return;
72
+ const controller = new AbortController();
73
+ // Through a microtask, so the effect itself doesn't set state.
74
+ void Promise.resolve()
75
+ .then(() => {
76
+ if (!controller.signal.aborted)
77
+ setFound({ query: debounced, status: 'loading' });
78
+ return find(debounced, { signal: controller.signal });
79
+ })
80
+ .then((records) => {
81
+ if (!controller.signal.aborted)
82
+ setFound({ query: debounced, status: 'success', records });
83
+ }, () => {
84
+ if (!controller.signal.aborted)
85
+ setFound({ query: debounced, status: 'error' });
86
+ });
87
+ return () => controller.abort();
88
+ }, [debounced]);
89
+ // What the records part says for the text on screen: found, still
90
+ // looking (typing, or asked), or couldn't look.
91
+ const records = !canFind || !text ? null : found?.query === text ? found : { query: text, status: 'loading' };
92
+ const groups = [];
93
+ if (!text && recent.length > 0)
94
+ groups.push({
95
+ heading: 'Recent',
96
+ options: recent.map((record, index) => ({ id: `${id}-recent-${index}`, label: record.title, detail: record.detail, to: record.to })),
97
+ });
98
+ const matched = matchPages(pages, text, text ? PAGES_MATCHED : PAGES_BEFORE_TYPING);
99
+ if (matched.length > 0)
100
+ groups.push({
101
+ heading: 'Pages',
102
+ options: matched.map((page, index) => ({ id: `${id}-page-${index}`, label: page.label, to: page.to })),
103
+ });
104
+ if (records?.status === 'success')
105
+ groupRecords(records.records).forEach((group, groupIndex) => groups.push({
106
+ heading: group.kind,
107
+ options: group.records.map((record, index) => ({
108
+ id: `${id}-record-${groupIndex}-${index}`,
109
+ label: record.title,
110
+ detail: record.detail,
111
+ to: record.to,
112
+ })),
113
+ }));
114
+ const options = groups.flatMap((group) => group.options);
115
+ const activeIndex = options.length === 0 ? -1 : Math.min(active, options.length - 1);
116
+ const activeOption = activeIndex >= 0 ? options[activeIndex] : undefined;
117
+ useEffect(() => {
118
+ if (activeOption)
119
+ document.getElementById(activeOption.id)?.scrollIntoView({ block: 'nearest' });
120
+ }, [activeOption]);
121
+ const go = (option) => {
122
+ onClose();
123
+ void navigate(option.to);
124
+ };
125
+ const onKeyDown = (event) => {
126
+ if (options.length === 0)
127
+ return;
128
+ const move = (to) => {
129
+ event.preventDefault();
130
+ setActive((to + options.length) % options.length);
131
+ };
132
+ if (event.key === 'ArrowDown')
133
+ move(activeIndex + 1);
134
+ else if (event.key === 'ArrowUp')
135
+ move(activeIndex - 1);
136
+ else if (event.key === 'Home' && event.ctrlKey)
137
+ move(0);
138
+ else if (event.key === 'End' && event.ctrlKey)
139
+ move(options.length - 1);
140
+ else if (event.key === 'Enter' && activeOption) {
141
+ event.preventDefault();
142
+ go(activeOption);
143
+ }
144
+ };
145
+ const nothing = text && options.length === 0 && records?.status !== 'loading';
146
+ return (_jsxs(DialogContent, { showCloseButton: false, "data-slot": "search-palette", className: "top-[12vh] max-h-[76vh] translate-y-0 grid-rows-[auto_minmax(0,1fr)] gap-0 overflow-hidden p-0 sm:max-w-lg", children: [_jsx(DialogTitle, { className: "sr-only", children: placeholder }), _jsx(DialogDescription, { className: "sr-only", children: "Type a page or a record's name; the arrows move through what's found and Enter opens it." }), _jsxs("div", { className: "flex items-center gap-2 border-b border-border px-3", children: [_jsx(SearchIcon, { "aria-hidden": "true", className: "size-4 shrink-0 text-muted-foreground" }), _jsx("input", { role: "combobox", "aria-label": placeholder, "aria-expanded": options.length > 0, "aria-controls": listId, "aria-autocomplete": "list", "aria-activedescendant": activeOption?.id, autoComplete: "off", spellCheck: false, value: query, placeholder: "Go to a page or find a record\u2026", onChange: (event) => {
147
+ setQuery(event.target.value);
148
+ setActive(0);
149
+ }, onKeyDown: onKeyDown, className: "h-11 min-w-0 flex-1 bg-transparent text-base outline-none placeholder:text-muted-foreground md:text-sm" }), records?.status === 'loading' && _jsx(Spinner, { "aria-label": "Searching", className: "size-4 text-muted-foreground" })] }), _jsxs("div", { className: "min-h-0 overflow-y-auto p-1", children: [_jsx("div", { role: "listbox", id: listId, "aria-label": placeholder, children: groups.map((group, groupIndex) => (_jsxs("div", { role: "group", "aria-labelledby": `${id}-group-${groupIndex}`, children: [_jsx("div", { id: `${id}-group-${groupIndex}`, className: "px-2 pt-2 pb-1 type-caption text-muted-foreground", children: group.heading }), group.options.map((option) => {
150
+ const selected = option.id === activeOption?.id;
151
+ return (_jsxs("div", { id: option.id, role: "option", "aria-selected": selected, "data-slot": "search-palette-option",
152
+ // A pointer moving over an option highlights it; a
153
+ // click opens it, focus staying in the box.
154
+ onPointerMove: () => {
155
+ const index = options.indexOf(option);
156
+ if (index !== activeIndex)
157
+ setActive(index);
158
+ }, onMouseDown: (event) => event.preventDefault(), onClick: () => go(option), className: cn('flex min-h-9 cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-sm text-foreground', selected && 'bg-muted'), children: [_jsx("span", { className: "min-w-0 flex-1 truncate", children: option.label }), option.detail && (_jsx("span", { className: cn('shrink-0 type-caption', selected ? 'text-foreground' : 'text-muted-foreground'), children: option.detail }))] }, option.id));
159
+ })] }, `${groupIndex}:${group.heading}`))) }), records?.status === 'error' && (_jsx("p", { role: "status", className: "px-2 py-2 text-sm text-muted-foreground", children: "Couldn't search records. Pages are still listed; try again in a moment." })), nothing && (_jsxs("p", { role: "status", className: "px-2 py-6 text-center text-sm text-muted-foreground", children: ["Nothing found for \u201C", text, "\u201D."] })), !text && options.length === 0 && (_jsx("p", { className: "px-2 py-6 text-center text-sm text-muted-foreground", children: "Type to find a page or a record." }))] })] }));
160
+ }
@@ -0,0 +1,10 @@
1
+ import { type RecentRecord } from '../lib/search-palette.js';
2
+ /**
3
+ * Remembers a record as opened, on this device, for AppShell's search
4
+ * palette, which lists the last few before you type (#N6). Call it in a
5
+ * record's view once the record has loaded; pass nothing while it
6
+ * loads. Kept in localStorage (the latest 20), forgotten on logout.
7
+ *
8
+ * useRecentRecord(task && { title: task.title, to: `/tasks/${task.id}`, detail: 'Task' })
9
+ */
10
+ export declare function useRecentRecord(record: RecentRecord | null | undefined | false): void;
@@ -0,0 +1,20 @@
1
+ import { useEffect } from 'react';
2
+ import { rememberRecentRecord } from '../lib/search-palette.js';
3
+ /**
4
+ * Remembers a record as opened, on this device, for AppShell's search
5
+ * palette, which lists the last few before you type (#N6). Call it in a
6
+ * record's view once the record has loaded; pass nothing while it
7
+ * loads. Kept in localStorage (the latest 20), forgotten on logout.
8
+ *
9
+ * useRecentRecord(task && { title: task.title, to: `/tasks/${task.id}`, detail: 'Task' })
10
+ */
11
+ export function useRecentRecord(record) {
12
+ const title = record ? record.title : undefined;
13
+ const to = record ? record.to : undefined;
14
+ const detail = record ? record.detail : undefined;
15
+ useEffect(() => {
16
+ if (title === undefined || to === undefined || !title.trim())
17
+ return;
18
+ rememberRecentRecord({ title, to, detail });
19
+ }, [title, to, detail]);
20
+ }
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { AppShell, type AppShellProps, type AppShellVersion, type BottomBarItem, type NavEntry, type NavItem, type NavSection, } from './components/app/app-shell.js';
1
+ export { AppShell, type AppShellProps, type AppShellSearch, type RecentRecord, type SearchRecord, type AppShellVersion, type BottomBarItem, type NavEntry, type NavItem, type NavSection, } from './components/app/app-shell.js';
2
2
  export type { IconComponent } from './components/app/icon-component.js';
3
3
  export { Board, type BoardColumn, type BoardMoveTarget, type BoardProps } from './components/app/board.js';
4
4
  export { SpinWheel, type SpinWheelProps } from './components/app/spin-wheel.js';
@@ -37,6 +37,8 @@ export { InlineCreate, type InlineCreateProps } from './components/app/inline-cr
37
37
  export { FoundationProviders } from './components/app/foundation-providers.js';
38
38
  export { Markdown, type MarkdownProps } from './components/app/markdown.js';
39
39
  export { PageTrail, type PageCrumb, type PageTrailProps } from './components/app/page-trail.js';
40
+ export { usePageTrail } from './components/app/page-trail-context.js';
41
+ export { useRecentRecord } from './hooks/use-recent-record.js';
40
42
  export type { CreatePage, PageLinkInfo, PageLinkResolver } from './lib/page-link.js';
41
43
  export { countTasks, toggleTaskAt, type TaskCount } from './lib/markdown-tasks.js';
42
44
  export { NotesOutline, type NotesOutlineProps } from './components/app/notes-outline.js';
package/dist/index.js CHANGED
@@ -41,6 +41,8 @@ export { InlineCreate } from './components/app/inline-create.js';
41
41
  export { FoundationProviders } from './components/app/foundation-providers.js';
42
42
  export { Markdown } from './components/app/markdown.js';
43
43
  export { PageTrail } from './components/app/page-trail.js';
44
+ export { usePageTrail } from './components/app/page-trail-context.js';
45
+ export { useRecentRecord } from './hooks/use-recent-record.js';
44
46
  export { countTasks, toggleTaskAt } from './lib/markdown-tasks.js';
45
47
  export { NotesOutline } from './components/app/notes-outline.js';
46
48
  export { MockModeBanner } from './components/app/mock-mode-banner.js';
@@ -0,0 +1,50 @@
1
+ import { type NavEntry } from '../components/app/app-shell-nav.js';
2
+ /**
3
+ * One record the app's `findRecords` found: its title, the page it opens
4
+ * (`to`, through the router), the heading it's listed under (`kind`,
5
+ * "Exercises"; "Records" without one), and a grey word beside it
6
+ * (`detail`, the module it's in, say).
7
+ */
8
+ export type SearchRecord = {
9
+ title: string;
10
+ to: string;
11
+ kind?: string;
12
+ detail?: string;
13
+ };
14
+ /** A record opened lately (`useRecentRecord`), as the palette lists it before you type. */
15
+ export type RecentRecord = {
16
+ title: string;
17
+ to: string;
18
+ /** A grey word beside it, as a found record's `detail`. */
19
+ detail?: string;
20
+ };
21
+ /** A nav page as the palette lists it: "Finance · Accounts" for a module's own page. */
22
+ export type SearchPage = {
23
+ label: string;
24
+ name: string;
25
+ to: string;
26
+ };
27
+ /** Every page in the nav, each once, a module's own pages named with their module. */
28
+ export declare function searchPages(nav: readonly NavEntry[]): SearchPage[];
29
+ /**
30
+ * The pages whose name (or module and name) has the text in it, the
31
+ * closest first, then the nav's order; at most `limit`. No text: the
32
+ * first `limit` pages.
33
+ */
34
+ export declare function matchPages(pages: readonly SearchPage[], query: string, limit: number): SearchPage[];
35
+ /** The records under their kinds, each kind once, in the order its first record came. */
36
+ export declare function groupRecords(records: readonly SearchRecord[]): {
37
+ kind: string;
38
+ records: SearchRecord[];
39
+ }[];
40
+ export declare const RECENT_RECORDS_KEY = "ui-foundation:recent-records";
41
+ /** How many are kept; the palette shows its `recent` of them. */
42
+ export declare const RECENT_RECORDS_KEPT = 20;
43
+ type StorageLike = Pick<Storage, 'getItem' | 'setItem' | 'removeItem'>;
44
+ /** The records opened lately, the latest first. Nothing when storage is missing or holds something else. */
45
+ export declare function readRecentRecords(store?: StorageLike | null): RecentRecord[];
46
+ /** Puts a record first among the recent ones (once, by its `to`), keeping the latest RECENT_RECORDS_KEPT. */
47
+ export declare function rememberRecentRecord(record: RecentRecord, store?: StorageLike | null): void;
48
+ /** Forgets every recent record (AppShell does on logout, so the next person doesn't see them). */
49
+ export declare function clearRecentRecords(store?: StorageLike | null): void;
50
+ export {};
@@ -0,0 +1,119 @@
1
+ // The search palette's logic (src/components/app/search-palette.tsx,
2
+ // AppShell's `search`, #N6): the nav's pages filtered by name, the app's
3
+ // records grouped by kind, and the records opened lately, remembered on
4
+ // the device. Pure, apart from the storage the recent records are kept in.
5
+ import { childItems, isNavSection } from '../components/app/app-shell-nav.js';
6
+ /** Every page in the nav, each once, a module's own pages named with their module. */
7
+ export function searchPages(nav) {
8
+ const seen = new Set();
9
+ const pages = [];
10
+ const add = (page) => {
11
+ if (seen.has(page.to))
12
+ return;
13
+ seen.add(page.to);
14
+ pages.push(page);
15
+ };
16
+ for (const entry of nav) {
17
+ for (const item of isNavSection(entry) ? entry.items : [entry]) {
18
+ add({ label: item.label, name: item.label, to: item.to });
19
+ for (const child of childItems(item))
20
+ add({ label: `${item.label} · ${child.label}`, name: child.label, to: child.to });
21
+ }
22
+ }
23
+ return pages;
24
+ }
25
+ // How close a name is to the text: the whole name, then a name starting
26
+ // with it, then a word starting with it, then anywhere. -1 is no match.
27
+ function closeness(name, text) {
28
+ const lower = name.toLowerCase();
29
+ if (lower === text)
30
+ return 0;
31
+ if (lower.startsWith(text))
32
+ return 1;
33
+ if (lower.split(/[\s·/-]+/).some((word) => word.startsWith(text)))
34
+ return 2;
35
+ return lower.includes(text) ? 3 : -1;
36
+ }
37
+ /**
38
+ * The pages whose name (or module and name) has the text in it, the
39
+ * closest first, then the nav's order; at most `limit`. No text: the
40
+ * first `limit` pages.
41
+ */
42
+ export function matchPages(pages, query, limit) {
43
+ const text = query.trim().toLowerCase();
44
+ if (!text)
45
+ return pages.slice(0, limit);
46
+ return pages
47
+ .map((page, index) => {
48
+ const own = closeness(page.name, text);
49
+ const full = closeness(page.label, text);
50
+ // The page's own name counts first; its module's name next.
51
+ const score = own >= 0 ? own : full >= 0 ? full + 4 : -1;
52
+ return { page, index, score };
53
+ })
54
+ .filter((match) => match.score >= 0)
55
+ .sort((a, b) => a.score - b.score || a.index - b.index)
56
+ .slice(0, limit)
57
+ .map((match) => match.page);
58
+ }
59
+ /** The records under their kinds, each kind once, in the order its first record came. */
60
+ export function groupRecords(records) {
61
+ const groups = new Map();
62
+ for (const record of records) {
63
+ const kind = record.kind?.trim() || 'Records';
64
+ const group = groups.get(kind);
65
+ if (group)
66
+ group.push(record);
67
+ else
68
+ groups.set(kind, [record]);
69
+ }
70
+ return [...groups].map(([kind, list]) => ({ kind, records: list }));
71
+ }
72
+ // ---- The records opened lately, on this device ----
73
+ export const RECENT_RECORDS_KEY = 'ui-foundation:recent-records';
74
+ /** How many are kept; the palette shows its `recent` of them. */
75
+ export const RECENT_RECORDS_KEPT = 20;
76
+ function storage() {
77
+ try {
78
+ return window.localStorage;
79
+ }
80
+ catch {
81
+ return null;
82
+ }
83
+ }
84
+ function isRecent(value) {
85
+ if (typeof value !== 'object' || value === null)
86
+ return false;
87
+ const { title, to, detail } = value;
88
+ return typeof title === 'string' && typeof to === 'string' && (detail === undefined || typeof detail === 'string');
89
+ }
90
+ /** The records opened lately, the latest first. Nothing when storage is missing or holds something else. */
91
+ export function readRecentRecords(store = storage()) {
92
+ try {
93
+ const parsed = JSON.parse(store?.getItem(RECENT_RECORDS_KEY) ?? '[]');
94
+ return Array.isArray(parsed) ? parsed.filter(isRecent) : [];
95
+ }
96
+ catch {
97
+ return [];
98
+ }
99
+ }
100
+ /** Puts a record first among the recent ones (once, by its `to`), keeping the latest RECENT_RECORDS_KEPT. */
101
+ export function rememberRecentRecord(record, store = storage()) {
102
+ const entry = { title: record.title, to: record.to, ...(record.detail ? { detail: record.detail } : {}) };
103
+ const next = [entry, ...readRecentRecords(store).filter((other) => other.to !== record.to)].slice(0, RECENT_RECORDS_KEPT);
104
+ try {
105
+ store?.setItem(RECENT_RECORDS_KEY, JSON.stringify(next));
106
+ }
107
+ catch {
108
+ // Not remembered: storage is full or refused (a private window).
109
+ }
110
+ }
111
+ /** Forgets every recent record (AppShell does on logout, so the next person doesn't see them). */
112
+ export function clearRecentRecords(store = storage()) {
113
+ try {
114
+ store?.removeItem(RECENT_RECORDS_KEY);
115
+ }
116
+ catch {
117
+ // Nothing to forget.
118
+ }
119
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tristan2828/ui-foundation",
3
- "version": "4.86.0",
3
+ "version": "4.87.0",
4
4
  "description": "Shared UI foundation for contract-first, database-backed React apps: shadcn primitives, DataTable/EntityForm composites, auth, the gateway error seam, design tokens, lint rules and the AI playbook.",
5
5
  "license": "MIT",
6
6
  "repository": {