@sincpro/web-framework 3.12.1 → 3.14.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.
Files changed (56) hide show
  1. package/README.md +65 -1
  2. package/dist/core/cache.js +11 -0
  3. package/dist/core/copy.d.ts +20 -0
  4. package/dist/core/copy.js +23 -0
  5. package/dist/core/edit.d.ts +3 -0
  6. package/dist/core/edit.js +9 -6
  7. package/dist/core/files.d.ts +58 -0
  8. package/dist/core/files.js +57 -15
  9. package/dist/core/index.d.ts +5 -3
  10. package/dist/core/index.js +5 -3
  11. package/dist/core/present.d.ts +16 -0
  12. package/dist/core/present.js +41 -4
  13. package/dist/core/reorder.d.ts +59 -0
  14. package/dist/core/reorder.js +106 -0
  15. package/dist/core/richText.d.ts +39 -0
  16. package/dist/core/richText.js +45 -0
  17. package/dist/core/summary.js +5 -1
  18. package/dist/errors/index.d.ts +3 -1
  19. package/dist/errors/index.js +14 -2
  20. package/dist/errors/narrowed.d.ts +2 -0
  21. package/dist/errors/narrowed.js +7 -0
  22. package/dist/errors/server.js +1 -7
  23. package/dist/react/context.d.ts +20 -1
  24. package/dist/react/context.js +11 -4
  25. package/dist/react/index.d.ts +1 -0
  26. package/dist/react/index.js +1 -0
  27. package/dist/react/useTextOf.d.ts +3 -2
  28. package/dist/react/useTextOf.js +4 -4
  29. package/dist/react/useUpload.d.ts +33 -0
  30. package/dist/react/useUpload.js +69 -0
  31. package/dist/telemetry/index.d.ts +21 -1
  32. package/dist/telemetry/index.js +35 -1
  33. package/dist/web/index.d.ts +6 -1
  34. package/dist/web/index.js +6 -1
  35. package/dist/web/list/EntityList.js +11 -5
  36. package/dist/web/list/reorder.d.ts +31 -0
  37. package/dist/web/list/reorder.js +67 -0
  38. package/dist/web/record/ActionButton.d.ts +1 -1
  39. package/dist/web/record/ActionButton.js +7 -2
  40. package/dist/web/record/ask.d.ts +18 -0
  41. package/dist/web/record/ask.js +15 -0
  42. package/dist/web/record/choice.d.ts +32 -0
  43. package/dist/web/record/choice.js +36 -0
  44. package/dist/web/record/control.d.ts +4 -0
  45. package/dist/web/record/control.js +52 -1
  46. package/dist/web/record/edit.js +37 -5
  47. package/dist/web/record/fileControl.d.ts +22 -0
  48. package/dist/web/record/fileControl.js +48 -0
  49. package/dist/web/record/person.d.ts +23 -0
  50. package/dist/web/record/person.js +27 -0
  51. package/dist/web/record/record.js +8 -2
  52. package/dist/web/record/richText.d.ts +27 -0
  53. package/dist/web/record/richText.js +59 -0
  54. package/dist/web/workspace/SincproApp.d.ts +10 -1
  55. package/dist/web/workspace/SincproApp.js +2 -2
  56. package/package.json +5 -5
package/README.md CHANGED
@@ -365,6 +365,58 @@ function InvoiceView({ api, resource }: ViewProps) {
365
365
  }
366
366
  ```
367
367
 
368
+ A field is drawn by what the model says it is, with no `as`: money (`widget: "money"`) is typed
369
+ in its currency — «Bs 1.150,50» —; formatted text (`widget: "html"`, sincpro_framework#371) is
370
+ web-ui's editor written and its cleaned HTML read; a relation to a person (`summary.person`) is
371
+ their face and name; a file or a picture is given right there, its bytes sent where the
372
+ application says. What is the application's is said once, on the provider:
373
+
374
+ ```tsx
375
+ <SincproApp
376
+ // …
377
+ currency="BOB"
378
+ region="es-BO" // numbers and money as the business writes them; words stay in `language`
379
+ richText={{ toolbar: "full", embeds: ["youtube"], sanitized: true }} // the backend cleans it
380
+ uploads={{
381
+ // sincpro_framework takes no file inside a Command (#364): the application's Command asks
382
+ // for an upload id for this record's field; the framework sends the bytes there, with
383
+ // progress, and the field holds `value` — what the save's Command names.
384
+ publish: async (file, { entity, id, field }, signal) => {
385
+ const { upload_id } = await mediaBoundedContext.execute(
386
+ new CommandStartUpload({ entity, id, field, name: file.name }),
387
+ { signal },
388
+ );
389
+ return {
390
+ link: `/files/uploads/${upload_id}`,
391
+ value: upload_id,
392
+ src: `/media/${upload_id}`,
393
+ };
394
+ },
395
+ }}
396
+ />
397
+ ```
398
+
399
+ A refusal is said by its reason in the copy's words (`FILE_TOO_LARGE` and its limit,
400
+ `FILE_TYPE_NOT_ALLOWED` and what it takes); `src` is where a picture inside a rich text is seen.
401
+ Without `uploads` a file field is only read. A field the model does not mark as formatted text
402
+ asks for it by reference — `<RecordField record={notice} name="body" as={richTextControl} />` —,
403
+ a screen of its own draws a choice's tag with `<ChoiceTag entity={payments} field="state"
404
+ value={payment.state} />`, and `useTextOf().money(total)` reads a bare amount a use case answered.
405
+
406
+ An action that asks before it runs says which answers it needs — «Confirmar» stays off, and the
407
+ dialog says what is missing, until they are given; how long or what shape an answer must be is
408
+ the use case's to refuse:
409
+
410
+ ```tsx
411
+ <CommandButton
412
+ entity={receipts}
413
+ command="reject"
414
+ id={receipt.id}
415
+ label="Reject…"
416
+ ask={[{ name: "reason", label: "Reason", widget: "textarea", required: true }]}
417
+ />
418
+ ```
419
+
368
420
  How a record of an entity LOOKS — as a choice, a row, a card, a tile — is said once, around the
369
421
  entity, and every place that draws one uses it (`EntityPicker`, `EntityTags`, ⌘K, `EntityList`'s
370
422
  rows, board and tiles). Each size answers web-ui's props for it, over the default; give only what changes:
@@ -563,6 +615,13 @@ Next writes the request's own into the page (`experimental.clientTraceMetadata:
563
615
  `<meta name="traceparent">` — on dynamic pages only: a cached page would hand every visitor one
