@sincpro/web-framework 2.6.0 → 3.1.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 (59) hide show
  1. package/README.md +62 -31
  2. package/dist/core/copy.d.ts +19 -1
  3. package/dist/core/copy.js +36 -0
  4. package/dist/core/explain.d.ts +12 -4
  5. package/dist/core/explain.js +18 -6
  6. package/dist/core/form.d.ts +7 -3
  7. package/dist/core/form.js +11 -5
  8. package/dist/core/groups.d.ts +17 -0
  9. package/dist/core/groups.js +31 -0
  10. package/dist/core/history.d.ts +45 -1
  11. package/dist/core/history.js +84 -12
  12. package/dist/core/index.d.ts +5 -4
  13. package/dist/core/index.js +5 -4
  14. package/dist/core/list.d.ts +14 -16
  15. package/dist/core/list.js +18 -25
  16. package/dist/core/measure.d.ts +14 -5
  17. package/dist/core/measure.js +32 -7
  18. package/dist/core/present.d.ts +51 -3
  19. package/dist/core/present.js +162 -15
  20. package/dist/core/summary.d.ts +6 -2
  21. package/dist/react/context.d.ts +23 -2
  22. package/dist/react/context.js +51 -2
  23. package/dist/react/index.d.ts +2 -1
  24. package/dist/react/index.js +2 -1
  25. package/dist/react/useCommand.d.ts +7 -1
  26. package/dist/react/useCommand.js +12 -2
  27. package/dist/react/useGroups.js +15 -4
  28. package/dist/react/useHistory.d.ts +4 -2
  29. package/dist/react/useHistory.js +20 -5
  30. package/dist/react/usePivot.js +18 -3
  31. package/dist/react/useRecord.d.ts +5 -2
  32. package/dist/react/useRecord.js +14 -2
  33. package/dist/react/useRecordLifecycle.d.ts +43 -0
  34. package/dist/react/useRecordLifecycle.js +49 -0
  35. package/dist/web/Refused.d.ts +3 -3
  36. package/dist/web/Refused.js +3 -3
  37. package/dist/web/index.d.ts +3 -2
  38. package/dist/web/index.js +2 -1
  39. package/dist/web/list/EntityList.js +70 -17
  40. package/dist/web/list/columns.d.ts +6 -1
  41. package/dist/web/list/columns.js +53 -8
  42. package/dist/web/list/presentation.d.ts +20 -1
  43. package/dist/web/list/rowCommands.d.ts +2 -0
  44. package/dist/web/list/rowCommands.js +6 -1
  45. package/dist/web/record/RecordLifecycle.d.ts +23 -0
  46. package/dist/web/record/RecordLifecycle.js +29 -0
  47. package/dist/web/record/RelatedList.d.ts +0 -15
  48. package/dist/web/record/RelatedList.js +35 -6
  49. package/dist/web/record/edit.d.ts +5 -0
  50. package/dist/web/record/edit.js +48 -8
  51. package/dist/web/record/opening.d.ts +2 -2
  52. package/dist/web/record/record.js +5 -2
  53. package/dist/web/workspace/SincproApp.d.ts +10 -1
  54. package/dist/web/workspace/SincproApp.js +18 -4
  55. package/dist/web/workspace/composer.d.ts +1 -1
  56. package/dist/web/workspace/composer.js +3 -4
  57. package/dist/web/workspace/record.d.ts +7 -2
  58. package/dist/web/workspace/record.js +41 -8
  59. package/package.json +6 -6
@@ -1,4 +1,5 @@
1
1
  "use client";
2
+ import { areGroups, NotGrouped } from "../core/groups.js";
2
3
  import { measuresOf, sumsOf } from "../core/measure.js";
3
4
  import { useFramework } from "./context.js";
4
5
  import { useWrites } from "./useWrites.js";
@@ -17,6 +18,8 @@ export function usePivot(listing, axes) {
17
18
  const question = JSON.stringify(asked);
18
19
  const measures = axes?.measures ?? sumsOf(listing.meta);
19
20
  const sums = measures.join(",");
21
+ // Each by the function the model adds it up with (`total`), as text: compared by content.
22
+ const measured = sums === "" ? "" : JSON.stringify(measuresOf(sums.split(","), listing.meta));
20
23
  const shape = axes === null ? "" : JSON.stringify([axes.rows, axes.columns]);
21
24
  const waiting = axes !== null && axes.measures === undefined && listing.meta === null;
22
25
  // Written by anyone — a save, a use case, a panel beside: the crossing is counted again.
@@ -35,7 +38,9 @@ export function usePivot(listing, axes) {
35
38
  ...JSON.parse(question),
36
39
  grouping: {
37
40
  group_by: levels.map((level) => ({ ...level })),
38
- ...(sums === "" ? {} : { measures: measuresOf(sums.split(",")) }),
41
+ ...(measured === ""
42
+ ? {}
43
+ : { measures: JSON.parse(measured) }),
39
44
  pagination: { limit: MAX_KEYS },
40
45
  },
41
46
  pagination: { limit: 1 },
@@ -44,7 +49,17 @@ export function usePivot(listing, axes) {
44
49
  transport.list(listing.route, grouped([rows, columns]), aborter.signal),
45
50
  transport.list(listing.route, grouped([columns]), aborter.signal),
46
51
  ]).then(([crossed, byColumn]) => {
47
- if (!aborter.signal.aborted)
52
+ if (aborter.signal.aborted)
53
+ return;
54
+ // Records answered to a grouped question are not a crossing (`areGroups`).
55
+ if (!areGroups(crossed.rows) || !areGroups(byColumn.rows))
56
+ setState({
57
+ status: "failed",
58
+ crossed: [],
59
+ columns: [],
60
+ error: new NotGrouped(listing.route),
61
+ });
62
+ else
48
63
  setState({
49
64
  status: "ready",
50
65
  crossed: crossed.rows,
@@ -56,6 +71,6 @@ export function usePivot(listing, axes) {
56
71
  setState({ status: "failed", crossed: [], columns: [], error });
57
72
  });
58
73
  return () => aborter.abort();
59
- }, [transport, listing.route, question, shape, sums, waiting, context, writes]);
74
+ }, [transport, listing.route, question, shape, measured, waiting, context, writes]);
60
75
  return { ...state, measures };
