@tristan2828/ui-foundation 4.148.0 → 4.150.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/conventions/docs/add-an-entity.md +73 -49
- package/conventions/docs/cell-patterns.md +34 -18
- package/dist/components/app/data-table.js +2 -1
- package/dist/components/app/edit-in-place-scope.d.ts +18 -1
- package/dist/components/app/edit-in-place-scope.js +13 -4
- package/dist/components/app/edit-in-place-store.d.ts +19 -0
- package/dist/components/app/edit-in-place-store.js +61 -28
- package/dist/components/app/editable-value.d.ts +7 -1
- package/dist/components/app/editable-value.js +8 -3
- package/dist/components/app/entity-view.js +2 -1
- package/dist/components/app/lost-edit-toast.d.ts +10 -0
- package/dist/components/app/lost-edit-toast.js +29 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/lib/image-file.d.ts +19 -0
- package/dist/lib/image-file.js +52 -1
- package/package.json +1 -1
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
- Step 8: Add Playwright specs for all three screens · lines 255–335
|
|
17
17
|
- Step 9: Register the nav entry and route names · lines 336–349
|
|
18
18
|
- Step 10: `npm run verify`. · lines 350–351
|
|
19
|
-
- [Step 6 in detail](#step-6-in-detail) · lines 353–
|
|
19
|
+
- [Step 6 in detail](#step-6-in-detail) · lines 353–959
|
|
20
20
|
- [A `reference`](#a-reference) · lines 358–360
|
|
21
21
|
- [A `single choice`](#a-single-choice) · lines 362–368
|
|
22
22
|
- [A `date-time`](#a-date-time) · lines 370–373
|
|
@@ -28,29 +28,29 @@
|
|
|
28
28
|
- [A `date`](#a-date) · lines 436–459
|
|
29
29
|
- [A `month-day`](#a-month-day) · lines 461–481
|
|
30
30
|
- [A `recurrence`](#a-recurrence) · lines 483–504
|
|
31
|
-
- [An image on a record](#an-image-on-a-record) · lines 506–
|
|
32
|
-
- [A `reference` inside a sub-record item](#a-reference-inside-a-sub-record-item) · lines
|
|
33
|
-
- [A `yes/no` marked `toggle`](#a-yesno-marked-toggle) · lines
|
|
34
|
-
- [Keep column definitions stable](#keep-column-definitions-stable) · lines
|
|
35
|
-
- [The view](#the-view) · lines
|
|
36
|
-
- [The view: long text and notes](#the-view-long-text-and-notes) · lines
|
|
37
|
-
- [The view: quick actions and editing in place](#the-view-quick-actions-and-editing-in-place) · lines
|
|
38
|
-
- [The table opens the view, and the form returns to it](#the-table-opens-the-view-and-the-form-returns-to-it) · lines
|
|
39
|
-
- [`<SelectValue>` shows the value, not the label](#selectvalue-shows-the-value-not-the-label) · lines
|
|
40
|
-
- [Choosing how each column looks](#choosing-how-each-column-looks) · lines
|
|
41
|
-
- [How a list opens a record](#how-a-list-opens-a-record) · lines
|
|
42
|
-
- [The record view](#the-record-view) · lines
|
|
43
|
-
- [Forms](#forms) · lines
|
|
44
|
-
- [Dialogs](#dialogs) · lines
|
|
45
|
-
- [Toasts and feedback](#toasts-and-feedback) · lines
|
|
46
|
-
- [What not to copy](#what-not-to-copy) · lines
|
|
47
|
-
- [After a commit, in the backend](#after-a-commit-in-the-backend) · lines
|
|
48
|
-
- [Saves that don't overwrite](#saves-that-dont-overwrite) · lines
|
|
49
|
-
- [Deleting](#deleting) · lines
|
|
50
|
-
- [Fields only a script writes](#fields-only-a-script-writes) · lines
|
|
51
|
-
- [Searching one part of the app](#searching-one-part-of-the-app) · lines
|
|
52
|
-
- [What a chat is told about an entity](#what-a-chat-is-told-about-an-entity) · lines
|
|
53
|
-
- [Behind a sign-in proxy](#behind-a-sign-in-proxy) · lines
|
|
31
|
+
- [An image on a record](#an-image-on-a-record) · lines 506–558
|
|
32
|
+
- [A `reference` inside a sub-record item](#a-reference-inside-a-sub-record-item) · lines 560–619
|
|
33
|
+
- [A `yes/no` marked `toggle`](#a-yesno-marked-toggle) · lines 621–636
|
|
34
|
+
- [Keep column definitions stable](#keep-column-definitions-stable) · lines 638–646
|
|
35
|
+
- [The view](#the-view) · lines 648–766
|
|
36
|
+
- [The view: long text and notes](#the-view-long-text-and-notes) · lines 768–822
|
|
37
|
+
- [The view: quick actions and editing in place](#the-view-quick-actions-and-editing-in-place) · lines 824–882
|
|
38
|
+
- [The table opens the view, and the form returns to it](#the-table-opens-the-view-and-the-form-returns-to-it) · lines 884–895
|
|
39
|
+
- [`<SelectValue>` shows the value, not the label](#selectvalue-shows-the-value-not-the-label) · lines 897–943
|
|
40
|
+
- [Choosing how each column looks](#choosing-how-each-column-looks) · lines 945–959
|
|
41
|
+
- [How a list opens a record](#how-a-list-opens-a-record) · lines 961–1472
|
|
42
|
+
- [The record view](#the-record-view) · lines 1104–1291
|
|
43
|
+
- [Forms](#forms) · lines 1293–1376
|
|
44
|
+
- [Dialogs](#dialogs) · lines 1378–1411
|
|
45
|
+
- [Toasts and feedback](#toasts-and-feedback) · lines 1413–1472
|
|
46
|
+
- [What not to copy](#what-not-to-copy) · lines 1474–1501
|
|
47
|
+
- [After a commit, in the backend](#after-a-commit-in-the-backend) · lines 1503–1520
|
|
48
|
+
- [Saves that don't overwrite](#saves-that-dont-overwrite) · lines 1522–1582
|
|
49
|
+
- [Deleting](#deleting) · lines 1584–1614
|
|
50
|
+
- [Fields only a script writes](#fields-only-a-script-writes) · lines 1616–1635
|
|
51
|
+
- [Searching one part of the app](#searching-one-part-of-the-app) · lines 1637–1646
|
|
52
|
+
- [What a chat is told about an entity](#what-a-chat-is-told-about-an-entity) · lines 1649–1691
|
|
53
|
+
- [Behind a sign-in proxy](#behind-a-sign-in-proxy) · lines 1693–1726
|
|
54
54
|
|
|
55
55
|
<!-- /index -->
|
|
56
56
|
|
|
@@ -505,33 +505,57 @@ rule it refuses); `next_after` and `occurrences` say when it falls
|
|
|
505
505
|
|
|
506
506
|
### An image on a record
|
|
507
507
|
|
|
508
|
-
**
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
`
|
|
515
|
-
|
|
516
|
-
`
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
508
|
+
**Pictures are stored once, for the whole app**, by the template's
|
|
509
|
+
reference: copy it whole the first time an entity needs one.
|
|
510
|
+
- *Contract:* `openapi.yaml`'s `/files` (`uploadFile`: the request body
|
|
511
|
+
is the picture itself, no multipart form; 201 a `File`, 413 over
|
|
512
|
+
10 MB, 422 on `file` for anything not a JPEG, PNG or WebP), `/files/{id}`
|
|
513
|
+
(`getFile`) and `/files/{id}/content` (`getFileContent`, the bytes, with
|
|
514
|
+
a `size` it takes and ignores). Another user's file is a 404.
|
|
515
|
+
- *Gateway:* `src/api/gateway/files.ts`. `uploadImage(file)` is the
|
|
516
|
+
foundation's `ImageUpload`: it calls `shrinkImage(file)` first (redrawn
|
|
517
|
+
upright, at most 2560 px on its long edge, as WebP, with no EXIF and so
|
|
518
|
+
no location; the original file where the browser can't), sends it with
|
|
519
|
+
`uploadFile`, and resolves to `{ id, thumbUrl, url }` (the
|
|
520
|
+
`ImageUploadResult`), the 422's reason as its `message`.
|
|
521
|
+
`fileContentUrl(id)` is the address, `/api/files/{id}/content`; text
|
|
522
|
+
holds it as ``. Its tests are
|
|
523
|
+
`tests/gateway/files.test.ts`.
|
|
524
|
+
- *Mocks:* `src/mocks/files.ts`, reset by `resetMockData()`; read the type
|
|
525
|
+
from the bytes as the backend does.
|
|
526
|
+
- *Backend:* `app/routers/files.py`, `StoredFile` and `StoredFileContent`
|
|
527
|
+
in `app/models.py`, migration `0018` (a `files` row, the bytes in
|
|
528
|
+
`file_contents` so reading the row never loads them). The type sniff,
|
|
529
|
+
the read with a limit and the serving headers are the backend
|
|
530
|
+
package's `foundation_backend.uploads` (`image_type`, `read_upload`,
|
|
531
|
+
`image_response`), never the app's own code: served with `nosniff`, an
|
|
532
|
+
inline `Content-Disposition` named from the id, `default-src 'none';
|
|
533
|
+
sandbox`, `same-origin` and a private, immutable cache. Nothing deletes a
|
|
534
|
+
file: a soft-deleted record can come back with its pictures.
|
|
535
|
+
|
|
536
|
+
**Pictures in long text** (a notes field): the description editor's
|
|
537
|
+
`upload` is that function, through a mutation
|
|
538
|
+
(`src/routes/widgets/use-upload-image.ts`, `upload={useUploadImage()}` on
|
|
539
|
+
`WidgetDescriptionEditor`); a picture pasted, dropped or picked with the
|
|
540
|
+
Image tool goes in as its address. `e2e/widget-description-images.spec.ts`
|
|
541
|
+
is its spec.
|
|
542
|
+
|
|
543
|
+
**An image on a record** (a photo of it) is its file's id on the wire
|
|
544
|
+
(`photoFileId`, `integer`, nullable), and on
|
|
545
|
+
the form the foundation's `ImageField` in a `Controller`
|
|
546
|
+
(`z.string().nullable()`, converted with the form's other fields:
|
|
547
|
+
`String(id)` in, `Number(value)` out): `value` and `onChange` are the
|
|
548
|
+
id, `thumbUrl` the record's saved photo (`fileContentUrl(id, 'thumb')`),
|
|
549
|
+
`onBusyChange` holds the submit while a file uploads, and `upload` the
|
|
550
|
+
same `useUploadImage()`. The backend column is a foreign key to
|
|
551
|
+
`files.id`, checked as the record's other references are (another
|
|
552
|
+
user's file is a 422 on the field).
|
|
529
553
|
|
|
530
554
|
The types it takes default to JPEG, PNG and WebP; never add SVG or
|
|
531
|
-
HTML, which run script when served from the app's own domain.
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
address or a path on the site, so `url` is one of those.
|
|
555
|
+
HTML, which run script when served from the app's own domain. Don't set
|
|
556
|
+
`maxSize` to the server's limit: the size checked is the picked file's,
|
|
557
|
+
before `shrinkImage` makes it smaller. `<Markdown>` shows an image only
|
|
558
|
+
from a web address or a path on the site, so `url` is one of those.
|
|
535
559
|
|
|
536
560
|
### A `reference` inside a sub-record item
|
|
537
561
|
|
|
@@ -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–
|
|
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–
|
|
35
|
-
- [In a table's rows](#in-a-tables-rows) · lines
|
|
36
|
-
- [A table of a few short columns: `width="content"`](#a-table-of-a-few-short-columns-widthcontent) · lines
|
|
37
|
-
- [19. Stage circle for an ordered status](#19-stage-circle-for-an-ordered-status) · lines
|
|
38
|
-
- [20. Count linking to the related records](#20-count-linking-to-the-related-records) · lines
|
|
39
|
-
- [21. Rows grouped under headings, and a pill filter](#21-rows-grouped-under-headings-and-a-pill-filter) · lines
|
|
40
|
-
- [22. A highlighted row, and rows that are done](#22-a-highlighted-row-and-rows-that-are-done) · lines
|
|
41
|
-
- [28. A list's rows: hover, lines, rows per page](#28-a-lists-rows-hover-lines-rows-per-page) · lines
|
|
42
|
-
- [23. A Group menu, and a record read beside the list](#23-a-group-menu-and-a-record-read-beside-the-list) · lines
|
|
43
|
-
- [24. A stored colour beside its name](#24-a-stored-colour-beside-its-name) · lines
|
|
44
|
-
- [Picking one on a form: `ColorField`](#picking-one-on-a-form-colorfield) · lines
|
|
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
|
|
46
|
-
- [The framed look, and sibling lists beside the title](#the-framed-look-and-sibling-lists-beside-the-title) · lines
|
|
47
|
-
- [26. A record's related list, capped](#26-a-records-related-list-capped) · lines
|
|
48
|
-
- [27. A repeat and its next time](#27-a-repeat-and-its-next-time) · lines
|
|
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,
|
|
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
|
|
@@ -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
|
-
|
|
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
|
-
|
|
25
|
-
|
|
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
|
|
30
|
-
//
|
|
31
|
-
//
|
|
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
|
-
//
|
|
148
|
-
//
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
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
|
|
169
|
-
//
|
|
170
|
-
|
|
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
|
|
173
|
-
.
|
|
174
|
-
|
|
175
|
-
|
|
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
|
|
179
|
-
return config.save(parsed.data).then(() => true, () =>
|
|
180
|
-
}
|
|
181
|
-
|
|
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
|
|
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,
|
|
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
|
-
|
|
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';
|
|
@@ -117,7 +117,7 @@ export { IconField, type IconFieldOption, type IconFieldProps } from './componen
|
|
|
117
117
|
export { MonthDayField, type MonthDayFieldProps } from './components/app/month-day-field.js';
|
|
118
118
|
export { ImageField, type ImageFieldProps } from './components/app/image-field.js';
|
|
119
119
|
export { ImageViewer, type ImageViewerImage, type ImageViewerProps } from './components/app/image-viewer.js';
|
|
120
|
-
export { DEFAULT_IMAGE_TYPES, type ImageUpload, type ImageUploadResult } from './lib/image-file.js';
|
|
120
|
+
export { DEFAULT_IMAGE_TYPES, shrinkImage, type ImageUpload, type ImageUploadResult, type ShrinkImageOptions } from './lib/image-file.js';
|
|
121
121
|
export { formatPlainDate, parsePlainDate, plainDateExamples, unreadableDateMessage, type ParsePlainDateOptions, type PlainDate, } from './lib/plain-date.js';
|
|
122
122
|
export { formatMonthDay, isMonthDay, monthDayProblem, type MonthDay } from './lib/month-day.js';
|
|
123
123
|
export { RecurrenceField, type RecurrenceFieldProps } from './components/app/recurrence-field.js';
|
package/dist/index.js
CHANGED
|
@@ -127,7 +127,7 @@ export { IconField } from './components/app/icon-field.js';
|
|
|
127
127
|
export { MonthDayField } from './components/app/month-day-field.js';
|
|
128
128
|
export { ImageField } from './components/app/image-field.js';
|
|
129
129
|
export { ImageViewer } from './components/app/image-viewer.js';
|
|
130
|
-
export { DEFAULT_IMAGE_TYPES } from './lib/image-file.js';
|
|
130
|
+
export { DEFAULT_IMAGE_TYPES, shrinkImage } from './lib/image-file.js';
|
|
131
131
|
export { formatPlainDate, parsePlainDate, plainDateExamples, unreadableDateMessage, } from './lib/plain-date.js';
|
|
132
132
|
export { formatMonthDay, isMonthDay, monthDayProblem } from './lib/month-day.js';
|
|
133
133
|
export { RecurrenceField } from './components/app/recurrence-field.js';
|
package/dist/lib/image-file.d.ts
CHANGED
|
@@ -36,5 +36,24 @@ export declare function acceptAttribute(accept?: readonly string[]): string;
|
|
|
36
36
|
export declare function imageRefusal(file: Pick<File, 'type' | 'size'> & {
|
|
37
37
|
name?: string;
|
|
38
38
|
}, rules?: ImageFileRules): string | null;
|
|
39
|
+
export type ShrinkImageOptions = {
|
|
40
|
+
/** The longest edge, in pixels, the picture is drawn at most. Defaults to 2560. A smaller picture is never enlarged. */
|
|
41
|
+
maxEdge?: number;
|
|
42
|
+
/** The type it's written as. Defaults to `image/webp`. */
|
|
43
|
+
type?: string;
|
|
44
|
+
/** Quality for a lossy type, 0 to 1. Defaults to 0.85. */
|
|
45
|
+
quality?: number;
|
|
46
|
+
};
|
|
47
|
+
/**
|
|
48
|
+
* A picture redrawn before it's uploaded: turned upright from its EXIF
|
|
49
|
+
* orientation, no longer than `maxEdge` on its long edge, and written as
|
|
50
|
+
* `type` (WebP unless asked otherwise). A phone photo of several
|
|
51
|
+
* megabytes becomes a few hundred kilobytes, and a redraw carries no
|
|
52
|
+
* EXIF, so no location. Resolves to the original file, untouched, when
|
|
53
|
+
* the browser can't: it can't read the file as a picture, or can't write
|
|
54
|
+
* the type. A courtesy, not a defence: the server checks what it's sent
|
|
55
|
+
* either way. An app's `ImageUpload` calls it before it sends the file.
|
|
56
|
+
*/
|
|
57
|
+
export declare function shrinkImage(file: File, options?: ShrinkImageOptions): Promise<File>;
|
|
39
58
|
/** What a failed upload says: the rejection's own `message` (an `AppError`'s), else a generic sentence. */
|
|
40
59
|
export declare function uploadFailure(error: unknown, noun?: string): string;
|
package/dist/lib/image-file.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
// Images a person picks, pastes or drops, before they're uploaded: which
|
|
2
2
|
// files are accepted, and why one isn't, in words. Shared by ImageField
|
|
3
3
|
// and the rich-text editor's upload. The upload itself is the app's (an
|
|
4
|
-
// `ImageUpload`): the package knows no endpoint and no storage.
|
|
4
|
+
// `ImageUpload`): the package knows no endpoint and no storage. Before it
|
|
5
|
+
// sends a picture, `shrinkImage` redraws it smaller and without its EXIF.
|
|
5
6
|
/** The image types accepted unless a field says otherwise. */
|
|
6
7
|
export const DEFAULT_IMAGE_TYPES = ['image/jpeg', 'image/png', 'image/webp'];
|
|
7
8
|
// How a type is named to a person: "JPEG", not "image/jpeg".
|
|
@@ -86,6 +87,56 @@ function article(name) {
|
|
|
86
87
|
const spelled = /^[A-Z][A-Z0-9]+$/.test(name);
|
|
87
88
|
return (spelled ? /^[AEFHILMNORSX]/ : /^[aeiou]/i).test(name) ? 'an' : 'a';
|
|
88
89
|
}
|
|
90
|
+
/**
|
|
91
|
+
* A picture redrawn before it's uploaded: turned upright from its EXIF
|
|
92
|
+
* orientation, no longer than `maxEdge` on its long edge, and written as
|
|
93
|
+
* `type` (WebP unless asked otherwise). A phone photo of several
|
|
94
|
+
* megabytes becomes a few hundred kilobytes, and a redraw carries no
|
|
95
|
+
* EXIF, so no location. Resolves to the original file, untouched, when
|
|
96
|
+
* the browser can't: it can't read the file as a picture, or can't write
|
|
97
|
+
* the type. A courtesy, not a defence: the server checks what it's sent
|
|
98
|
+
* either way. An app's `ImageUpload` calls it before it sends the file.
|
|
99
|
+
*/
|
|
100
|
+
export async function shrinkImage(file, options = {}) {
|
|
101
|
+
const { maxEdge = 2560, type = 'image/webp', quality = 0.85 } = options;
|
|
102
|
+
if (typeof createImageBitmap !== 'function' || typeof document === 'undefined')
|
|
103
|
+
return file;
|
|
104
|
+
let bitmap;
|
|
105
|
+
try {
|
|
106
|
+
bitmap = await createImageBitmap(file, { imageOrientation: 'from-image' });
|
|
107
|
+
}
|
|
108
|
+
catch {
|
|
109
|
+
return file;
|
|
110
|
+
}
|
|
111
|
+
try {
|
|
112
|
+
const scale = Math.min(1, maxEdge / Math.max(bitmap.width, bitmap.height));
|
|
113
|
+
const width = Math.max(1, Math.round(bitmap.width * scale));
|
|
114
|
+
const height = Math.max(1, Math.round(bitmap.height * scale));
|
|
115
|
+
const canvas = document.createElement('canvas');
|
|
116
|
+
canvas.width = width;
|
|
117
|
+
canvas.height = height;
|
|
118
|
+
const context = canvas.getContext('2d');
|
|
119
|
+
if (!context)
|
|
120
|
+
return file;
|
|
121
|
+
context.imageSmoothingQuality = 'high';
|
|
122
|
+
context.drawImage(bitmap, 0, 0, width, height);
|
|
123
|
+
const blob = await new Promise((resolve) => canvas.toBlob(resolve, type, quality));
|
|
124
|
+
// A browser that can't write the type hands back a PNG instead.
|
|
125
|
+
if (!blob || blob.type !== type)
|
|
126
|
+
return file;
|
|
127
|
+
return new File([blob], renamed(file.name, type), { type, lastModified: file.lastModified });
|
|
128
|
+
}
|
|
129
|
+
finally {
|
|
130
|
+
bitmap.close();
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
const EXTENSIONS = { 'image/webp': 'webp', 'image/jpeg': 'jpg', 'image/png': 'png' };
|
|
134
|
+
// "IMG_0042.HEIC" written as WebP is "IMG_0042.webp".
|
|
135
|
+
function renamed(name, type) {
|
|
136
|
+
const extension = EXTENSIONS[type] ?? type.split('/')[1] ?? 'img';
|
|
137
|
+
const stem = name.includes('.') ? name.slice(0, name.lastIndexOf('.')) : name;
|
|
138
|
+
return `${stem || 'image'}.${extension}`;
|
|
139
|
+
}
|
|
89
140
|
/** What a failed upload says: the rejection's own `message` (an `AppError`'s), else a generic sentence. */
|
|
90
141
|
export function uploadFailure(error, noun = 'image') {
|
|
91
142
|
if (error && typeof error === 'object' && 'message' in error) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tristan2828/ui-foundation",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.150.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": {
|