564
616
  trace).
565
617
 
618
+ A page drawn on the server can hand its trace to the browser: with
619
+ `browserTracer({ …, continueServerTrace: true })` the page's first use case is a child of the
620
+ render's span (`<meta name="traceparent">`), one trace from the request to the first read the
621
+ browser made; what a person does later starts traces of its own. Only on pages rendered per
622
+ request — a cached page (ISR, a static export) carries one meta for every visitor, so leave it
623
+ off where that cannot be told.
624
+
566
625
  A page that broke while drawing shows the route's error screen instead of the framework's generic
567
626
  one: plain words, the code the server logged it with (Next's `digest`), «try again» and «home»,
568
627
  reported once through the process:
@@ -580,7 +639,8 @@ What fails on the server reaches GlitchTip too, with its real stack — the brow
580
639
  Next's generic message and the `digest`. `./errors/server` keeps one Sentry-compatible client per
581
640
  process (`@sentry/core`'s server client, not `@sentry/node`, which would set up an OpenTelemetry
582
641
  of its own); a request's report carries the same `digest` the visitor sees, its route and its
583
- trace:
642
+ trace — and the browser's report of it (`RouteError`, through `glitchtipReporter`) is tagged
643
+ with that `digest` too, so the two reports of one failure are found together:
584
644
 
585
645
  ```ts
586
646
  // instrumentation.ts (Next) — once per process, and each request that failed
@@ -638,6 +698,10 @@ hook and draw your own, or go straight to the loose piece.
638
698
  | What is each field? | `Meta` from the server, or `defineMeta` | — | `textOf`, `viewOf`, `metaFromSchema` |
639
699
  | A value outside a model | — | `useTextOf` | `moneyTextOf`, `dayTextOf`, `instantTextOf`, `numberTextOf` |
640
700
  | A file or a photo it holds | `EntityList`, `RecordField`: by its widget, as a `FileValue` | — | `attachmentOf`, `storedFileOf`, `renditionUrl` |
701
+ | A file given in the record | `RecordField` with `uploads`: `FileControl` (`DropZone`) | `useUpload` | `sendFile`, `uploadRefusalOf` |
702
+ | Formatted text | `RecordField` (`widget: "html"`), `factsOf`: `RichTextControl` | — | `richTextPlainOf`, `holdsRichText` |
703
+ | A person, read | `RecordField`, `factsOf`: `PersonValue` (`UserChip`) | `useSummaryOf` | `isPersonEntity` |
704
+ | A choice's tag outside a list | `ChoiceTag` | — | `choiceTagOf` |
641
705
  | What is a record, at any size? | `cardOf`, `relationOf` | `useSummaryOf` | `summaryOf` |
642
706
  | How does a record look? | `presented(entity, { option, row, card, tile })` | — | `presentationOf` |
643
707
  | N records: search, filter, page | `EntityList`, `EntitySearchBar` | `useListing`, `useGroups` | `transport.list(route, criteria)` |
@@ -99,6 +99,17 @@ export function cachedTransport(transport, options = {}) {
99
99
  : {
100
100
  read: (route, signal, options) => transport.read(route, signal, options),
101
101
  }),
102
+ // An export streamed and a file's bytes are never an answer to keep: they pass through.
103
+ ...(transport.download === undefined
104
+ ? {}
105
+ : {
106
+ download: (route, signal, options) => transport.download(route, signal, options),
107
+ }),
108
+ ...(transport.upload === undefined
109
+ ? {}
110
+ : {
111
+ upload: (link, file, signal, options) => transport.upload(link, file, signal, options),
112
+ }),
102
113
  async send(method, route, body, signal, sending) {
103
114
  try {
104
115
  return await transport.send(method, route, body, signal, sending);
@@ -32,6 +32,8 @@ export type FrameworkCopy = {
32
32
  capped: (shown: number) => string;
33
33
  /** Conditions the server could not answer: the list is WIDER than asked. */
34
34
  dropped: (fields: readonly string[]) => string;
35
+ /** A row put in its place by hand was dropped among another group's: nothing was written. */
36
+ reorderElsewhere: string;
35
37
  /** The group of the records that hold no value in the field grouped by. */
36
38
  noValue: string;
37
39
  /** More groups than shown: narrow the set instead of scrolling them. */
@@ -146,8 +148,24 @@ export type FrameworkCopy = {
146
148
  /** Leaves for the application's start. */
147
149
  home: string;
148
150
  };
151
+ /**
152
+ * A file a person gives a record (`RecordField` of a file, a picture inside a rich text): why
153
+ * it was not taken, by the backend's reason. Optional, as `route`: English without it.
154
+ */
155
+ upload?: {
156
+ /** Larger than the backend takes; `max` is its limit as a person reads it, when it said. */
157
+ tooLarge: (max: string | null) => string;
158
+ /** A kind of file it does not take; `allowed` its MIME types, when it said them. */
159
+ typeNotAllowed: (allowed: readonly string[]) => string;
160
+ empty: string;
161
+ /** The link to send it to ended, or was used: choosing the file again asks for another. */
162
+ expired: string;
163
+ /** Anything else: it did not arrive. */
164
+ failed: string;
165
+ };
149
166
  };
150
167
  type RouteCopy = NonNullable<FrameworkCopy["route"]>;
168
+ type UploadCopy = NonNullable<FrameworkCopy["upload"]>;
151
169
  export declare const ENGLISH_FRAMEWORK_COPY: FrameworkCopy;
152
170
  export declare const SPANISH_FRAMEWORK_COPY: FrameworkCopy;
153
171
  /** Install the framework's words once, where the application starts. */
@@ -156,4 +174,6 @@ export declare function installFrameworkCopy(copy: FrameworkCopy): void;
156
174
  export declare const frameworkCopy: () => FrameworkCopy;
157
175
  /** The words of a page that broke: the installed table's, or English when it has none. */
158
176
  export declare const routeCopy: () => RouteCopy;
177
+ /** The words of a file not taken: the installed table's, or English when it has none. */
178
+ export declare const uploadCopy: () => UploadCopy;
159
179
  export {};
package/dist/core/copy.js CHANGED
@@ -1,3 +1,12 @@
1
+ const ENGLISH_UPLOAD = {
2
+ tooLarge: (max) => max === null ? "The file is too large." : `The file is larger than ${max}.`,
3
+ typeNotAllowed: (allowed) => allowed.length === 0
4
+ ? "This kind of file is not taken."
5
+ : `This kind of file is not taken (it takes ${allowed.join(", ")}).`,
6
+ empty: "The file is empty.",
7
+ expired: "The upload took too long. Choose the file again.",
8
+ failed: "The file could not be sent.",
9
+ };
1
10
  const ENGLISH_ROUTE = {
2
11
  broke: "Something went wrong showing this page",
3
12
  sentence: "It is not something you did. Try again; if it happens again, report it.",
@@ -23,6 +32,7 @@ export const ENGLISH_FRAMEWORK_COPY = {
23
32
  builder: "Criteria builder",
24
33
  capped: (shown) => `Showing the first ${shown}. Narrow the search to see the rest.`,
25
34
  dropped: (fields) => `The server ignored a condition on ${fields.join(", ")}: the list shows more than asked.`,
35
+ reorderElsewhere: "A row only moves among the rows of its own group.",
26
36
  noValue: "No value",
27
37
  groupsCapped: (shown) => `The first ${shown} groups. Narrow the search to see the rest.`,
28
38
  groups: (groups, records) => `${groups} ${groups === 1 ? "group" : "groups"} · ${records} ${records === 1 ? "record" : "records"}`,
@@ -108,6 +118,7 @@ export const ENGLISH_FRAMEWORK_COPY = {
108
118
  },
109
119
  },
110
120
  route: ENGLISH_ROUTE,
121
+ upload: ENGLISH_UPLOAD,
111
122
  };
112
123
  export const SPANISH_FRAMEWORK_COPY = {
113
124
  value: {
@@ -127,6 +138,7 @@ export const SPANISH_FRAMEWORK_COPY = {
127
138
  builder: "Constructor de criteria",
128
139
  capped: (shown) => `Se muestran los primeros ${shown}. Refiná la búsqueda para ver el resto.`,
129
140
  dropped: (fields) => `El servidor ignoró una condición sobre ${fields.join(", ")}: la lista muestra más de lo pedido.`,
141
+ reorderElsewhere: "Una fila solo se mueve entre las de su mismo grupo.",
130
142
  noValue: "Sin valor",
131
143
  groupsCapped: (shown) => `Los primeros ${shown} grupos. Acotá la búsqueda para ver el resto.`,
132
144
  groups: (groups, records) => `${groups} ${groups === 1 ? "grupo" : "grupos"} · ${records} ${records === 1 ? "registro" : "registros"}`,
@@ -211,6 +223,15 @@ export const SPANISH_FRAMEWORK_COPY = {
211
223
  internal: "Si vuelve a pasar, avisá a soporte.",
212
224
  },
213
225
  },
226
+ upload: {
227
+ tooLarge: (max) => max === null ? "El archivo es demasiado grande." : `El archivo pesa más de ${max}.`,
228
+ typeNotAllowed: (allowed) => allowed.length === 0
229
+ ? "Este tipo de archivo no se acepta."
230
+ : `Este tipo de archivo no se acepta (se acepta ${allowed.join(", ")}).`,
231
+ empty: "El archivo está vacío.",
232
+ expired: "La subida tardó demasiado. Elegí el archivo de nuevo.",
233
+ failed: "No se pudo enviar el archivo.",
234
+ },
214
235
  route: {
215
236
  broke: "Algo salió mal al mostrar esta página",
216
237
  sentence: "No es algo que hayas hecho. Intentá de nuevo; si vuelve a pasar, avisá a soporte.",
@@ -228,3 +249,5 @@ export function installFrameworkCopy(copy) {
228
249
  export const frameworkCopy = () => installed;
229
250
  /** The words of a page that broke: the installed table's, or English when it has none. */
230
251
  export const routeCopy = () => installed.route ?? ENGLISH_ROUTE;
252
+ /** The words of a file not taken: the installed table's, or English when it has none. */
253
+ export const uploadCopy = () => installed.upload ?? ENGLISH_UPLOAD;
@@ -66,6 +66,9 @@ export declare function lineStatesOf(fromServer: FieldStates | undefined, name:
66
66
  export declare function linePlacesOf(name: string, line: AnyRecord, index: number, identity: string): string[];
67
67
  /** The fields whose value differs from the record's — what a save or a draft sends. */
68
68
  export declare function changesOf(record: AnyRecord, values: AnyRecord): AnyRecord;
69
+ /** Whether a value says nothing: `null`, nothing at all, an empty text or an empty list. What a
70
+ * required field may not be — in a record's save and in what an action asks. */
71
+ export declare function isEmptyValue(value: unknown): boolean;
69
72
  /** What is missing before it can be saved: a required, visible, editable field left empty. */
70
73
  export declare function missingOf(meta: Meta | null | undefined, values: AnyRecord, fromServer?: FieldStates): string[];
71
74
  /**
package/dist/core/edit.js CHANGED
@@ -84,18 +84,21 @@ export function changesOf(record, values) {
84
84
  changed[name] = value;
85
85
  return changed;
86
86
  }
87
+ /** Whether a value says nothing: `null`, nothing at all, an empty text or an empty list. What a
88
+ * required field may not be — in a record's save and in what an action asks. */
89
+ export function isEmptyValue(value) {
90
+ return (value === null ||
91
+ value === undefined ||
92
+ value === "" ||
93
+ (Array.isArray(value) && value.length === 0));
94
+ }
87
95
  /** What is missing before it can be saved: a required, visible, editable field left empty. */
88
96
  export function missingOf(meta, values, fromServer) {
89
97
  if (!meta)
90
98
  return [];
91
99
  return Object.keys(meta.fields).filter((name) => {
92
100
  const state = fieldStateOf(meta, name, values, fromServer);
93
- const value = values[name];
94
- const empty = value === null ||
95
- value === undefined ||
96
- value === "" ||
97
- (Array.isArray(value) && value.length === 0);
98
- return state.required && state.visible && !state.readonly && empty;
101
+ return state.required && state.visible && !state.readonly && isEmptyValue(values[name]);
99
102
  });
100
103
  }
101
104
  /**
@@ -1,3 +1,4 @@
1
+ import { type Transport } from "@sincpro/client-framework";
1
2
  /**
2
3
  * A file a record holds — sincpro_framework's `StoredFile`, as a read answers it: its name as it
3
4
  * was sent, its type, its size, a link to see it (`url`), and for a picture its renditions,
@@ -45,3 +46,60 @@ export declare function storedFileOf(value: unknown): StoredFileValue | null;
45
46
  /** Where to see the rendition `name` of a stored picture — the original's link when it has
46
47
  * none (a file put whole, a picture smaller than the rendition). */
47
48
  export declare function renditionUrl(file: StoredFileValue, name: string): string | undefined;
49
+ /** What a file being sent is for: the field of a record it goes into. */
50
+ export type UploadAbout = {
51
+ /** The entity's key (`aggregate`): `"Organo"`. */
52
+ entity: string;
53
+ /** The record's id — a new one's too, when the framework gave it one —; `null` when none yet. */
54
+ id: string | null;
55
+ /** The field it goes into: `"foto"`, or a rich text's `"cuerpo"` for a picture inside it. */
56
+ field: string;
57
+ };
58
+ /** Where a file goes, as the application's Command answered it. */
59
+ export type Published = {
60
+ /** Where its bytes are sent: the service's `/files/uploads/{id}`, or a bucket's signed URL. */
61
+ link: string;
62
+ /** What the field holds once the bytes are there — the id the save's Command names, or the
63
+ * file as the record will hold it. Left out when the backend already put it in the record
64
+ * (its Command claims the upload): the record is read again. */
65
+ value?: unknown;
66
+ /** Where the file is seen — a picture inside a rich text: `/media/…`, a CDN's address. */
67
+ src?: string;
68
+ /** What a picture shows, for whoever cannot see it. */
69
+ alt?: string;
70
+ };
71
+ /**
72
+ * How a file a person chose reaches the backend — the application's, because sincpro_framework
73
+ * publishes no route for it: a Command of its own asks for an upload id (`ObjectStorage.publish`
74
+ * with `Access.WRITE`, what it may be, how large), and the next Command names it.
75
+ *
76
+ * uploads={{
77
+ * publish: async (file, { entity, id, field }, signal) => {
78
+ * const { upload_id } = await media.execute(new CommandStartUpload(entity, id, field, file.name), { signal });
79
+ * return { link: `/files/uploads/${upload_id}`, value: upload_id };
80
+ * },
81
+ * }}
82
+ */
83
+ export type Uploads = {
84
+ publish: (file: File, about: UploadAbout, signal: AbortSignal) => Promise<Published>;
85
+ };
86
+ /**
87
+ * A file sent where the application says: asked for its link (`publish`), its bytes sent raw to
88
+ * it (`uploadTo`, client-framework) with the progress a screen draws and the signal that cancels
89
+ * it. Answers what was published; a refusal is the transport's (`uploadRefusalOf` says it).
90
+ *
91
+ * Context: sincpro_framework takes no file inside a Command (#364): the bytes go to an upload id,
92
+ * the same request whether they land on the service or on a bucket. One way in for every place a
93
+ * person gives a file — a record's file field, a picture inside a rich text.
94
+ */
95
+ export declare function sendFile(transport: Transport, uploads: Uploads, file: File, about: UploadAbout, options: {
96
+ signal: AbortSignal;
97
+ onProgress?: (fraction: number) => void;
98
+ }): Promise<Published>;
99
+ /**
100
+ * Why a file was not taken, in the copy table's words — by the problem's `reason`, with what it
101
+ * disclosed (`max_bytes`, `allowed`), never what a screen believes a file may be.
102
+ *
103
+ * uploadRefusalOf(transportError) -> "El archivo pesa más de 5 MB."
104
+ */
105
+ export declare function uploadRefusalOf(error: unknown): string;
@@ -1,18 +1,5 @@
1
- /**
2
- * A file a record holds — sincpro_framework's `StoredFile`, as a read answers it: its name as it
3
- * was sent, its type, its size, a link to see it (`url`), and for a picture its renditions,
4
- * `thumb` for a list's line and `view` for a record.
5
- *
6
- * holdsFile(meta.fields.foto) -> true (widget "image" or "file")
7
- * storedFileOf({ key: "fotos/01a1e.jpg", name: "Directorio.jpg", … }) -> StoredFileValue
8
- * storedFileOf("fotos/01a1e.jpg") -> null (a bare key names nothing)
9
- * renditionUrl(foto, "thumb") -> "/files/cGhv…" (else the original's)
10
- *
11
- * Context: the model publishes such a field as `embedded` with the widget `file` — or `image`,
12
- * by its presentation —; read as any embedded value it was a section of its parts (key, name,
13
- * type…) and a list's cell its JSON. Drawn by its widget it is ONE value: the picture and the
14
- * name it was sent with, the name downloading it (web-ui's `FileValue`).
15
- */
1
+ import { uploadTo } from "@sincpro/client-framework";
2
+ import { uploadCopy } from "./copy.js";
16
3
  /** The widgets that draw a field as one file: sincpro_framework's `Widget.FILE` / `IMAGE`. */
17
4
  export const FILE_WIDGETS = new Set(["file", "image"]);
18
5
  /** Whether a field holds a file — drawn as one value, by its widget. */
@@ -33,3 +20,58 @@ export function storedFileOf(value) {
33
20
  export function renditionUrl(file, name) {
34
21
  return file.renditions?.find((one) => one.name === name)?.url ?? file.url;
35
22
  }
23
+ /**
24
+ * A file sent where the application says: asked for its link (`publish`), its bytes sent raw to
25
+ * it (`uploadTo`, client-framework) with the progress a screen draws and the signal that cancels
26
+ * it. Answers what was published; a refusal is the transport's (`uploadRefusalOf` says it).
27
+ *
28
+ * Context: sincpro_framework takes no file inside a Command (#364): the bytes go to an upload id,
29
+ * the same request whether they land on the service or on a bucket. One way in for every place a
30
+ * person gives a file — a record's file field, a picture inside a rich text.
31
+ */
32
+ export async function sendFile(transport, uploads, file, about, options) {
33
+ const published = await uploads.publish(file, about, options.signal);
34
+ const progress = options.onProgress;
35
+ await uploadTo(transport, published.link, file, options.signal, {
36
+ ...(progress === undefined
37
+ ? {}
38
+ : {
39
+ onProgress: ({ loaded, total }) => progress(total > 0 ? loaded / total : 1),
40
+ }),
41
+ });
42
+ return published;
43
+ }
44
+ /** A size as a person reads it: «5 MB», «300 KB». */
45
+ function sizeText(bytes) {
46
+ if (bytes >= 1024 * 1024)
47
+ return `${Math.round((bytes / (1024 * 1024)) * 10) / 10} MB`;
48
+ if (bytes >= 1024)
49
+ return `${Math.round(bytes / 1024)} KB`;
50
+ return `${bytes} B`;
51
+ }
52
+ /**
53
+ * Why a file was not taken, in the copy table's words — by the problem's `reason`, with what it
54
+ * disclosed (`max_bytes`, `allowed`), never what a screen believes a file may be.
55
+ *
56
+ * uploadRefusalOf(transportError) -> "El archivo pesa más de 5 MB."
57
+ */
58
+ export function uploadRefusalOf(error) {
59
+ const copy = uploadCopy();
60
+ const problem = typeof error === "object" && error !== null && "problem" in error
61
+ ? error.problem
62
+ : null;
63
+ const said = problem?.extensions ?? {};
64
+ switch (problem?.reason) {
65
+ case "FILE_TOO_LARGE":
66
+ return copy.tooLarge(typeof said["max_bytes"] === "number" ? sizeText(said["max_bytes"]) : null);
67
+ case "FILE_TYPE_NOT_ALLOWED":
68
+ return copy.typeNotAllowed(Array.isArray(said["allowed"]) ? said["allowed"].map(String) : []);
69
+ case "FILE_EMPTY":
70
+ return copy.empty;
71
+ case "PUBLICATION_EXPIRED":
72
+ case "PUBLICATION_USED_UP":
73
+ return copy.expired;
74
+ default:
75
+ return copy.failed;
76
+ }
77
+ }
@@ -10,9 +10,9 @@
10
10
  export { type CachedTransport, cachedTransport, type CacheOptions, } from "./cache.js";
11
11
  export { sendRoute } from "./command.js";
12
12
  export { ENGLISH_FRAMEWORK_COPY, type FrameworkCopy, frameworkCopy, installFrameworkCopy, SPANISH_FRAMEWORK_COPY, } from "./copy.js";
13
- export { type Advice, adviceAt, changesOf, computedLocally, creationOf, defaultsOf, editedOf, errorAt, errorsByField, type FieldState, fieldStateOf, type FieldStates, linePlacesOf, lineStatesOf, missingOf, needsPreview, pathOf, type ServerFieldState, } from "./edit.js";
13
+ export { type Advice, adviceAt, changesOf, computedLocally, creationOf, defaultsOf, editedOf, errorAt, errorsByField, type FieldState, fieldStateOf, type FieldStates, isEmptyValue, linePlacesOf, lineStatesOf, missingOf, needsPreview, pathOf, type ServerFieldState, } from "./edit.js";
14
14
  export { explain } from "./explain.js";
15
- export { FILE_WIDGETS, holdsFile, renditionUrl, type RenditionValue, storedFileOf, type StoredFileValue, } from "./files.js";
15
+ export { FILE_WIDGETS, holdsFile, type Published, renditionUrl, type RenditionValue, sendFile, storedFileOf, type StoredFileValue, type UploadAbout, uploadRefusalOf, type Uploads, } from "./files.js";
16
16
  export { type FormLayout, formOf } from "./form.js";
17
17
  export { areGroups, NotGrouped } from "./groups.js";
18
18
  export { FACT_TONES, type FactTone, type HistoryChange, type HistoryEntry, historyOf, toneOfFact, } from "./history.js";
@@ -20,9 +20,11 @@ export { addingOf, type AddingRule, blankLine, type Declared, editableLines, isR
20
20
  export { CHOOSE_MANY, choosesMany, defineList, type GroupLevel, isList, type ListDefinition, listingAsk, type ListingQuestion, type ListSpec, type NamedFilter, readListing, scopeOf, trashOf, } from "./list.js";
21
21
  export { lookupOf, type LookupOption } from "./lookup.js";
22
22
  export { detailOf, measuresOf, sumsOf, type Total, totalOf, } from "./measure.js";
23
- export { BOOKKEEPING, currencyNow, type DateStyle, dateStyleNow, dayTextOf, defaultFields, fieldAt, fieldMetaOf, type FieldView, installCurrency, installDateStyle, instantTextOf, moneyTextOf, numberTextOf, shortTextOf, sortKeyOf, STAMPS, textOf, valueAt, viewOf, } from "./present.js";
23
+ export { amountTextOf, BOOKKEEPING, currencyNow, type DateStyle, dateStyleNow, dayTextOf, defaultFields, fieldAt, fieldMetaOf, type FieldView, installCurrency, installDateStyle, installRegion, instantTextOf, moneyTextOf, numberTextOf, regionNow, shortTextOf, sortKeyOf, STAMPS, textOf, valueAt, viewOf, } from "./present.js";
24
24
  export { type Related, relatedOf } from "./related.js";
25
25
  export { backReference, entityFor, relatedScope, type RelationField, relationFieldOf, } from "./relation.js";
26
+ export { GAP, HANDLE_WIDGET, handleOf, type Move, movesFor, placed, type Reordering, reorderingOf, } from "./reorder.js";
27
+ export { holdsRichText, RICH_TEXT_WIDGET, richTextPlainOf, type RichTextSettings, } from "./richText.js";
26
28
  export { readOnServer, readRecordOnServer, type RecordRead, type ServerRead, } from "./server.js";
27
29
  export { type RecordSummary, summaryFieldsOf, summaryOf, } from "./summary.js";
28
30
  export { placeOf, stepIn, type Trail } from "./trail.js";
@@ -10,9 +10,9 @@
10
10
  export { cachedTransport, } from "./cache.js";
11
11
  export { sendRoute } from "./command.js";
12
12
  export { ENGLISH_FRAMEWORK_COPY, frameworkCopy, installFrameworkCopy, SPANISH_FRAMEWORK_COPY, } from "./copy.js";
13
- export { adviceAt, changesOf, computedLocally, creationOf, defaultsOf, editedOf, errorAt, errorsByField, fieldStateOf, linePlacesOf, lineStatesOf, missingOf, needsPreview, pathOf, } from "./edit.js";
13
+ export { adviceAt, changesOf, computedLocally, creationOf, defaultsOf, editedOf, errorAt, errorsByField, fieldStateOf, isEmptyValue, linePlacesOf, lineStatesOf, missingOf, needsPreview, pathOf, } from "./edit.js";
14
14
  export { explain } from "./explain.js";
15
- export { FILE_WIDGETS, holdsFile, renditionUrl, storedFileOf, } from "./files.js";
15
+ export { FILE_WIDGETS, holdsFile, renditionUrl, sendFile, storedFileOf, uploadRefusalOf, } from "./files.js";
16
16
  export { formOf } from "./form.js";
17
17
  export { areGroups, NotGrouped } from "./groups.js";
18
18
  export { FACT_TONES, historyOf, toneOfFact, } from "./history.js";
@@ -20,9 +20,11 @@ export { addingOf, blankLine, editableLines, isReference, lineFields, lineKey, l
20
20
  export { CHOOSE_MANY, choosesMany, defineList, isList, listingAsk, readListing, scopeOf, trashOf, } from "./list.js";
21
21
  export { lookupOf } from "./lookup.js";
22
22
  export { detailOf, measuresOf, sumsOf, totalOf, } from "./measure.js";
23
- export { BOOKKEEPING, currencyNow, dateStyleNow, dayTextOf, defaultFields, fieldAt, fieldMetaOf, installCurrency, installDateStyle, instantTextOf, moneyTextOf, numberTextOf, shortTextOf, sortKeyOf, STAMPS, textOf, valueAt, viewOf, } from "./present.js";
23
+ export { amountTextOf, BOOKKEEPING, currencyNow, dateStyleNow, dayTextOf, defaultFields, fieldAt, fieldMetaOf, installCurrency, installDateStyle, installRegion, instantTextOf, moneyTextOf, numberTextOf, regionNow, shortTextOf, sortKeyOf, STAMPS, textOf, valueAt, viewOf, } from "./present.js";
24
24
  export { relatedOf } from "./related.js";
25
25
  export { backReference, entityFor, relatedScope, relationFieldOf, } from "./relation.js";
26
+ export { GAP, HANDLE_WIDGET, handleOf, movesFor, placed, reorderingOf, } from "./reorder.js";
27
+ export { holdsRichText, RICH_TEXT_WIDGET, richTextPlainOf, } from "./richText.js";
26
28
  export { readOnServer, readRecordOnServer, } from "./server.js";
27
29
  export { summaryFieldsOf, summaryOf, } from "./summary.js";
28
30
  export { placeOf, stepIn } from "./trail.js";
@@ -70,6 +70,10 @@ export type DateStyle = "numeric" | "literal";
70
70
  export declare function installDateStyle(style: DateStyle | undefined): void;
71
71
  /** The style dates are written in now. */
72
72
  export declare const dateStyleNow: () => DateStyle;
73
+ /** Install the region numbers and money are written in (`"es-BO"`); `undefined` forgets it. */
74
+ export declare function installRegion(code: string | undefined): void;
75
+ /** The region numbers are written in now, if one was installed. */
76
+ export declare const regionNow: () => string | undefined;
73
77
  /**
74
78
  * What a value reads as when a screen holds it outside any model — a total it added up, a
75
79
  * due date of its own: the same text `textOf` gives a field of that type, in `locale`, on the
@@ -96,6 +100,18 @@ export declare function moneyTextOf(value: unknown, locale?: string): string | n
96
100
  export declare function installCurrency(code: string | undefined): void;
97
101
  /** The business's currency now, if one was installed. */
98
102
  export declare const currencyNow: () => string | undefined;
103
+ /**
104
+ * An amount as money, whatever shape it came in: a money (`{ amount, currency }`) in its own
105
+ * currency, a bare amount (`1150.5`, `"1150.50"`) in the business's — a total a use case
106
+ * answered, outside any model. `null` when it is neither.
107
+ *
108
+ * amountTextOf("1150.5", "es") -> "Bs 1.150,50" (BOB installed, region es-BO)
109
+ * amountTextOf({ amount: "3", currency: "USD" }, "es") -> "US$ 3,00"
110
+ *
111
+ * Context: `moneyTextOf` reads only a money, so a panel's «por revisar» — a plain decimal —
112
+ * was wrapped by hand in `{ amount, currency: currencyNow() }` (#42).
113
+ */
114
+ export declare function amountTextOf(value: unknown, locale?: string): string | null;
99
115
  /** A definition of exactly an amount and a currency: a money, whatever the entity calls it. */
100
116
  export declare function isMoneyDefinition(definition: Meta | null | undefined): boolean;
101
117
  /**
@@ -3,6 +3,7 @@ import { choiceLabelOf, labelOf, } from "@sincpro/criteria";
3
3
  import { frameworkCopy } from "./copy.js";
4
4
  import { holdsFile, storedFileOf } from "./files.js";
5
5
  import { relatedOf } from "./related.js";
6
+ import { holdsRichText, richTextPlainOf } from "./richText.js";
6
7
  /** Present when a field is named that the model does not declare: drawn plain, never thrown. */
7
8
  const UNKNOWN = {
8
9
  type: "unknown",
@@ -162,7 +163,24 @@ function dateText(date, locale, withTime) {
162
163
  ? numericDate(date, withTime)
163
164
  : dateFormat(locale, withTime).format(date);
164
165
  }
165
- function numberFormat(locale, kept) {
166
+ /**
167
+ * Where numbers and money are written as the business writes them — `es-BO`: «Bs 1.150,50» —,
168
+ * apart from the language of the words (`es`). Installed once with the zone and the currency
169
+ * (`FrameworkProvider region`); without one, numbers follow the language.
170
+ *
171
+ * Context: with `locale="es"`, `Intl` wrote money as «1150,50 BOB» — Spanish has no region —,
172
+ * and an application could not pass `es-BO` as its locale: labels are read by their exact
173
+ * language key, and every `es` label fell back to the default (#42).
174
+ */
175
+ let region;
176
+ /** Install the region numbers and money are written in (`"es-BO"`); `undefined` forgets it. */
177
+ export function installRegion(code) {
178
+ region = code;
179
+ }
180
+ /** The region numbers are written in now, if one was installed. */
181
+ export const regionNow = () => region;
182
+ function numberFormat(given, kept) {
183
+ const locale = region ?? given;
166
184
  const key = `n|${locale ?? ""}|${kept ?? ""}`;
167
185
  let format = formatters.get(key);
168
186
  if (format === undefined) {
@@ -173,7 +191,8 @@ function numberFormat(locale, kept) {
173
191
  }
174
192
  /** The currency codes `Intl` refused, by locale: asked once, not on every cell. */
175
193
  const unknownCurrencies = new Set();
176
- function currencyFormat(locale, currency) {
194
+ function currencyFormat(given, currency) {
195
+ const locale = region ?? given;
177
196
  const key = `c|${locale ?? ""}|${currency}`;
178
197
  if (unknownCurrencies.has(key))
179
198
  return null;
@@ -285,12 +304,26 @@ export const currencyNow = () => currency;
285
304
  /** A bare amount drawn as money: in the business's currency, or rounded to cents. */
286
305
  function amountText(value, locale) {
287
306
  const amount = typeof value === "number" ? String(value) : value;
288
- if (typeof amount !== "string" || Number.isNaN(Number(amount)))
307
+ if (typeof amount !== "string" || amount.trim() === "" || Number.isNaN(Number(amount)))
289
308
  return null;
290
309
  if (currency !== undefined)
291
310
  return moneyText({ amount, currency }, locale);
292
311
  return numberFormat(locale, 2).format(Number(amount));
293
312
  }
313
+ /**
314
+ * An amount as money, whatever shape it came in: a money (`{ amount, currency }`) in its own
315
+ * currency, a bare amount (`1150.5`, `"1150.50"`) in the business's — a total a use case
316
+ * answered, outside any model. `null` when it is neither.
317
+ *
318
+ * amountTextOf("1150.5", "es") -> "Bs 1.150,50" (BOB installed, region es-BO)
319
+ * amountTextOf({ amount: "3", currency: "USD" }, "es") -> "US$ 3,00"
320
+ *
321
+ * Context: `moneyTextOf` reads only a money, so a panel's «por revisar» — a plain decimal —
322
+ * was wrapped by hand in `{ amount, currency: currencyNow() }` (#42).
323
+ */
324
+ export function amountTextOf(value, locale) {
325
+ return Money.isMoney(value) ? moneyText(value, locale) : amountText(value, locale);
326
+ }
294
327
  /** A definition of exactly an amount and a currency: a money, whatever the entity calls it. */
295
328
  export function isMoneyDefinition(definition) {
296
329
  const parts = Object.keys(definition?.fields ?? {});
@@ -346,6 +379,9 @@ export function textOf(meta, name, value, locale) {
346
379
  // A file reads as the name it was sent with — never its storage key, never its JSON.
347
380
  if (holdsFile(field))
348
381
  return storedFileOf(value)?.name ?? null;
382
+ // Formatted text reads as its words where there is one line: never its tags.
383
+ if (holdsRichText(field) && typeof value === "string")
384
+ return richTextPlainOf(value) || null;
349
385
  // An amount the model draws as money is money, though it travels bare.
350
386
  if (field.widget === "money" && field.kind === "scalar") {
351
387
  const amount = amountText(value, locale);
@@ -382,7 +418,8 @@ export function textOf(meta, name, value, locale) {
382
418
  return typeof value === "object" ? JSON.stringify(value) : String(value);
383
419
  }
384
420
  }
385
- function compactFormat(locale, currency) {
421
+ function compactFormat(given, currency) {
422
+ const locale = region ?? given;
386
423
  const key = `k|${locale ?? ""}|${currency ?? ""}`;
387
424
  let format = formatters.get(key);
388
425
  if (format === undefined) {
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Records put in their order by hand: which field is the position, when the rows on screen may
3
+ * be dragged, and what a drop writes.
4
+ *
5
+ * const reordering = reorderingOf(meta, listing.order); // undefined: no grip
6
+ * const moves = movesFor(rows, keyOf, reordering, "h7", "h2");
7
+ * // [{ id: "h7", value: 1500 }] — one Edit of one record
8
+ *
9
+ * Context: sincpro_framework has no reorder Command and needs none (sincpro_framework#390). The
10
+ * position is a plain integer field the model marks with the widget `handle`
11
+ * (`presentation(widgets=lambda h: {h.orden: "handle"})`), the order comes from the criteria,
12
+ * and a move is one normal `Edit` of the record moved. So the rule lives here, once, read from
13
+ * what the backend publishes — not in each application's screen.
14
+ *
15
+ * WHEN — the active order (the Search's, else the model's `default_order`) holds the handle
16
+ * field ascending. The sorts before it are the GROUP (`album_id,orden`: a photo moves within its
17
+ * album); the ones after it only break ties. Sorted by anything else, the order shown is not the
18
+ * one being changed, and there is no grip.
19
+ *
20
+ * WHAT — the new position goes between its neighbours of the same group, with gaps of `GAP`:
21
+ * halfway when there is room, a gap above the first or below the last. Without room (ties, such
22
+ * as a set never ordered — all `0` —, or neighbours one apart) the group on screen is respaced in
23
+ * its new order: one Edit per row whose value changes. Rare, not atomic, and re-running it
24
+ * converges.
25
+ */
26
+ import { type AnyRecord, type Meta, type Sort } from "@sincpro/criteria";
27
+ /** The widget that marks a field as the record's position by hand. */
28
+ export declare const HANDLE_WIDGET = "handle";
29
+ /** The room left between two positions: a thousand moves between them before a respacing. */
30
+ export declare const GAP = 1000;
31
+ export type Reordering = {
32
+ /** The position field. */
33
+ handle: string;
34
+ /** The fields a row keeps while it moves: it only lands among rows with the same values. */
35
+ group: readonly string[];
36
+ };
37
+ /** One write a drop asks for: the record and its new position. */
38
+ export type Move = {
39
+ id: string;
40
+ value: number;
41
+ };
42
+ /** The field the model marks as the position, if any. */
43
+ export declare function handleOf(meta: Meta | null | undefined): string | undefined;
44
+ /** Whether the rows in `order` (the Search's; empty, the model's own) may be dragged, and
45
+ * within which group. */
46
+ export declare function reorderingOf(meta: Meta | null | undefined, order: readonly Sort[]): Reordering | undefined;
47
+ /**
48
+ * The writes that put `id` in front of `before` (`null`: after the last row) among `rows` — the
49
+ * rows on screen, in their order. `"elsewhere"` when the row would land outside its group;
50
+ * `[]` when it is dropped where it already is.
51
+ *
52
+ * 1. The landing place among the rest of the rows, and its neighbours there.
53
+ * 2. A neighbour of another group does not count; with none of its own, it is elsewhere.
54
+ * 3. Final: halfway between the two, a gap past the one, or — without room — the group respaced.
55
+ */
56
+ export declare function movesFor<T extends AnyRecord>(rows: readonly T[], keyOf: (row: T) => string, { handle, group }: Reordering, id: string, before: string | null): Move[] | "elsewhere";
57
+ /** `rows` with `id` in front of `before` (`null`: the end) — what the screen shows while the
58
+ * writes travel. */
59
+ export declare function placed<T>(rows: readonly T[], keyOf: (row: T) => string, id: string, before: string | null): T[];