61
76
  }
@@ -1,4 +1,4 @@
1
- import { type Draft, type Entity, type EntityRef } from "@sincpro/client-framework";
1
+ import { type Draft, type Entity, type ResourceRef } from "@sincpro/client-framework";
2
2
  import type { AnyRecord, Meta } from "@sincpro/criteria";
3
3
  import { type Advice, type FieldState } from "../core/edit.js";
4
4
  /**
@@ -62,6 +62,9 @@ export type Editing = {
62
62
  changed: AnyRecord;
63
63
  dirty: boolean;
64
64
  set: (name: string, value: unknown) => void;
65
+ /** Whether the entity can store this record at all — `create` for a new one, `edit`/`save`
66
+ * for a stored one. Without it every field is read only (`state`), the hints aside. */
67
+ writable: boolean;
65
68
  state: (name: string) => FieldState;
66
69
  /** A cell of a list of records — line `index` of `name`, its `field`: the line model's hints
67
70
  * over that line, refined by what the server's preview said of it (`items`, by the line's
@@ -101,4 +104,4 @@ export type RecordReading<T> = RecordState<T> & {
101
104
  reload: () => void;
102
105
  edit: Editing;
103
106
  };
104
- export declare function useRecord<T extends AnyRecord>(entity: Entity<T>, opened: string | EntityRef): RecordReading<T>;
107
+ export declare function useRecord<T extends AnyRecord>(entity: Entity<T>, opened: string | ResourceRef): RecordReading<T>;
@@ -161,6 +161,13 @@ export function useRecord(entity, opened) {
161
161
  const byEdit = isNew &&
162
162
  entity.edit !== undefined &&
163
163
  (state.meta?.get_id || state.meta?.identity || "id") === "id";
164
+ // Whether anything can store this record: a new one by `create` (or `Edit` under a minted
165
+ // key), a stored one by `edit`/`save`. A payment or an order that only Commands move has
166
+ // neither — every field of it is read only, whatever the model's hints say: an input nothing
167
+ // can save is an invitation that lies.
168
+ const writable = isNew
169
+ ? byEdit || entity.create !== undefined
170
+ : (entity.edit ?? entity.save) !== undefined;
164
171
  /** The record's key for a write: its own, or the one minted for it while it is new. */
