@tristan2828/ui-foundation 4.148.0 → 4.149.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.
@@ -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–935
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–534
32
- - [A `reference` inside a sub-record item](#a-reference-inside-a-sub-record-item) · lines 536–595
33
- - [A `yes/no` marked `toggle`](#a-yesno-marked-toggle) · lines 597–612
34
- - [Keep column definitions stable](#keep-column-definitions-stable) · lines 614–622
35
- - [The view](#the-view) · lines 624–742
36
- - [The view: long text and notes](#the-view-long-text-and-notes) · lines 744–798
37
- - [The view: quick actions and editing in place](#the-view-quick-actions-and-editing-in-place) · lines 800–858
38
- - [The table opens the view, and the form returns to it](#the-table-opens-the-view-and-the-form-returns-to-it) · lines 860–871
39
- - [`<SelectValue>` shows the value, not the label](#selectvalue-shows-the-value-not-the-label) · lines 873–919
40
- - [Choosing how each column looks](#choosing-how-each-column-looks) · lines 921–935
41
- - [How a list opens a record](#how-a-list-opens-a-record) · lines 937–1448
42
- - [The record view](#the-record-view) · lines 1080–1267
43
- - [Forms](#forms) · lines 1269–1352
44
- - [Dialogs](#dialogs) · lines 1354–1387
45
- - [Toasts and feedback](#toasts-and-feedback) · lines 1389–1448
46
- - [What not to copy](#what-not-to-copy) · lines 1450–1477
47
- - [After a commit, in the backend](#after-a-commit-in-the-backend) · lines 1479–1496
48
- - [Saves that don't overwrite](#saves-that-dont-overwrite) · lines 1498–1558
49
- - [Deleting](#deleting) · lines 1560–1590
50
- - [Fields only a script writes](#fields-only-a-script-writes) · lines 1592–1611
51
- - [Searching one part of the app](#searching-one-part-of-the-app) · lines 1613–1622
52
- - [What a chat is told about an entity](#what-a-chat-is-told-about-an-entity) · lines 1625–1667
53
- - [Behind a sign-in proxy](#behind-a-sign-in-proxy) · lines 1669–1702
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
- **An image on a record** (a photo of it) is the stored file's id on the
509
- wire (`string`, nullable), and on the form the foundation's
510
- `ImageField` in a `Controller` (`z.string().nullable()`): `value` and
511
- `onChange` are the id, `thumbUrl` the record's saved photo,
512
- `onBusyChange` holds the submit while a file uploads. Its `upload` is the app's own, one function in the
513
- gateway that sends the file to the app's endpoint and resolves to
514
- `{ id, thumbUrl, url }` (the `ImageUploadResult`), rejecting with the
515
- `AppError`; the same function goes to a notes field's
516
- `RichTextEditor`, so pictures in its text use the same storage:
517
-
518
- ```ts
519
- // src/api/gateway/files.ts
520
- export async function uploadImage(file: File): Promise<ImageUploadResult> {
521
- const body = new FormData()
522
- body.append('file', file)
523
- const response = await safeFetch('/files', { method: 'POST', body })
524
- if (response.status !== 201) throw toAppError(response.status, response.body, response.headers)
525
- const { id } = response.body as components['schemas']['File']
526
- return { id, thumbUrl: `/api/files/${id}/content?size=thumb`, url: `/api/files/${id}/content` }
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 `![](/api/files/{id}/content)`. 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. The
532
- endpoint, the storage and serving the files are the app's (the
533
- template has none); `<Markdown>` shows an image only from a web
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
 
package/dist/index.d.ts CHANGED
@@ -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';
@@ -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;
@@ -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.148.0",
3
+ "version": "4.149.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": {