@tristan2828/ui-foundation 4.149.0 → 4.151.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.
@@ -26,26 +26,26 @@
26
26
  - [A variant: a pressed icon inside another value's cell](#a-variant-a-pressed-icon-inside-another-values-cell) · lines 636–715
27
27
  - [16. Title linking to the record's view](#16-title-linking-to-the-records-view) · lines 717–758
28
28
  - [17. Quick action on the view](#17-quick-action-on-the-view) · lines 760–832
29
- - [18. Editable value](#18-editable-value) · lines 834–1627
29
+ - [18. Editable value](#18-editable-value) · lines 834–1643
30
30
  - [Presets: one line per field](#presets-one-line-per-field) · lines 1227–1299
31
31
  - [Several fields edited as one](#several-fields-edited-as-one) · lines 1301–1337
32
32
  - [A link and its label](#a-link-and-its-label) · lines 1339–1363
33
33
  - [A list of sub-items](#a-list-of-sub-items) · lines 1365–1498
34
- - [On a page of the app's own: `EditInPlaceScope`](#on-a-page-of-the-apps-own-editinplacescope) · lines 1500–1544
35
- - [In a table's rows](#in-a-tables-rows) · lines 1546–1620
36
- - [A table of a few short columns: `width="content"`](#a-table-of-a-few-short-columns-widthcontent) · lines 1622–1627
37
- - [19. Stage circle for an ordered status](#19-stage-circle-for-an-ordered-status) · lines 1629–1695
38
- - [20. Count linking to the related records](#20-count-linking-to-the-related-records) · lines 1697–1751
39
- - [21. Rows grouped under headings, and a pill filter](#21-rows-grouped-under-headings-and-a-pill-filter) · lines 1753–1835
40
- - [22. A highlighted row, and rows that are done](#22-a-highlighted-row-and-rows-that-are-done) · lines 1837–1862
41
- - [28. A list's rows: hover, lines, rows per page](#28-a-lists-rows-hover-lines-rows-per-page) · lines 1864–1897
42
- - [23. A Group menu, and a record read beside the list](#23-a-group-menu-and-a-record-read-beside-the-list) · lines 1899–1950
43
- - [24. A stored colour beside its name](#24-a-stored-colour-beside-its-name) · lines 1952–2026
44
- - [Picking one on a form: `ColorField`](#picking-one-on-a-form-colorfield) · lines 1972–2026
45
- - [25. A list's tools: views, filters, columns, row actions, a phone's rows](#25-a-lists-tools-views-filters-columns-row-actions-a-phones-rows) · lines 2028–2240
46
- - [The framed look, and sibling lists beside the title](#the-framed-look-and-sibling-lists-beside-the-title) · lines 2189–2240
47
- - [26. A record's related list, capped](#26-a-records-related-list-capped) · lines 2242–2276
48
- - [27. A repeat and its next time](#27-a-repeat-and-its-next-time) · lines 2278–2325
34
+ - [On a page of the app's own: `EditInPlaceScope`](#on-a-page-of-the-apps-own-editinplacescope) · lines 1500–1560
35
+ - [In a table's rows](#in-a-tables-rows) · lines 1562–1636
36
+ - [A table of a few short columns: `width="content"`](#a-table-of-a-few-short-columns-widthcontent) · lines 1638–1643
37
+ - [19. Stage circle for an ordered status](#19-stage-circle-for-an-ordered-status) · lines 1645–1711
38
+ - [20. Count linking to the related records](#20-count-linking-to-the-related-records) · lines 1713–1767
39
+ - [21. Rows grouped under headings, and a pill filter](#21-rows-grouped-under-headings-and-a-pill-filter) · lines 1769–1851
40
+ - [22. A highlighted row, and rows that are done](#22-a-highlighted-row-and-rows-that-are-done) · lines 1853–1878
41
+ - [28. A list's rows: hover, lines, rows per page](#28-a-lists-rows-hover-lines-rows-per-page) · lines 1880–1913
42
+ - [23. A Group menu, and a record read beside the list](#23-a-group-menu-and-a-record-read-beside-the-list) · lines 1915–1966
43
+ - [24. A stored colour beside its name](#24-a-stored-colour-beside-its-name) · lines 1968–2042
44
+ - [Picking one on a form: `ColorField`](#picking-one-on-a-form-colorfield) · lines 1988–2042
45
+ - [25. A list's tools: views, filters, columns, row actions, a phone's rows](#25-a-lists-tools-views-filters-columns-row-actions-a-phones-rows) · lines 2044–2256
46
+ - [The framed look, and sibling lists beside the title](#the-framed-look-and-sibling-lists-beside-the-title) · lines 2205–2256
47
+ - [26. A record's related list, capped](#26-a-records-related-list-capped) · lines 2258–2292
48
+ - [27. A repeat and its next time](#27-a-repeat-and-its-next-time) · lines 2294–2341
49
49
 
50
50
  <!-- /index -->
51
51
 
@@ -1531,16 +1531,32 @@ const body = editInPlace<string>({
1531
1531
  tabs are: one pane per open note, all mounted, only the one in front
1532
1532
  shown (the others `hidden`), so each keeps its caret and undo. A
1533
1533
  hidden value still saves, and the one leave guard covers them all.
1534
+ - **Tabs that are URLs** (`/notes/1`, `/notes/2`, the one in front
1535
+ being the route) pass `staysOnPage`, given the next location (and the
1536
+ current one), true for a move that only brings another of the scope's
1537
+ panes to the front:
1538
+ `staysOnPage={(next) => matchPath('/notes/:id', next.pathname) !== null}`.
1539
+ A move that stays is never held for a save and never asks, even with a
1540
+ refused save open: the text behind goes on saving itself. Without it,
1541
+ every move to another path is leaving the page. A move within the same
1542
+ path never is.
1534
1543
  - **A value that leaves the page mid-typing is still saved** (a tab
1535
1544
  closed, a pane unmounted): what was typed goes at once rather than
1536
- after the pause.
1545
+ after the pause, and a value whose save had been refused tries once
1546
+ more. If that save fails, nothing on screen holds the text any more,
1547
+ so a toast says "Couldn't save *label*" with the reason and stays until
1548
+ dismissed, with **Copy Text** to put what was typed on the clipboard.
1549
+ `onLostEdit`, given `{ label, value, reason }` (`LostEdit`), is for the
1550
+ app to do more, such as reopen the note's tab. A record's view and a
1551
+ table toast the same way.
1537
1552
  - **An app that opens on an editor** calls `preloadRichTextEditor()`
1538
1553
  as it starts (in `main.tsx`), so the editor's code is loading while
1539
1554
  the note is fetched, not after. It returns nothing, never throws, and
1540
1555
  is safe to call more than once; a failed load is the editor's to meet
1541
1556
  when one mounts.
1542
1557
 
1543
- The stories are `app/EditInPlaceScope` (one note, and two in one scope);
1558
+ The stories are `app/EditInPlaceScope` (one note, two in one scope, and
1559
+ the two as URL tabs with `staysOnPage`);
1544
1560
  `e2e/edit-in-place-scope.spec.ts` is the browser behaviour.
1545
1561
 
1546
1562
  ### In a table's rows
@@ -9,7 +9,7 @@ to the device, where the app's service worker shows it.
9
9
 
10
10
  | Part | Where | What it does |
11
11
  |---|---|---|
12
- | `pwa({ name })` | `vite.config.ts`, from `@tristan2828/ui-foundation/vite` | The app installable: a manifest, icons in the theme's colours, and `/push-sw.js`, the service worker that shows pushes and opens their path |
12
+ | `pwa({ name })` | `vite.config.ts`, from `@tristan2828/ui-foundation/vite` | The app installable: a manifest, icons in the theme's colours (or the app's own), and `/push-sw.js`, the service worker that shows pushes and opens their path |
13
13
  | `usePushPermission()` | the package | Whether this device gets reminders, and `enable`/`disable` |
14
14
  | `AllowReminders` | the package | The control: says what reminders are, then asks, on a click |
15
15
  | `/push/public-key`, `/push/subscriptions` | `openapi.yaml`, the foundation's part (optional) | The VAPID key to subscribe with; this device's subscription saved or dropped |
@@ -53,6 +53,38 @@ there is no push at all, so `usePushPermission` says `needs-install` and
53
53
  `AllowReminders` shows the steps. `pwa()`'s manifest (`display:
54
54
  standalone`) is what makes the Home Screen app an app.
55
55
 
56
+ ## The app's own icon
57
+
58
+ Without one, `pwa()` draws the icons: an SVG with the name's first letter,
59
+ and PNGs of the theme colour alone (a letter in a PNG needs a font
60
+ rasteriser the package doesn't carry). An app with its own mark passes it,
61
+ each a path from the Vite root:
62
+
63
+ ```ts
64
+ pwa({
65
+ name: 'Quick Jot',
66
+ icon: 'icons/icon-512.png', // a square PNG, 512×512 or more
67
+ smallIcon: 'icons/icon-192.png', // the same at 192×192
68
+ maskableIcon: 'icons/icon-maskable-512.png', // the mark inside the safe zone, background to the edges
69
+ iconSvg: 'icons/icon.svg', // the mark as an SVG
70
+ })
71
+ ```
72
+
73
+ | Option | In the manifest | Used for |
74
+ |---|---|---|
75
+ | `icon` (a PNG) | an `any` entry | iOS's Home Screen (the apple-touch-icon), a push's icon without `smallIcon`, and wherever nothing better fits |
76
+ | `smallIcon` (a PNG) | an `any` entry | Windows' Start menu and taskbar and the install prompt, which would scale the large one down; a push's icon |
77
+ | `maskableIcon` (a PNG) | the `maskable` entry | Android's Home Screen, cropped to the launcher's circle or squircle. Keep the mark inside the central 80% circle and the background to every edge. Without one, Android draws `icon` shrunk on a plain disc |
78
+ | `iconSvg` (an SVG) | an `any` entry with `sizes: "any"` | Chrome and Android, sharp at every size |
79
+
80
+ Each PNG's `sizes` is read from its own header, so a 1024×1024 `icon` is
81
+ named 1024x1024. The three beside `icon` need it (iOS takes a PNG only)
82
+ and are each optional: `icon` alone gives the manifest that one entry, as
83
+ before. `pwa()` can't resize a PNG (that needs a rasteriser, which isn't on
84
+ the allowlist), so export the 192 and maskable copies from the same artwork
85
+ in an image editor and commit the PNGs beside the large one. An SVG passed as `icon` is refused:
86
+ pass it as `iconSvg` beside a PNG.
87
+
56
88
  ## Home-screen shortcuts
57
89
 
58
90
  `pwa({ name, shortcuts: [{ name: 'Add To-Do', url: '/todo/add' }] })` writes
@@ -214,9 +214,10 @@ function CollapsibleNavGroup({ group, activeTo }) {
214
214
  }
215
215
  // The phone's back arrow, below the md breakpoint only: the
216
216
  // shell's own way up from a page below a nav entry. Its label is the
217
- // place it goes, so it reads "Back to Accounts".
217
+ // place it goes, so it reads "Back to Accounts". A finger's 44px tall on
218
+ // a touch screen, inside the 56px bar; a mouse keeps the 32px button.
218
219
  function PhoneBack({ back }) {
219
- return (_jsxs(Link, { to: back.to, "data-slot": "app-shell-back", "aria-label": `Back to ${back.label}`, className: cn(buttonVariants({ variant: 'ghost', size: 'sm' }), '-ml-2 max-w-[60vw] gap-0.5 px-1.5 text-link hover:text-link md:hidden'), children: [_jsx(ChevronLeftIcon, { "aria-hidden": "true" }), _jsx("span", { className: "truncate", children: back.label })] }));
220
+ return (_jsxs(Link, { to: back.to, "data-slot": "app-shell-back", "aria-label": `Back to ${back.label}`, className: cn(buttonVariants({ variant: 'ghost', size: 'sm' }), '-ml-2 max-w-[60vw] gap-0.5 px-1.5 text-link hover:text-link pointer-coarse:h-11 md:hidden'), children: [_jsx(ChevronLeftIcon, { "aria-hidden": "true" }), _jsx("span", { className: "truncate", children: back.label })] }));
220
221
  }
221
222
  function AppShellSkeleton() {
222
223
  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" })] })] }));
@@ -27,6 +27,7 @@ import { ToggleGroup, ToggleGroupItem } from '../ui/toggle-group.js';
27
27
  import { EditInPlaceContext } from './edit-in-place.js';
28
28
  import { EditInPlaceStore } from './edit-in-place-store.js';
29
29
  import { LeaveGuard } from './editable-value.js';
30
+ import { toastLostEdit } from './lost-edit-toast.js';
30
31
  import { recordDialogState } from './record-dialog-context.js';
31
32
  import { IconAction } from './icon-action.js';
32
33
  import { groupByValues, groupRuns } from './table-groups.js';
@@ -492,7 +493,7 @@ export function DataTable({ columns, data, total, page, pageSize, onPageChange,
492
493
  // a cell that renders an <EditableValue> edits where it's shown, one at
493
494
  // a time, with the leave-page prompt while one is open, the same rules
494
495
  // as a record's view.
495
- const [store] = useState(() => new EditInPlaceStore());
496
+ const [store] = useState(() => new EditInPlaceStore({ onLost: toastLostEdit }));
496
497
  const editing = useSyncExternalStore(store.subscribe, () => store.editing, () => store.editing);
497
498
  const pageCount = Math.max(1, Math.ceil(total / pageSize));
498
499
  // The columns showing: a view's while it's on, else the Columns menu's
@@ -1,5 +1,22 @@
1
1
  import { type ReactNode } from 'react';
2
+ import type { Location } from 'react-router';
3
+ import { type LostEdit } from './edit-in-place-store.js';
4
+ export type { LostEdit };
2
5
  export type EditInPlaceScopeProps = {
3
6
  children: ReactNode;
7
+ /**
8
+ * Whether a move to another path stays on this page: true for one that
9
+ * only brings another of the scope's own kept-mounted panes to the front
10
+ * (`(next) => matchPath('/notes/:id', next.pathname) !== null`). A move
11
+ * that stays is never blocked and saves nothing early. Without it, every
12
+ * move to another path is leaving the page.
13
+ */
14
+ staysOnPage?: (next: Location, current: Location) => boolean;
15
+ /**
16
+ * A value that left the page (unmounted) holding something that then
17
+ * couldn't be saved. The toast shows either way; this is for the app to
18
+ * do more with `value`, what was typed, such as reopen its record.
19
+ */
20
+ onLostEdit?: (lost: LostEdit) => void;
4
21
  };
5
- export declare function EditInPlaceScope({ children }: EditInPlaceScopeProps): import("react").JSX.Element;
22
+ export declare function EditInPlaceScope({ children, staysOnPage, onLostEdit }: EditInPlaceScopeProps): import("react").JSX.Element;
@@ -17,14 +17,23 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
17
17
  // React Router's blocker, and the router holds one blocker at a time. A
18
18
  // scope holds any number of always-editable values, such as a notes
19
19
  // app's open tabs kept mounted with only the one in front shown.
20
- import { useState, useSyncExternalStore } from 'react';
20
+ //
21
+ // When those tabs are URLs (/notes/1, /notes/2), `staysOnPage` says a move
22
+ // between them isn't leaving: it's never held for a save or asked about,
23
+ // and each tab's text goes on saving itself. A value taken off the page
24
+ // (a tab closed) still saves what it holds; if that save fails, a toast
25
+ // says so and offers the text (toastLostEdit), and `onLostEdit` lets the
26
+ // app do more, such as open the record again.
27
+ import { useEffect, useState, useSyncExternalStore } from 'react';
21
28
  import { EditInPlaceContext } from './edit-in-place.js';
22
29
  import { EditInPlaceStore } from './edit-in-place-store.js';
23
30
  import { LeaveGuard } from './editable-value.js';
24
- export function EditInPlaceScope({ children }) {
25
- const [store] = useState(() => new EditInPlaceStore());
31
+ import { toastLostEdit } from './lost-edit-toast.js';
32
+ export function EditInPlaceScope({ children, staysOnPage, onLostEdit }) {
33
+ const [store] = useState(() => new EditInPlaceStore({ onLost: toastLostEdit }));
34
+ useEffect(() => (onLostEdit ? store.subscribeLost(onLostEdit) : undefined), [store, onLostEdit]);
26
35
  // The leave-page prompt only while a value is open (or one is always
27
36
  // editable), so a page nobody's editing never blocks anything.
28
37
  const editing = useSyncExternalStore(store.subscribe, () => store.editing, () => store.editing);
29
- return (_jsxs(EditInPlaceContext.Provider, { value: store, children: [editing && _jsx(LeaveGuard, { store: store }), children] }));
38
+ return (_jsxs(EditInPlaceContext.Provider, { value: store, children: [editing && _jsx(LeaveGuard, { store: store, staysOnPage: staysOnPage }), children] }));
30
39
  }
@@ -40,6 +40,17 @@ export type EditFieldConfig = {
40
40
  * typed over theirs. Long text's default is `rebaseMarkdown`.
41
41
  */
42
42
  rebase?: ((base: unknown, mine: unknown, theirs: unknown) => unknown) | false;
43
+ /** The field's name as the person knows it ("Notes"), for `onLost`'s words. */
44
+ label?: string;
45
+ };
46
+ /** A field that left the view holding something that couldn't be saved (`onLost`). */
47
+ export type LostEdit = {
48
+ /** The field's label, or "your changes" when its config gives none. */
49
+ label: string;
50
+ /** What was typed: the draft that didn't save, as the control held it (long text's markdown). */
51
+ value: unknown;
52
+ /** Why it didn't save: the server's or the schema's words, a problem, or the conflict. */
53
+ reason: string;
43
54
  };
44
55
  export type EditFieldState = {
45
56
  status: 'closed';
@@ -81,6 +92,11 @@ export declare const AUTOSAVE_DELAY_MS = 1000;
81
92
  export type EditInPlaceStoreOptions = {
82
93
  /** The pause before an autosave, in ms. Defaults to AUTOSAVE_DELAY_MS. */
83
94
  autosaveDelay?: number;
95
+ /**
96
+ * A field left the view (unmounted) holding something unsaved that then
97
+ * couldn't be saved: nothing on screen says so any more, so this does.
98
+ */
99
+ onLost?: (lost: LostEdit) => void;
84
100
  };
85
101
  /** What a field shows when the saved value changed under unsaved typing. */
86
102
  export declare const CONFLICT_MESSAGE = "This changed elsewhere (another tab, device or chat) since you started typing. Saving now replaces that.";
@@ -107,7 +123,10 @@ export declare class EditInPlaceStore {
107
123
  private sent;
108
124
  private detached;
109
125
  private hurried;
126
+ private lostListeners;
110
127
  constructor(options?: EditInPlaceStoreOptions);
128
+ /** Called as `onLost` is, besides it, until the returned function is. */
129
+ subscribeLost: (listener: (lost: LostEdit) => void) => () => void;
111
130
  subscribe: (listener: () => void) => () => void;
112
131
  private emit;
113
132
  private set;
@@ -26,9 +26,12 @@
26
26
  // - A problem the control reports (rich text that can't round-trip) means
27
27
  // nothing is saved; it counts as unsaved at once (leaving asks), and its
28
28
  // message shows after the pause.
29
- // - A field leaving the view mid-save (unmounted) still sends what was
30
- // typed after that save started: the last draft and its config go with
31
- // the save waiting behind it (`register`'s cleanup).
29
+ // - A field leaving the view (unmounted) still sends what it holds
30
+ // unsaved: at once, or once a save in flight lands, from its last draft
31
+ // and config (`register`'s cleanup). If that can't save (refused, a
32
+ // problem, a conflict), nothing is left on screen to say so: the store's
33
+ // `onLost` gets the draft and the reason, so the person hears of it and
34
+ // can keep what they typed.
32
35
  // - The saved value changing elsewhere (another tab, a phone, an AI chat)
33
36
  // shows at once in a field with nothing of its own unsaved, even with the
34
37
  // caret in it (`refresh`). Under unsaved typing it's a conflict: nothing
@@ -109,9 +112,19 @@ export class EditInPlaceStore {
109
112
  detached = new Set();
110
113
  // The page is hidden: an autosave doesn't wait for the pause.
111
114
  hurried = false;
115
+ lostListeners = new Set();
112
116
  constructor(options = {}) {
113
117
  this.autosaveDelay = options.autosaveDelay ?? AUTOSAVE_DELAY_MS;
118
+ if (options.onLost)
119
+ this.lostListeners.add(options.onLost);
114
120
  }
121
+ /** Called as `onLost` is, besides it, until the returned function is. */
122
+ subscribeLost = (listener) => {
123
+ this.lostListeners.add(listener);
124
+ return () => {
125
+ this.lostListeners.delete(listener);
126
+ };
127
+ };
115
128
  subscribe = (listener) => {
116
129
  this.listeners.add(listener);
117
130
  return () => {
@@ -144,17 +157,12 @@ export class EditInPlaceStore {
144
157
  const inFlight = this.autosaving.get(key);
145
158
  const state = this.state(key);
146
159
  const last = this.configs.get(key)?.();
147
- // With a save in flight, what was typed since goes once it lands,
148
- // from this draft and config: the field is gone by then.
149
- if (inFlight) {
150
- this.clearTimer(key);
151
- if (state.status === 'open' && last)
152
- this.sendDetached(inFlight, state, last);
153
- }
154
- // A save still waiting for the pause goes now: the field is leaving,
155
- // not giving up what was typed.
156
- else if (this.timers.has(key))
157
- void this.flush(key);
160
+ // An autosaving field is leaving, not giving up what was typed: what
161
+ // it holds unsaved goes now, or once the save in flight lands, from
162
+ // this draft and config (the field is gone by then).
163
+ this.clearTimer(key);
164
+ if (state.status === 'open' && last && this.autosaves(key))
165
+ this.sendDetached(state, last, inFlight);
158
166
  this.configs.delete(key);
159
167
  this.states.delete(key);
160
168
  this.seen.delete(key);
@@ -165,20 +173,43 @@ export class EditInPlaceStore {
165
173
  this.emit();
166
174
  };
167
175
  }
168
- // A field that left mid-save: once its save in flight settles, its last
169
- // draft is sent if it's newer than what that save held.
170
- sendDetached(inFlight, state, config) {
176
+ // A field that left the view: what it holds unsaved is sent now, or,
177
+ // with a save in flight, once that settles if it's newer than what that
178
+ // save held. Whatever can't be saved goes to `onLost` with the reason:
179
+ // the field isn't there to show it.
180
+ sendDetached(state, config, inFlight) {
171
181
  const isEqual = config.isEqual ?? sameAsJson;
172
- const run = inFlight.promise
173
- .then((saved) => {
174
- if (state.problem || state.conflict || isEqual(state.draft, inFlight.draft))
175
- return saved;
182
+ const lose = (reason) => {
183
+ const lost = { label: config.label ?? 'your changes', value: state.draft, reason };
184
+ for (const listener of this.lostListeners)
185
+ listener(lost);
186
+ return false;
187
+ };
188
+ const send = () => {
189
+ if (state.problem)
190
+ return lose(state.problem);
191
+ if (state.conflict)
192
+ return lose(conflictMessage(config));
176
193
  const parsed = config.schema ? config.schema.safeParse(state.draft) : { success: true, data: state.draft };
177
194
  if (!parsed.success)
178
- return false;
179
- return config.save(parsed.data).then(() => true, () => false);
180
- })
181
- .finally(() => {
195
+ return lose(parsed.error.issues[0]?.message ?? 'Check this value.');
196
+ return config.save(parsed.data).then(() => true, (error) => lose(isConflict(error) ? conflictMessage(config) : messageOf(error)));
197
+ };
198
+ let pending;
199
+ if (inFlight) {
200
+ pending = inFlight.promise.then((saved) => {
201
+ if (!state.problem && isEqual(state.draft, inFlight.draft))
202
+ return saved || lose(inFlight.failure ?? 'The save failed.');
203
+ return send();
204
+ });
205
+ }
206
+ else {
207
+ // Nothing unsaved: nothing to send.
208
+ if (!state.problem && isEqual(state.draft, state.initial))
209
+ return;
210
+ pending = Promise.resolve(send());
211
+ }
212
+ const run = pending.finally(() => {
182
213
  this.detached.delete(run);
183
214
  this.emit();
184
215
  });
@@ -464,7 +495,8 @@ export class EditInPlaceStore {
464
495
  if (parsed.data !== sent)
465
496
  this.remember(key, parsed.data);
466
497
  this.set(key, { ...state, error: null, fieldErrors: undefined, autosave: 'saving' });
467
- const promise = config
498
+ const flight = { promise: Promise.resolve(true), draft: sent };
499
+ flight.promise = config
468
500
  .save(parsed.data)
469
501
  .then(() => {
470
502
  const now = this.state(key);
@@ -474,6 +506,7 @@ export class EditInPlaceStore {
474
506
  }
475
507
  return true;
476
508
  }, (error) => {
509
+ flight.failure = isConflict(error) ? conflictMessage(config) : messageOf(error);
477
510
  const now = this.state(key);
478
511
  if (now.status !== 'open')
479
512
  return false;
@@ -488,8 +521,8 @@ export class EditInPlaceStore {
488
521
  return false;
489
522
  })
490
523
  .finally(() => this.autosaving.delete(key));
491
- this.autosaving.set(key, { promise, draft: sent });
492
- return promise;
524
+ this.autosaving.set(key, flight);
525
+ return flight.promise;
493
526
  }
494
527
  /**
495
528
  * Saves every autosaving field that holds something unsaved, now
@@ -1,4 +1,5 @@
1
1
  import { type ReactNode } from 'react';
2
+ import { type Location } from 'react-router';
2
3
  import { type EditInPlace } from './edit-in-place.js';
3
4
  import type { EditInPlaceStore } from './edit-in-place-store.js';
4
5
  export type EditableValueProps = {
@@ -46,11 +47,16 @@ export declare function EditableField({ label, edit, children, layout, look, cla
46
47
  * and EditInPlaceScope only while a field is being edited, so a view
47
48
  * nobody's editing never blocks anything.
48
49
  *
50
+ * A move within the same path never counts, nor one `staysOnPage` says
51
+ * stays (a notes app's tabs, each its own URL, all kept mounted).
52
+ *
49
53
  * When everything unsaved autosaves, an in-app move saves it first and
50
54
  * goes on once saved, asking only if that save fails. Closing the tab
51
55
  * can't wait, so it starts the save and asks; hiding the page (another
52
56
  * tab, a phone's home screen) saves too.
53
57
  */
54
- export declare function LeaveGuard({ store }: {
58
+ export declare function LeaveGuard({ store, staysOnPage, }: {
55
59
  store: EditInPlaceStore;
60
+ /** A move to another path that stays on this page (EditInPlaceScope's `staysOnPage`): never blocked. */
61
+ staysOnPage?: (next: Location, current: Location) => boolean;
56
62
  }): import("react").JSX.Element;
@@ -184,7 +184,7 @@ export function EditableField({ label, edit, children, layout = 'block', look =
184
184
  const config = useRef({ ...edit, rebase: undefined });
185
185
  useLayoutEffect(() => {
186
186
  const rebase = edit.rebase === false ? undefined : (edit.rebase ?? (edit.kind === 'long-text' ? rebaseText : undefined));
187
- config.current = { ...edit, alwaysEditable: always || edit.alwaysEditable, rebase };
187
+ config.current = { ...edit, alwaysEditable: always || edit.alwaysEditable, rebase, label };
188
188
  });
189
189
  useEffect(() => store.register(key, () => config.current), [store, key]);
190
190
  const state = useSyncExternalStore(store.subscribe, () => store.state(key), () => store.state(key));
@@ -463,12 +463,15 @@ const sameAsJson = (a, b) => JSON.stringify(a) === JSON.stringify(b);
463
463
  * and EditInPlaceScope only while a field is being edited, so a view
464
464
  * nobody's editing never blocks anything.
465
465
  *
466
+ * A move within the same path never counts, nor one `staysOnPage` says
467
+ * stays (a notes app's tabs, each its own URL, all kept mounted).
468
+ *
466
469
  * When everything unsaved autosaves, an in-app move saves it first and
467
470
  * goes on once saved, asking only if that save fails. Closing the tab
468
471
  * can't wait, so it starts the save and asks; hiding the page (another
469
472
  * tab, a phone's home screen) saves too.
470
473
  */
471
- export function LeaveGuard({ store }) {
474
+ export function LeaveGuard({ store, staysOnPage, }) {
472
475
  const dirty = useSyncExternalStore(store.subscribe, () => store.dirty, () => store.dirty);
473
476
  const savesOnLeave = useSyncExternalStore(store.subscribe, () => store.savesOnLeave, () => store.savesOnLeave);
474
477
  // Typing a rich-text field holds back counts: the tab's prompt is
@@ -476,7 +479,9 @@ export function LeaveGuard({ store }) {
476
479
  const holding = useSyncExternalStore(subscribePendingEdits, hasPendingEdits, hasPendingEdits);
477
480
  const blocker = useBlocker(({ currentLocation, nextLocation }) => {
478
481
  flushPendingEdits();
479
- return store.dirty && currentLocation.pathname !== nextLocation.pathname;
482
+ if (!store.dirty || currentLocation.pathname === nextLocation.pathname)
483
+ return false;
484
+ return !staysOnPage?.(nextLocation, currentLocation);
480
485
  });
481
486
  const [saveFailed, setSaveFailed] = useState(false);
482
487
  const latestBlocker = useRef(blocker);
@@ -107,6 +107,7 @@ import { EditInPlaceStore } from './edit-in-place-store.js';
107
107
  import { EditableList } from './editable-list.js';
108
108
  import { editRowClass, onEditRowClick } from './edit-row.js';
109
109
  import { EditableField, EditableValue, LeaveGuard } from './editable-value.js';
110
+ import { toastLostEdit } from './lost-edit-toast.js';
110
111
  import { EmptyText } from './empty-value.js';
111
112
  import { EMPTY_DASH, isEmptyValue } from '../../lib/empty-value.js';
112
113
  import { useRecordDialog } from './record-dialog-context.js';
@@ -392,7 +393,7 @@ export function EntityView({ title, documentTitle, titleEdit, leading, subtitle,
392
393
  const sections = statusSectionFirst(givenSections);
393
394
  // Editing in place: one store per view, and the leave-page prompt only
394
395
  // while a field is open (or one is always editable).
395
- const [store] = useState(() => new EditInPlaceStore());
396
+ const [store] = useState(() => new EditInPlaceStore({ onLost: toastLostEdit }));
396
397
  // Opened over its list (RecordDialogRoute): the heading names the dialog,
397
398
  // and the dialog's own bar replaces the back link.
398
399
  const dialog = useRecordDialog();
@@ -0,0 +1,10 @@
1
+ import type { LostEdit } from './edit-in-place-store.js';
2
+ /**
3
+ * A field that left the page (unmounted: a closed tab, a collapsed
4
+ * section) and whose last save then failed: said in a toast that stays
5
+ * until it's dismissed, with the reason, and for text a "Copy Text" that
6
+ * puts what was typed on the clipboard, since nothing on screen holds it
7
+ * any more. Every store EntityView, DataTable and EditInPlaceScope make
8
+ * calls it (EditInPlaceStoreOptions' `onLost`).
9
+ */
10
+ export declare function toastLostEdit({ label, value, reason }: LostEdit): void;
@@ -0,0 +1,29 @@
1
+ import { toast } from 'sonner';
2
+ /**
3
+ * A field that left the page (unmounted: a closed tab, a collapsed
4
+ * section) and whose last save then failed: said in a toast that stays
5
+ * until it's dismissed, with the reason, and for text a "Copy Text" that
6
+ * puts what was typed on the clipboard, since nothing on screen holds it
7
+ * any more. Every store EntityView, DataTable and EditInPlaceScope make
8
+ * calls it (EditInPlaceStoreOptions' `onLost`).
9
+ */
10
+ export function toastLostEdit({ label, value, reason }) {
11
+ const text = typeof value === 'string' && value.trim() !== '' ? value : null;
12
+ const id = toast.error(`Couldn't save ${label}`, {
13
+ description: text ? `${reason} It's no longer on the page: copy what you typed to keep it.` : reason,
14
+ duration: Infinity,
15
+ action: text
16
+ ? {
17
+ label: 'Copy Text',
18
+ onClick: (event) => {
19
+ // The toast stays until the copy is done: it holds the only copy.
20
+ event.preventDefault();
21
+ void navigator.clipboard.writeText(text).then(() => {
22
+ toast.dismiss(id);
23
+ toast.success('Copied what you typed');
24
+ }, () => toast.error("Couldn't copy it", { description: 'The browser kept the clipboard closed. Copy Text tries again.' }));
25
+ },
26
+ }
27
+ : undefined,
28
+ });
29
+ }
package/dist/index.d.ts CHANGED
@@ -52,7 +52,7 @@ export { linkHost, linkHref, linkRule } from './lib/link-href.js';
52
52
  export { TITLE_CASE_SMALL_WORDS, titleCase } from './lib/title-case.js';
53
53
  export { DataEnvironmentBanner } from './components/app/data-environment-banner.js';
54
54
  export { EditableValue, type EditableValueProps } from './components/app/editable-value.js';
55
- export { EditInPlaceScope, type EditInPlaceScopeProps } from './components/app/edit-in-place-scope.js';
55
+ export { EditInPlaceScope, type EditInPlaceScopeProps, type LostEdit } from './components/app/edit-in-place-scope.js';
56
56
  export { editRowClass, onEditRowClick, SAVED_FOR_MS } from './components/app/edit-row.js';
57
57
  export { ErrorState } from './components/app/error-state.js';
58
58
  export { InlineCreate, type InlineCreateProps } from './components/app/inline-create.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tristan2828/ui-foundation",
3
- "version": "4.149.0",
3
+ "version": "4.151.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": {
package/vite/index.d.ts CHANGED
@@ -45,9 +45,32 @@ export type PwaOptions = {
45
45
  backgroundColor?: string
46
46
  /**
47
47
  * The app's own icon, a square PNG of at least 512×512 (path from the Vite
48
- * root). Replaces the generated ones everywhere.
48
+ * root). Replaces the generated ones everywhere: the manifest's `any`
49
+ * entry (its `sizes` read from the PNG), the apple-touch-icon and, without
50
+ * a `smallIcon`, a push's icon. Alone it is the manifest's only icon;
51
+ * the three below add the rest.
49
52
  */
50
53
  icon?: string
54
+ /**
55
+ * A smaller copy of `icon`, a square PNG of 192×192 (path from the Vite
56
+ * root): a second `any` entry, for the places that would scale the large
57
+ * one down (Windows, the install prompt), and a push's icon. Needs `icon`.
58
+ */
59
+ smallIcon?: string
60
+ /**
61
+ * The icon to crop to the device's mask shape (Android's circle or
62
+ * squircle), a square PNG of at least 512×512 (path from the Vite root)
63
+ * with the mark inside the central 80% circle and the background to the
64
+ * edges: the manifest's `maskable` entry. Without one, Android draws
65
+ * `icon` shrunk on a plain disc. Needs `icon`.
66
+ */
67
+ maskableIcon?: string
68
+ /**
69
+ * The app's mark as an SVG (path from the Vite root): an `any` entry
70
+ * with `sizes: 'any'`, which Chrome and Android draw sharp at every size.
71
+ * Needs `icon`, since iOS's Home Screen takes a PNG only.
72
+ */
73
+ iconSvg?: string
51
74
  /**
52
75
  * Home-screen shortcuts: actions offered when the installed icon is
53
76
  * long-pressed (Android, Chrome and Edge on desktop). Left out, the manifest
package/vite/pwa.d.ts CHANGED
@@ -5,6 +5,7 @@ import type { PwaOptions } from './index'
5
5
 
6
6
  export function themeToken(css: string, name: string): string
7
7
  export function oklchToHex(value: string): string
8
+ export function pngSize(bytes: Buffer): { width: number; height: number } | undefined
8
9
  export function solidPng(size: number, hex: string): Buffer
9
10
  export function letterSvg(name: string, background: string, foreground: string): string
10
11
  export function pwaFiles(
package/vite/pwa.js CHANGED
@@ -11,7 +11,9 @@
11
11
  // - /icons/: an SVG with the name's first letter (Chrome, Android) and
12
12
  // plain PNGs in the theme colour (iOS's Home Screen icon must be a PNG,
13
13
  // and drawing a letter into one needs a font rasteriser the package
14
- // doesn't carry). `icon` replaces them all with the app's own PNG.
14
+ // doesn't carry). `icon` replaces them all with the app's own PNG, and
15
+ // `smallIcon`, `maskableIcon` and `iconSvg` add its other sizes and
16
+ // shapes beside it; each PNG's `sizes` is read from its header.
15
17
  // - /push-sw.js: ./push-sw.js, showing pushes, opening their path, and
16
18
  // posting a message's action (a Done button) to the app's own path.
17
19
  // And adds the manifest, theme-color and apple-touch-icon tags to
@@ -150,6 +152,37 @@ export function letterSvg(name, background, foreground) {
150
152
  )
151
153
  }
152
154
 
155
+ // ---------------------------------------------------------- own icons
156
+
157
+ const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
158
+
159
+ /** A PNG's width and height, from its IHDR chunk; undefined if it isn't a PNG. */
160
+ export function pngSize(bytes) {
161
+ if (bytes.length < 24 || !bytes.subarray(0, 8).equals(PNG_SIGNATURE)) return undefined
162
+ if (bytes.toString('ascii', 12, 16) !== 'IHDR') return undefined
163
+ return { width: bytes.readUInt32BE(16), height: bytes.readUInt32BE(20) }
164
+ }
165
+
166
+ /** An app's own PNG (path from the Vite root), with the manifest's `sizes` read from it. */
167
+ function ownPng(file, option, root) {
168
+ const own = path.resolve(root, file)
169
+ if (own.toLowerCase().endsWith('.svg')) {
170
+ throw new Error(`pwa: ${option} must be a PNG file; an SVG goes in \`iconSvg\`, beside a PNG \`icon\` (iOS's Home Screen takes a PNG only).`)
171
+ }
172
+ const bytes = fs.existsSync(own) ? fs.readFileSync(own) : undefined
173
+ const size = bytes && pngSize(bytes)
174
+ if (!size) throw new Error(`pwa: ${option} must be a PNG file; ${own} isn't one.`)
175
+ return { bytes, sizes: `${size.width}x${size.height}` }
176
+ }
177
+
178
+ /** An app's own SVG (path from the Vite root). */
179
+ function ownSvg(file, option, root) {
180
+ const own = path.resolve(root, file)
181
+ const source = own.toLowerCase().endsWith('.svg') && fs.existsSync(own) ? fs.readFileSync(own, 'utf8') : undefined
182
+ if (!source || !/<svg[\s>]/.test(source)) throw new Error(`pwa: ${option} must be an SVG file; ${own} isn't one.`)
183
+ return source
184
+ }
185
+
153
186
  // --------------------------------------------------------------- plugin
154
187
 
155
188
  /**
@@ -169,13 +202,34 @@ export function pwaFiles(options, base = '/', root = process.cwd()) {
169
202
  const files = new Map()
170
203
  let icons
171
204
  let touchIcon
205
+ let workerIcon
172
206
  if (options.icon) {
173
- const own = path.resolve(root, options.icon)
174
- if (!own.endsWith('.png') || !fs.existsSync(own)) throw new Error(`pwa: icon must be a PNG file; ${own} isn't one.`)
175
- files.set('icons/icon.png', { type: 'image/png', source: fs.readFileSync(own) })
176
- icons = [{ src: at('icons/icon.png'), sizes: '512x512', type: 'image/png', purpose: 'any' }]
207
+ // The app's own: its PNG (the Home Screen's on iOS, the push's), and
208
+ // beside it any of a smaller PNG, a maskable PNG and an SVG it has.
209
+ const own = ownPng(options.icon, 'icon', root)
210
+ files.set('icons/icon.png', { type: 'image/png', source: own.bytes })
211
+ icons = [{ src: at('icons/icon.png'), sizes: own.sizes, type: 'image/png', purpose: 'any' }]
212
+ workerIcon = 'icons/icon.png'
213
+ if (options.smallIcon) {
214
+ const small = ownPng(options.smallIcon, 'smallIcon', root)
215
+ files.set('icons/icon-small.png', { type: 'image/png', source: small.bytes })
216
+ icons.unshift({ src: at('icons/icon-small.png'), sizes: small.sizes, type: 'image/png', purpose: 'any' })
217
+ workerIcon = 'icons/icon-small.png'
218
+ }
219
+ if (options.iconSvg) {
220
+ files.set('icons/icon.svg', { type: 'image/svg+xml', source: ownSvg(options.iconSvg, 'iconSvg', root) })
221
+ icons.unshift({ src: at('icons/icon.svg'), sizes: 'any', type: 'image/svg+xml', purpose: 'any' })
222
+ }
223
+ if (options.maskableIcon) {
224
+ const maskable = ownPng(options.maskableIcon, 'maskableIcon', root)
225
+ files.set('icons/icon-maskable.png', { type: 'image/png', source: maskable.bytes })
226
+ icons.push({ src: at('icons/icon-maskable.png'), sizes: maskable.sizes, type: 'image/png', purpose: 'maskable' })
227
+ }
177
228
  touchIcon = 'icons/icon.png'
178
229
  } else {
230
+ for (const option of ['iconSvg', 'smallIcon', 'maskableIcon']) {
231
+ if (options[option]) throw new Error(`pwa: \`${option}\` goes with \`icon\`, the app's own PNG; pass that too.`)
232
+ }
179
233
  files.set('icons/icon.svg', { type: 'image/svg+xml', source: letterSvg(shortName, theme, onTheme) })
180
234
  for (const size of [192, 512]) files.set(`icons/icon-${size}.png`, { type: 'image/png', source: solidPng(size, theme) })
181
235
  files.set('icons/apple-touch-icon.png', { type: 'image/png', source: solidPng(180, theme) })
@@ -187,6 +241,7 @@ export function pwaFiles(options, base = '/', root = process.cwd()) {
187
241
  { src: at('icons/icon-512.png'), sizes: '512x512', type: 'image/png', purpose: 'maskable' },
188
242
  ]
189
243
  touchIcon = 'icons/apple-touch-icon.png'
244
+ workerIcon = 'icons/icon-192.png'
190
245
  }
191
246
  const shortcuts = (options.shortcuts ?? []).map((shortcut, index) => {
192
247
  const label = shortcut?.name?.trim()
@@ -197,11 +252,10 @@ export function pwaFiles(options, base = '/', root = process.cwd()) {
197
252
  }
198
253
  let icon
199
254
  if (shortcut.icon) {
200
- const own = path.resolve(root, shortcut.icon)
201
- if (!own.endsWith('.png') || !fs.existsSync(own)) throw new Error(`pwa: shortcuts[${index}].icon must be a PNG file; ${own} isn't one.`)
255
+ const own = ownPng(shortcut.icon, `shortcuts[${index}].icon`, root)
202
256
  const file = `icons/shortcut-${index}.png`
203
- files.set(file, { type: 'image/png', source: fs.readFileSync(own) })
204
- icon = [{ src: at(file), sizes: '192x192', type: 'image/png' }]
257
+ files.set(file, { type: 'image/png', source: own.bytes })
258
+ icon = [{ src: at(file), sizes: own.sizes, type: 'image/png' }]
205
259
  }
206
260
  return {
207
261
  name: label,
@@ -226,7 +280,7 @@ export function pwaFiles(options, base = '/', root = process.cwd()) {
226
280
  type: 'application/manifest+json',
227
281
  source: `${JSON.stringify(manifest, null, 2)}\n`,
228
282
  })
229
- const worker = fs.readFileSync(WORKER_SOURCE, 'utf8').replace('__ICON__', options.icon ? at('icons/icon.png') : at('icons/icon-192.png'))
283
+ const worker = fs.readFileSync(WORKER_SOURCE, 'utf8').replace('__ICON__', at(workerIcon))
230
284
  files.set('push-sw.js', { type: 'text/javascript', source: worker })
231
285
  return {
232
286
  files,