165
172
  const keyNow = () => {
166
173
  if (!byEdit)
@@ -260,11 +267,16 @@ export function useRecord(entity, opened) {
260
267
  setTyped(next);
261
268
  ask(next, name);
262
269
  },
263
- state: (name) => fieldStateOf(state.meta, name, values, fromServer),
270
+ writable,
271
+ state: (name) => {
272
+ const said = fieldStateOf(state.meta, name, values, fromServer);
273
+ return writable ? said : { ...said, readonly: true, required: false };
274
+ },
264
275
  cell: (name, index, field) => {
265
276
  const line = (Array.isArray(values[name]) ? values[name] : [])[index];
266
277
  const definition = state.meta?.fields[name]?.definition;
267
- return fieldStateOf(definition, field, line ?? {}, lineStatesOf(fromServer, name, line, index, definition?.identity || "id"));
278
+ const said = fieldStateOf(definition, field, line ?? {}, lineStatesOf(fromServer, name, line, index, definition?.identity || "id"));
279
+ return writable ? said : { ...said, readonly: true, required: false };
268
280
  },
269
281
  errors: failure instanceof TransportError ? errorsByField(failure.problem?.errors) : {},
270
282
  advice,
@@ -0,0 +1,43 @@
1
+ import type { AnyRecord } from "@sincpro/criteria";
2
+ import { type Rehearsal } from "./useCommand.js";
3
+ import type { RecordReading } from "./useRecord.js";
4
+ /** An action on the record itself — what `RecordLifecycle` draws with `ActionButton`'s gesture:
5
+ * one that destroys can `rehearse` first; one that can be undone runs on the click. It answers
6
+ * `null` when done, `undefined` when refused. */
7
+ export type LifecycleAction = {
8
+ run: () => Promise<null | undefined>;
9
+ rehearse?: () => Promise<Rehearsal | undefined>;
10
+ busy: boolean;
11
+ error: unknown;
12
+ rehearsal: Rehearsal | null;
13
+ reset: () => void;
14
+ };
15
+ /** What the record's entity lets be done to the record itself, each only when declared. */
16
+ export type RecordLifecycleActions = {
17
+ /** sincpro_framework's `Delete`: gone, its fact kept in the history. Rehearsed first. */
18
+ delete?: LifecycleAction;
19
+ /** `Archive`: into the trash — out of every reading, nothing lost. On a record not archived. */
20
+ archive?: LifecycleAction;
21
+ /** `Restore`: out of the trash. On an archived record (`archived_at` set). */
22
+ restore?: LifecycleAction;
23
+ };
24
+ /**
25
+ * The record's own lifecycle, as actions of ONE stored record: what its entity declares of
26
+ * sincpro_framework's `Delete` (`entity.delete`) and its trash (`entity.archive`,
27
+ * `entity.restore`, client-framework 2.0) — `archive` on a record outside the trash, `restore` on
28
+ * one in it (`archived_at` set).
29
+ *
30
+ * const lifecycle = useRecordLifecycle(member);
31
+ * lifecycle.delete?.rehearse() // «Se eliminará Ana Pérez»: nothing touched
32
+ * lifecycle.delete?.run() // null: gone
33
+ *
34
+ * Context: an application wrote a Command and a Feature per aggregate to delete one, and a
35
+ * confirm of its own. The backend publishes the generic `Delete` (3.37): a `DryRunnable` whose
36
+ * dry run answers what would go, refused when the record moved past the version read
37
+ * (`origin_version`), answering nothing. So each action sends the version this screen read and
38
+ * a deletion rehearses with the same body: the confirmation is the server's word on THIS version.
39
+ * Putting a record in the trash, or taking it out, can be undone: it runs on the click. A new
40
+ * record, or one not read yet, has none. Over REST a `DELETE`'s fields travel in its query string
41
+ * (client-framework 1.12): sent in a body, a dry run would run the real delete.
42
+ */
43
+ export declare function useRecordLifecycle<T extends AnyRecord>(record: RecordReading<T>): RecordLifecycleActions;
@@ -0,0 +1,49 @@
1
+ "use client";
2
+ import { useRouteCommand, } from "./useCommand.js";
3
+ /**
4
+ * The record's own lifecycle, as actions of ONE stored record: what its entity declares of
5
+ * sincpro_framework's `Delete` (`entity.delete`) and its trash (`entity.archive`,
6
+ * `entity.restore`, client-framework 2.0) — `archive` on a record outside the trash, `restore` on
7
+ * one in it (`archived_at` set).
8
+ *
9
+ * const lifecycle = useRecordLifecycle(member);
10
+ * lifecycle.delete?.rehearse() // «Se eliminará Ana Pérez»: nothing touched
11
+ * lifecycle.delete?.run() // null: gone
12
+ *
13
+ * Context: an application wrote a Command and a Feature per aggregate to delete one, and a
14
+ * confirm of its own. The backend publishes the generic `Delete` (3.37): a `DryRunnable` whose
15
+ * dry run answers what would go, refused when the record moved past the version read
16
+ * (`origin_version`), answering nothing. So each action sends the version this screen read and
17
+ * a deletion rehearses with the same body: the confirmation is the server's word on THIS version.
18
+ * Putting a record in the trash, or taking it out, can be undone: it runs on the click. A new
19
+ * record, or one not read yet, has none. Over REST a `DELETE`'s fields travel in its query string
20
+ * (client-framework 1.12): sent in a body, a dry run would run the real delete.
21
+ */
22
+ export function useRecordLifecycle(record) {
23
+ const { entity } = record;
24
+ const deletion = useRouteCommand(entity.delete, entity.key);
25
+ const archival = useRouteCommand(entity.archive, entity.key);
26
+ const restoral = useRouteCommand(entity.restore, entity.key);
27
+ const stored = !record.isNew && record.status === "ready";
28
+ if (!stored)
29
+ return {};
30
+ const held = record.record;
31
+ const version = held["version"];
32
+ const checked = typeof version === "number" ? { origin_version: version } : {};
33
+ const archived = held["archived_at"] !== null && held["archived_at"] !== undefined;
34
+ const action = (command, rehearsed) => ({
35
+ run: () => command.run(record.id, checked),
36
+ ...(rehearsed ? { rehearse: () => command.rehearse(record.id, checked) } : {}),
37
+ busy: command.busy,
38
+ error: command.error,
39
+ rehearsal: command.rehearsal,
40
+ reset: command.reset,
41
+ });
42
+ return {
43
+ ...(entity.delete === undefined ? {} : { delete: action(deletion, true) }),
44
+ ...(entity.archive === undefined || archived ? {} : { archive: action(archival, false) }),
45
+ ...(entity.restore === undefined || !archived
46
+ ? {}
47
+ : { restore: action(restoral, false) }),
48
+ };
49
+ }
@@ -1,7 +1,7 @@
1
1
  /**
2
- * A failure, said the way the server said it: its title, what happened and what to do —
3
- * `guidance` included, which is the part a person acts on. Retry only when retrying can help:
4
- * a «you have no access» with a retry button is a button that lies.
2
+ * A failure in the application's words: the copy table's heading for its kind, what the server
3
+ * said happened, and what to do (`explain`). Retry only when retrying can help: a «you have no
4
+ * access» with a retry button is a button that lies.
5
5
  */
6
6
  export declare function Refused({ error, onRetry }: {
7
7
  error: unknown;
@@ -4,9 +4,9 @@ import { frameworkCopy } from "../core/copy.js";
4
4
  import { explain } from "../core/explain.js";
5
5
  import { Button, Failed } from "@sincpro/web-ui";
6
6
  /**
7
- * A failure, said the way the server said it: its title, what happened and what to do —
8
- * `guidance` included, which is the part a person acts on. Retry only when retrying can help:
9
- * a «you have no access» with a retry button is a button that lies.
7
+ * A failure in the application's words: the copy table's heading for its kind, what the server
8
+ * said happened, and what to do (`explain`). Retry only when retrying can help: a «you have no
9
+ * access» with a retry button is a button that lies.
10
10
  */
11
11
  export function Refused({ error, onRetry }) {
12
12
  const { heading, sentence, retryable } = explain(error);
@@ -1,13 +1,13 @@
1
1
  /**
2
2
  * The web bindings: what draws a `Listing` and a record with `@sincpro/web-ui`.
3
3
  */
4
- export { type ColumnOptions, columnsOf } from "./list/columns.js";
4
+ export { aggregateOf, type ColumnOptions, columnsOf, } from "./list/columns.js";
5
5
  export { type EntityFace, EntityList, type EntityListProps, type View, } from "./list/EntityList.js";
6
6
  export { EntitySearchBar } from "./list/EntitySearchBar.js";
7
7
  export { groupableOf, pilesOf } from "./list/groups.js";
8
8
  export { OpenInMenu } from "./list/openIn.js";
9
9
  export { pivotOf } from "./list/pivot.js";
10
- export { type CardLook, type OptionLook, type Presentation, presentationOf, type Presented, presented, type RowLook, } from "./list/presentation.js";
10
+ export { type CardLook, type ChoiceTones, type OptionLook, type Presentation, presentationOf, type Presented, presented, type RowLook, } from "./list/presentation.js";
11
11
  export { type RowCommand, type RowCommands, useRowCommands, } from "./list/rowCommands.js";
12
12
  export { facetsOf, modelOf } from "./list/search.js";
13
13
  export { CommandButton } from "./record/CommandButton.js";
@@ -18,6 +18,7 @@ export { EntityTags } from "./record/EntityTags.js";
18
18
  export { type LineColumn, type LineControl, type LinesLook, RecordLinesEditor, } from "./record/lines.js";
19
19
  export { type RecordOpening, RecordOpeningProvider, useRecordOpening, } from "./record/opening.js";
20
20
  export { countOf, factsOf, RecordLines } from "./record/record.js";
21
+ export { RecordLifecycle } from "./record/RecordLifecycle.js";
21
22
  export { RelatedList } from "./record/RelatedList.js";
22
23
  export { ServiceButton } from "./record/ServiceButton.js";
23
24
  export { cardOf, relationOf } from "./record/summary.js";
package/dist/web/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * The web bindings: what draws a `Listing` and a record with `@sincpro/web-ui`.
3
3
  */
4
- export { columnsOf } from "./list/columns.js";
4
+ export { aggregateOf, columnsOf, } from "./list/columns.js";
5
5
  export { EntityList, } from "./list/EntityList.js";
6
6
  export { EntitySearchBar } from "./list/EntitySearchBar.js";
7
7
  export { groupableOf, pilesOf } from "./list/groups.js";
@@ -18,6 +18,7 @@ export { EntityTags } from "./record/EntityTags.js";
18
18
  export { RecordLinesEditor, } from "./record/lines.js";
19
19
  export { RecordOpeningProvider, useRecordOpening, } from "./record/opening.js";
20
20
  export { countOf, factsOf, RecordLines } from "./record/record.js";
21
+ export { RecordLifecycle } from "./record/RecordLifecycle.js";
21
22
  export { RelatedList } from "./record/RelatedList.js";
22
23
  export { ServiceButton } from "./record/ServiceButton.js";
23
24
  export { cardOf, relationOf } from "./record/summary.js";
@@ -6,6 +6,7 @@ import { RecordLink, useCrumbs, usePhone } from "@sincpro/web-composer";
6
6
  import { frameworkCopy } from "../../core/copy.js";
7
7
  import { explain } from "../../core/explain.js";
8
8
  import { textOf, viewOf } from "../../core/present.js";
9
+ import { summaryFieldsOf } from "../../core/summary.js";
9
10
  import { useFramework } from "../../react/context.js";
10
11
  import { useGroups } from "../../react/useGroups.js";
11
12
  import { usePivot } from "../../react/usePivot.js";
@@ -15,8 +16,9 @@ import { pilesOf } from "./groups.js";
15
16
  import { OpenInMenu, openOptions, targetsFor } from "./openIn.js";
16
17
  import { pivotOf } from "./pivot.js";
17
18
  import { over, presentationOf } from "./presentation.js";
18
- import { useRowCommands } from "./rowCommands.js";
19
+ import { RESTORE, useRowCommands, } from "./rowCommands.js";
19
20
  import { Button, Callout, List, Pagination, pathKey, RecordCard, SearchField, Tag, } from "@sincpro/web-ui";
21
+ import { RotateCcw } from "lucide-react";
20
22
  import { useEffect, useId, useMemo, useRef, useState } from "react";
21
23
  /** What `useCrumbs` reads when the list is not in a workspace: no trail, and nothing to follow. */
22
24
  const NO_TRAIL = [];
@@ -35,7 +37,9 @@ export function EntityList({ listing, api, columns: askedColumns, cells, views:
35
37
  // A named list (`defineList`) brings its own columns, filters, faces and words; what the
36
38
  // screen passes wins.
37
39
  const definition = listing.definition;
38
- const columns = askedColumns ?? definition?.columns;
40
+ // The entity's own look (`presented`): its columns, the tones of its choices, its row and card.
41
+ const look = presentationOf(listing.entity);
42
+ const columns = askedColumns ?? definition?.columns ?? look.columns;
39
43
  const views = askedViews ??
40
44
  definition?.views ??
41
45
  (embedded ? ["table"] : pivotAsked === undefined ? EVERY_VIEW : [...EVERY_VIEW, "pivot"]);
@@ -63,7 +67,7 @@ export function EntityList({ listing, api, columns: askedColumns, cells, views:
63
67
  // Opened by `api.pick` (`entity.chooserRef()`): a row ANSWERS whoever asked, it does not open.
64
68
  const choosing = api?.self.params?.[PICK_PARAM] !== undefined;
65
69
  // The record opened from a row knows the page it came from: «3 / 64» and its neighbours.
66
- const { trails } = useFramework();
70
+ const { trails, dateStyle } = useFramework();
67
71
  const trailKey = `trail:${useId()}`;
68
72
  // Kept current with the page on screen: the row and its name (`RecordLink`) open the same
69
73
  // reference, and whichever opens it, the record finds where it came from.
@@ -139,13 +143,19 @@ export function EntityList({ listing, api, columns: askedColumns, cells, views:
139
143
  const openingNow = useRef(openingIn);
140
144
  openingNow.current = openingIn;
141
145
  const openInOf = (row) => elsewhere.length === 0 || openingIn === undefined ? null : (_jsx(OpenInMenu, { targets: elsewhere, name: idOf(row), onOpen: (to) => openingNow.current?.(row, to) }));
142
- const linked = choosing ||
143
- cells?.[identity] !== undefined ||
144
- (api === undefined && elsewhere.length === 0)
146
+ // The column that names a row carries its link and «Abrir en…»: the identity, or — in a list
147
+ // that does not show it (a relation inside a record) — the record's name, else the first.
148
+ const named = columns === undefined || columns.includes(identity)
149
+ ? identity
150
+ : meta?.display && columns.includes(meta.display)
151
+ ? meta.display
152
+ : (columns[0] ?? identity);
153
+ const rowName = (row) => named === identity ? idOf(row) : (textOf(meta, named, row[named], locale) ?? idOf(row));
154
+ const linked = choosing || cells?.[named] !== undefined || (api === undefined && elsewhere.length === 0)
145
155
  ? cells
146
156
  : {
147
157
  ...cells,
148
- [identity]: (row) => (_jsxs("span", { className: "inline-flex items-center gap-1", children: [api === undefined ? (idOf(row)) : (_jsx(RecordLink, { api: api, resource: refOf(row), children: idOf(row) })), openInOf(row)] })),
158
+ [named]: (row) => (_jsxs("span", { className: "inline-flex items-center gap-1", children: [api === undefined ? (rowName(row)) : (_jsx(RecordLink, { api: api, resource: refOf(row), children: rowName(row) })), openInOf(row)] })),
149
159
  };
150
160
  // `useCrumbs`, not `api.crumbs()`: the crumb must follow a name given later (`setTitle`).
151
161
  // Without a workspace it reads a trail that never changes — a hook cannot be skipped.
@@ -177,16 +187,24 @@ export function EntityList({ listing, api, columns: askedColumns, cells, views:
177
187
  // every cell of the table. `columns` is compared by content (it is usually a literal);
178
188
  // `cells` by identity, since its functions may close over state — memoise it to keep this.
179
189
  const names = columns?.join("\u0000");
180
- const shown = useMemo(() => columnsOf(meta, columns, { locale, ...(linked ? { cells: linked } : {}) }),
190
+ const shown = useMemo(() => columnsOf(meta, columns, {
191
+ locale,
192
+ ...(linked ? { cells: linked } : {}),
193
+ ...(look.tones === undefined ? {} : { tones: look.tones }),
194
+ }),
181
195
  // eslint-disable-next-line react-hooks/exhaustive-deps
182
- [meta, locale, names, cells, api, elsewhere.join(), openingIn === undefined]);
196
+ [meta, locale, names, cells, api, elsewhere.join(), openingIn === undefined, dateStyle]);
197
+ // A state the application gave colours to is the row's tag — and not again among its facts.
198
+ const stateField = summaryFieldsOf(meta, {}, listing.entity.summary).state;
199
+ const stateTones = stateField === undefined ? undefined : look.tones?.[stateField];
183
200
  // A row and a card read the record by its display and the first fields shown beside it.
184
201
  const display = meta?.display || identity;
185
202
  const facts = shown
186
- .filter((c) => c.id !== display && c.id !== identity && !c.defaultHidden)
203
+ .filter((c) => c.id !== display &&
204
+ c.id !== identity &&
205
+ !c.defaultHidden &&
206
+ (stateTones === undefined || c.id !== stateField))
187
207
  .slice(0, 3);
188
- // The entity's own look of a row and a card (`presented`) goes over these defaults.
189
- const look = presentationOf(listing.entity);
190
208
  // The pivot asks the server only while it is the face on screen.
191
209
  const axes = pivotAsked === undefined || present !== "pivot" || !views.includes("pivot")
192
210
  ? null
@@ -229,10 +247,22 @@ export function EntityList({ listing, api, columns: askedColumns, cells, views:
229
247
  const rowOf = (row) => over({
230
248
  name: textOf(meta, display, row[display], locale) ?? idOf(row),
231
249
  meta: [
232
- ...(display === identity ? [] : [idOf(row)]),
250
+ // The key only where the list reads it: one that leaves it out (a relation inside a
251
+ // record) does not print a UUID on every row.
252
+ ...(display === identity || named !== identity ? [] : [idOf(row)]),
233
253
  ...facts.map((c) => textOf(meta, c.id, row[c.id], locale)).filter(Boolean),
234
254
  ].join(" · "),
235
255
  ...(elsewhere.length === 0 ? {} : { actions: openInOf(row) }),
256
+ ...(stateTones === undefined || stateField === undefined
257
+ ? {}
258
+ : (() => {
259
+ const word = textOf(meta, stateField, row[stateField], locale);
260
+ return word === null
261
+ ? {}
262
+ : {
263
+ tags: (_jsx(Tag, { tone: stateTones[String(row[stateField])] ?? "neutral", children: word })),
264
+ };
265
+ })()),
236
266
  }, look.row?.(row));
237
267
  // Without a look of its own, the board's card is web-ui's, made of the row. With one, the
238
268
  // same card — the row's name, meta and tags — under it, and pressing it is still the list's:
@@ -289,9 +319,32 @@ export function EntityList({ listing, api, columns: askedColumns, cells, views:
289
319
  }
290
320
  : {};
291
321
  const records = groups.buckets.reduce((sum, bucket) => sum + bucket.count, 0);
322
+ // The foot adds up what the model says adds up (`total`) — over the rows in hand, never a
323
+ // grouped set (each group says its own, counted by the server). While the rows are not the
324
+ // whole set the list says the figures are this page's (`pageTotals`): the server's total over
325
+ // everything filtered waits on a reading of measures (sincpro_framework, PRD_09).
326
+ const totalled = !grouped &&
327
+ listing.rows.length > 0 &&
328
+ shown.some((column) => column.aggregate !== undefined && !column.defaultHidden);
329
+ const partial = listing.paging === "pages"
330
+ ? page.hasPrev || page.hasNext
331
+ : listing.hasMore || listing.capped;
292
332
  // A row's actions: the entity's Commands, then whatever else the screen offers.
293
- const rowCommands = useRowCommands(listing, commands);
294
- const rowActions = commands.length === 0 && askedRowActions === undefined
333
+ // The trash (`trashOf`): each row is brought back from where it is, with the entity's own
334
+ // `restore` — it can be undone, so it runs on the click; the list reads again after.
335
+ const restoring = listing.definition?.trash === true && listing.entity.restore !== undefined;
336
+ const offered = useMemo(() => restoring
337
+ ? [
338
+ ...commands,
339
+ {
340
+ command: RESTORE,
341
+ label: frameworkCopy().record.restore,
342
+ icon: RotateCcw,
343
+ },
344
+ ]
345
+ : commands, [restoring, commands]);
346
+ const rowCommands = useRowCommands(listing, offered);
347
+ const rowActions = offered.length === 0 && askedRowActions === undefined
295
348
  ? undefined
296
349
  : (row) => [...rowCommands.rowActions(row), ...(askedRowActions?.(row) ?? [])];
297
350
  const refused = rowCommands.error === null ? null : explain(rowCommands.error);
@@ -323,9 +376,9 @@ export function EntityList({ listing, api, columns: askedColumns, cells, views:
323
376
  // Emptied (or cleared with ×): the whole set again, at once.
324
377
  if (next === "" && listing.text !== "")
325
378
  listing.search("", { now: true });
326
- }, onSubmit: (text) => listing.search(text, { now: true }), placeholder: copy.search, "aria-label": copy.search }) })) : null, actions === undefined && creating === undefined ? null : (_jsxs(List.Actions, { children: [actions, creating === undefined ? null : (_jsx(Button, { role: "primary", size: "sm", onClick: creating, children: frameworkCopy().record.create }))] })), _jsxs(List.Pagination, { children: [dropped.length === 0 ? null : (_jsx(Tag, { tone: "warn", title: copy.dropped(dropped), children: copy.dropped(dropped) })), grouped ? (groups.status !== "ready" ? null : (_jsx("span", { className: "text-meta text-muted", children: groups.capped
379
+ }, onSubmit: (text) => listing.search(text, { now: true }), placeholder: copy.search, "aria-label": copy.search }) })) : null, actions === undefined && creating === undefined ? null : (_jsxs(List.Actions, { children: [actions, creating === undefined ? null : (_jsx(Button, { role: "primary", size: "sm", onClick: creating, children: frameworkCopy().record.create }))] })), _jsxs(List.Pagination, { children: [totalled && partial && present === "table" ? (_jsx("span", { className: "text-meta text-muted", children: copy.pageTotals })) : null, dropped.length === 0 ? null : (_jsx(Tag, { tone: "warn", title: copy.dropped(dropped), children: copy.dropped(dropped) })), grouped ? (groups.status !== "ready" ? null : (_jsx("span", { className: "text-meta text-muted", children: groups.capped
327
380
  ? copy.groupsCapped(groups.buckets.length)
328
- : copy.groups(groups.buckets.length, records) }))) : listing.paging === "pages" ? (page.from === 0 ? null : (_jsx(Pagination, { from: page.from, to: page.to, total: count?.value ?? page.to, ...(page.hasPrev ? { onPrev: listing.prev } : {}), ...(page.hasNext ? { onNext: listing.next } : {}) }))) : (_jsxs(_Fragment, { children: [count === null ? null : (_jsx("span", { className: "text-meta text-muted", children: copy.shown(listing.rows.length, count.value, count.exact) })), listing.capped ? (_jsx("span", { className: "text-meta text-muted", children: copy.capped(listing.rows.length) })) : listing.hasMore ? (_jsx(Button, { size: "sm", role: "secondary", disabled: listing.status === "loadingMore", onClick: listing.more, children: listing.status === "loadingMore" ? copy.loading : copy.loadMore })) : null] }))] })] }), views.includes("table") ? (_jsx(List.Table, { columns: shown, ...(rowActions === undefined ? {} : { rowActions }) })) : null, _jsx(List.Rows, { row: rowOf }), views.includes("sheet") ? (_jsx(List.Sheet, { columns: sheetColumns, cell: (row, column) => {
381
+ : copy.groups(groups.buckets.length, records) }))) : listing.paging === "pages" ? (page.from === 0 ? null : (_jsx(Pagination, { from: page.from, to: page.to, total: count?.value ?? page.to, ...(page.hasPrev ? { onPrev: listing.prev } : {}), ...(page.hasNext ? { onNext: listing.next } : {}) }))) : (_jsxs(_Fragment, { children: [count === null ? null : (_jsx("span", { className: "text-meta text-muted", children: copy.shown(listing.rows.length, count.value, count.exact) })), listing.capped ? (_jsx("span", { className: "text-meta text-muted", children: copy.capped(listing.rows.length) })) : listing.hasMore ? (_jsx(Button, { size: "sm", role: "secondary", disabled: listing.status === "loadingMore", onClick: listing.more, children: listing.status === "loadingMore" ? copy.loading : copy.loadMore })) : null] }))] })] }), views.includes("table") ? (_jsx(List.Table, { columns: shown, ...(totalled ? { totals: true } : {}), ...(rowActions === undefined ? {} : { rowActions }) })) : null, _jsx(List.Rows, { row: rowOf }), views.includes("sheet") ? (_jsx(List.Sheet, { columns: sheetColumns, cell: (row, column) => {
329
382
  const value = row[column.id];
330
383
  return value === null || value === undefined
331
384
  ? null
@@ -1,9 +1,14 @@
1
1
  import type { AnyRecord, Meta } from "@sincpro/criteria";
2
- import type { DataColumn } from "@sincpro/web-ui";
2
+ import type { ChoiceTones } from "./presentation.js";
3
+ import { type Aggregate, type DataColumn } from "@sincpro/web-ui";
3
4
  import type { ReactNode } from "react";
4
5
  export type ColumnOptions<T> = {
5
6
  locale?: string | undefined;
6
7
  /** The cells that are not plain text, by field name. */
7
8
  cells?: Readonly<Partial<Record<string, (row: T) => ReactNode>>>;
9
+ /** The colour of each value of a choice (`presented(entity, { tones })`). */
10
+ tones?: ChoiceTones<T> | undefined;
8
11
  };
12
+ /** How the model adds a field up at a list's foot, as web-ui's `aggregate`. */
13
+ export declare function aggregateOf(meta: Meta | null | undefined, name: string): Aggregate | undefined;
9
14
  export declare function columnsOf<T extends AnyRecord>(meta: Meta | null | undefined, names?: readonly string[], options?: ColumnOptions<T>): DataColumn<T>[];
@@ -1,5 +1,9 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
- import { BOOKKEEPING, defaultFields, sortKeyOf, textOf, viewOf, } from "../../core/present.js";
2
+ import { frameworkCopy } from "../../core/copy.js";
3
+ import { totalOf } from "../../core/measure.js";
4
+ import { BOOKKEEPING, defaultFields, fieldMetaOf, sortKeyOf, textOf, valueAt, viewOf, } from "../../core/present.js";
5
+ import { Tag } from "@sincpro/web-ui";
6
+ import { Check } from "lucide-react";
3
7
  /**
4
8
  * The columns of a table, from the model: name the fields, the rest follows.
5
9
  *
@@ -7,32 +11,73 @@ import { BOOKKEEPING, defaultFields, sortKeyOf, textOf, viewOf, } from "../../co
7
11
  * p.display_name`, a date formatter per screen — while the server already said what each field
8
12
  * is called and what type it holds. Here a column is a NAME: its header is the model's label,
9
13
  * its cell the text the value reads as (`textOf`), its sort key the raw value, and whether it
10
- * can be ordered is what the server said (`sortable`). A cell that needs more than text — a
11
- * link, a tag — is the one thing a screen writes (`cells`).
14
+ * can be ordered is what the server said (`sortable`). A cell is drawn by its TYPE: a choice is a
15
+ * tag in the tone the application declared for its value (`presented(entity, { tones })`), a
16
+ * yes/no a check, an amount the model draws as money is money. A cell that needs more — a link,
17
+ * a figure of its own — is the one thing a screen writes (`cells`).
18
+ *
19
+ * A column the model adds up at a list's foot (`total`: `sum`, `avg`, `min`, `max`) declares it
20
+ * (`aggregate`), with its own format: the foot reads «Bs 1.204,50» like the cells above it.
12
21
  *
13
22
  * The fields NOT named still exist: they come after, `optional` and hidden, so the columns
14
23
  * menu offers them and nobody edits the screen to see a field the server already sends.
15
24
  */
16
25
  /** The types whose value is one short thing, read whole. */
17
26
  const DATES = new Set(["date", "datetime", "time"]);
27
+ /** The model's `total` as web-ui's aggregate. */
28
+ const AGGREGATES = {
29
+ sum: "sum",
30
+ avg: "mean",
31
+ min: "min",
32
+ max: "max",
33
+ };
34
+ /** How the model adds a field up at a list's foot, as web-ui's `aggregate`. */
35
+ export function aggregateOf(meta, name) {
36
+ const total = totalOf(meta, name);
37
+ return total === undefined ? undefined : AGGREGATES[total];
38
+ }
18
39
  function columnOf(meta, name, options, hidden) {
19
40
  const view = viewOf(meta, name, options.locale);
20
- const text = (row) => textOf(meta, name, row[name], options.locale) ?? "";
41
+ const field = fieldMetaOf(meta, name);
42
+ const raw = (row) => valueAt(meta, row, name);
43
+ const text = (row) => textOf(meta, name, raw(row), options.locale) ?? "";
21
44
  const own = options.cells?.[name];
22
45
  // A code, a date, an amount is read whole: «F-2026-0060» in three lines is three values.
23
- const whole = view.name === meta?.identity || view.numeric || DATES.has(view.type);
46
+ const money = field?.widget === "money";
47
+ const whole = view.name === meta?.identity || view.numeric || money || DATES.has(view.type);
48
+ const tones = options.tones?.[name];
49
+ const choice = (field?.choices?.length ?? 0) > 0;
50
+ const aggregate = aggregateOf(meta, name);
24
51
  return {
25
52
  id: name,
26
53
  header: view.label,
27
54
  field: name,
28
- value: (row) => sortKeyOf(meta, name, row[name]),
55
+ value: (row) => sortKeyOf(meta, name, raw(row)),
29
56
  cell: own ??
30
- (whole ? (row) => _jsx("span", { className: "whitespace-nowrap", children: text(row) }) : text),
57
+ (choice
58
+ ? // A state reads at a glance: its word in a tag, in the tone the application gave it.
59
+ (row) => {
60
+ const word = text(row);
61
+ return word === "" ? null : (_jsx(Tag, { tone: tones?.[String(raw(row))] ?? "neutral", children: word }));
62
+ }
63
+ : view.type === "boolean"
64
+ ? // A yes is a check and a no is nothing: a column of «sí/no» is noise to scan.
65
+ (row) => raw(row) === true ? (_jsx(Check, { role: "img", "aria-label": frameworkCopy().value.yes, className: "size-(--size-icon-sm)" })) : null
66
+ : whole
67
+ ? (row) => _jsx("span", { className: "whitespace-nowrap", children: text(row) })
68
+ : text),
31
69
  text,
32
- numeric: view.numeric,
70
+ numeric: view.numeric || money,
33
71
  sortable: view.sortable,
34
72
  ...(view.name === meta?.identity ? { mono: true } : {}),
35
73
  ...(hidden ? { optional: true, defaultHidden: true } : {}),
74
+ ...(aggregate === undefined
75
+ ? {}
76
+ : {
77
+ aggregate,
78
+ // The foot reads as the cells above it: «Bs 1.204,50», not «1204.5».
79
+ format: (value) => textOf(meta, name, value, options.locale) ?? String(value),
80
+ }),
36
81
  };
37
82
  }
38
83
  export function columnsOf(meta, names, options = {}) {
@@ -1,7 +1,7 @@
1
1
  import { type CommandAnswers, type CommandBodies, type Entity } from "@sincpro/client-framework";
2
2
  import type { AnyRecord } from "@sincpro/criteria";
3
3
  import { type ListDefinition } from "../../core/list.js";
4
- import type { PickerItem, RecordCard, RowOf } from "@sincpro/web-ui";
4
+ import type { PickerItem, RecordCard, RowOf, Tone } from "@sincpro/web-ui";
5
5
  import type { ComponentProps } from "react";
6
6
  /**
7
7
  * How a record of an entity looks at each size — a choice, a row, a card — declared ONCE with
@@ -35,10 +35,29 @@ export type OptionLook = Partial<Omit<PickerItem, "id">>;
35
35
  export type RowLook = Partial<RowOf>;
36
36
  /** The board's card. Opening it stays the list's: `onOpen` is not the presentation's. */
37
37
  export type CardLook = Partial<Omit<ComponentProps<typeof RecordCard>, "onOpen">>;
38
+ /** The colour of each value of a choice, by field and by value as text (the Meta's own keys):
39
+ * `{ estado: { APROBADO: "good", RECHAZADO: "bad" } }`. */
40
+ export type ChoiceTones<T> = Readonly<Partial<Record<keyof T & string, Readonly<Record<string, Tone>>>>>;
38
41
  export type Presentation<T> = {
39
42
  option?: (record: T) => OptionLook;
40
43
  row?: (record: T) => RowLook;
41
44
  card?: (record: T) => CardLook;
45
+ /**
46
+ * The colour of each value of a choice — a state, a priority. Declared once here and used
47
+ * wherever the framework draws the value: a table's cell, a row's and a card's tag, the tag of
48
+ * the record's header. A value with no tone is a neutral tag; the word is always the Meta's.
49
+ *
50
+ * Context: which colour «Rechazado» is, is the client's decision — the backend says what a
51
+ * value is called, never how it looks — and nothing here held it: every application kept a
52
+ * dictionary per state and passed it to its rows, its record and its cells by hand.
53
+ */
54
+ tones?: ChoiceTones<T>;
55
+ /** The colour of each kind of fact in its history, by its `name` — whole, or its last part
56
+ * (`pago_aprobado`) — over the framework's own (`FACT_TONES`). */
57
+ facts?: Readonly<Record<string, Tone>>;
58
+ /** The fields a table of its records shows when the screen names none — on its own list and
59
+ * inside another record (a one2many) alike. Without it, every field but the stamps. */
60
+ columns?: readonly (keyof T & string)[];
42
61
  };
43
62
  export type Presented<T extends AnyRecord, C extends CommandBodies = CommandBodies, A extends CommandAnswers = CommandAnswers> = Entity<T, C, A> & {
44
63
  readonly presentation: Presentation<T>;
@@ -36,6 +36,8 @@ export type RowCommand<T, C extends CommandBodies = CommandBodies> = {
36
36
  body?: (row: T) => C[N];
37
37
  };
38
38
  }[keyof C & string];
39
+ /** The row action of the trash (`trashOf`): the entity's `restore` route, run from the row. */
40
+ export declare const RESTORE = "restore";
39
41
  export type RowCommands<T> = {
40
42
  rowActions: (row: T) => readonly RowAction[];
41
43
  /** The last refusal, until `dismiss`. */
@@ -3,6 +3,8 @@ import { bodyFor, pathFor, retryKeys } from "@sincpro/client-framework";
3
3
  import { matches } from "@sincpro/criteria";
4
4
  import { useFramework } from "../../react/context.js";
5
5
  import { useCallback, useState } from "react";
6
+ /** The row action of the trash (`trashOf`): the entity's `restore` route, run from the row. */
7
+ export const RESTORE = "restore";
6
8
  export function useRowCommands(listing, commands) {
7
9
  const { transport } = useFramework();
8
10
  const [running, setRunning] = useState(new Set());
@@ -12,7 +14,10 @@ export function useRowCommands(listing, commands) {
12
14
  const { entity, meta } = listing;
13
15
  const key = meta?.get_id || meta?.identity || "id";
14
16
  const run = useCallback(async (one, row) => {
15
- const route = entity.commands[one.command];
17
+ // «Restore» on a row of the trash runs the entity's own `restore` route (`trashOf`), unless
18
+ // the entity declares a Command of that name.
19
+ const route = entity.commands[one.command] ??
20
+ (one.command === RESTORE ? entity.restore : undefined);
16
21
  if (route === undefined)
17
22
  throw new Error(`${entity.key} declares no command "${one.command}"`);
18
23
  const id = String(row[key]);