@sincpro/web-framework 3.0.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 (44) hide show
  1. package/README.md +29 -0
  2. package/dist/core/copy.d.ts +11 -1
  3. package/dist/core/copy.js +28 -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 +41 -4
  11. package/dist/core/history.js +79 -12
  12. package/dist/core/index.d.ts +4 -3
  13. package/dist/core/index.js +4 -3
  14. package/dist/core/measure.d.ts +14 -5
  15. package/dist/core/measure.js +32 -7
  16. package/dist/core/present.d.ts +51 -3
  17. package/dist/core/present.js +162 -15
  18. package/dist/core/summary.d.ts +6 -2
  19. package/dist/react/context.d.ts +23 -2
  20. package/dist/react/context.js +51 -2
  21. package/dist/react/useGroups.js +15 -4
  22. package/dist/react/useHistory.d.ts +4 -2
  23. package/dist/react/useHistory.js +20 -5
  24. package/dist/react/usePivot.js +18 -3
  25. package/dist/react/useRecord.d.ts +3 -0
  26. package/dist/react/useRecord.js +14 -2
  27. package/dist/web/Refused.d.ts +3 -3
  28. package/dist/web/Refused.js +3 -3
  29. package/dist/web/index.d.ts +2 -2
  30. package/dist/web/index.js +1 -1
  31. package/dist/web/list/EntityList.js +53 -14
  32. package/dist/web/list/columns.d.ts +6 -1
  33. package/dist/web/list/columns.js +53 -8
  34. package/dist/web/list/presentation.d.ts +20 -1
  35. package/dist/web/record/RelatedList.d.ts +0 -15
  36. package/dist/web/record/RelatedList.js +35 -6
  37. package/dist/web/record/edit.d.ts +5 -0
  38. package/dist/web/record/edit.js +48 -8
  39. package/dist/web/record/record.js +5 -2
  40. package/dist/web/workspace/SincproApp.d.ts +10 -1
  41. package/dist/web/workspace/SincproApp.js +18 -4
  42. package/dist/web/workspace/record.d.ts +7 -2
  43. package/dist/web/workspace/record.js +31 -6
  44. package/package.json +6 -6
@@ -1,6 +1,6 @@
1
1
  "use client";
2
2
  import { listRoute } from "@sincpro/client-framework";
3
- import { historyOf } from "../core/history.js";
3
+ import { historyOf, } from "../core/history.js";
4
4
  import { useFramework } from "./context.js";
5
5
  import { useWrites } from "./useWrites.js";
6
6
  import { useEffect, useState } from "react";
@@ -14,12 +14,22 @@ import { useEffect, useState } from "react";
14
14
  * says «nothing happened», which is a different claim from «you may not see it». Pass the
15
15
  * record among `deps` so a write that reloads it reads its new facts too.
16
16
  *
17
+ * Each side of an edit is written by the record's own model when it is known (`metas`), and
18
+ * each kind of fact takes the tone `tones` gives its `name` (`presented(entity, { facts })`).
19
+ *
17
20
  * Named after sincpro_framework's `history_of`; web-ui's `useActivity` is something else (the
18
21
  * panel's open state).
19
22
  */
20
23
  const SHOWN = 100;
21
- export function useHistory(entity, id, deps = []) {
22
- const { transport, locale, context } = useFramework();
24
+ export function useHistory(entity, id, deps = [], options = {}) {
25
+ const { transport, locale, context, metas, events, dateStyle, currency } = useFramework();
26
+ const tones = options.tones;
27
+ // By content: a screen passes its tones as a literal, a new object on every render.
28
+ const toned = tones === undefined ? "" : JSON.stringify(tones);
29
+ // By the events it names: an application that builds them inline must not read it again.
30
+ const named = Object.keys(events).join("|");
31
+ // How its texts are written: another tone, event, date style or currency writes them again.
32
+ const written = `${toned}\u0000${named}\u0000${dateStyle}\u0000${currency ?? ""}`;
23
33
  const [entries, setEntries] = useState(undefined);
24
34
  const history = entity.history;
25
35
  // A write under the record — anyone's — adds a fact to its history: read it again.
@@ -34,9 +44,14 @@ export function useHistory(entity, id, deps = []) {
34
44
  order: [{ field: "created_at", descending: true }],
35
45
  pagination: { limit: SHOWN },
36
46
  };
37
- transport.list(listRoute(history, { id }), criteria, aborter.signal).then((page) => aborter.signal.aborted || setEntries(historyOf(page.rows, page.meta, locale)), () => aborter.signal.aborted || setEntries(undefined));
47
+ transport.list(listRoute(history, { id }), criteria, aborter.signal).then((page) => aborter.signal.aborted ||
48
+ setEntries(historyOf(page.rows, page.meta, locale, {
49
+ record: metas.get(entity.key),
50
+ events,
51
+ tones,
52
+ })), () => aborter.signal.aborted || setEntries(undefined));
38
53
  return () => aborter.abort();
39
54
  // eslint-disable-next-line react-hooks/exhaustive-deps -- the caller names what reloads it
40
- }, [transport, history, id, locale, context, writes, ...deps]);
55
+ }, [transport, history, id, locale, context, writes, written, ...deps]);
41
56
  return entries;
42
57
  }
@@ -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
  }
@@ -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
@@ -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,
@@ -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";
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";
@@ -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";
@@ -36,7 +37,9 @@ export function EntityList({ listing, api, columns: askedColumns, cells, views:
36
37
  // A named list (`defineList`) brings its own columns, filters, faces and words; what the
37
38
  // screen passes wins.
38
39
  const definition = listing.definition;
39
- 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;
40
43
  const views = askedViews ??
41
44
  definition?.views ??
42
45
  (embedded ? ["table"] : pivotAsked === undefined ? EVERY_VIEW : [...EVERY_VIEW, "pivot"]);
@@ -64,7 +67,7 @@ export function EntityList({ listing, api, columns: askedColumns, cells, views:
64
67
  // Opened by `api.pick` (`entity.chooserRef()`): a row ANSWERS whoever asked, it does not open.
65
68
  const choosing = api?.self.params?.[PICK_PARAM] !== undefined;
66
69
  // The record opened from a row knows the page it came from: «3 / 64» and its neighbours.
67
- const { trails } = useFramework();
70
+ const { trails, dateStyle } = useFramework();
68
71
  const trailKey = `trail:${useId()}`;
69
72
  // Kept current with the page on screen: the row and its name (`RecordLink`) open the same
70
73
  // reference, and whichever opens it, the record finds where it came from.
@@ -140,13 +143,19 @@ export function EntityList({ listing, api, columns: askedColumns, cells, views:
140
143
  const openingNow = useRef(openingIn);
141
144
  openingNow.current = openingIn;
142
145
  const openInOf = (row) => elsewhere.length === 0 || openingIn === undefined ? null : (_jsx(OpenInMenu, { targets: elsewhere, name: idOf(row), onOpen: (to) => openingNow.current?.(row, to) }));
143
- const linked = choosing ||
144
- cells?.[identity] !== undefined ||
145
- (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)
146
155
  ? cells
147
156
  : {
148
157
  ...cells,
149
- [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)] })),
150
159
  };
151
160
  // `useCrumbs`, not `api.crumbs()`: the crumb must follow a name given later (`setTitle`).
152
161
  // Without a workspace it reads a trail that never changes — a hook cannot be skipped.
@@ -178,16 +187,24 @@ export function EntityList({ listing, api, columns: askedColumns, cells, views:
178
187
  // every cell of the table. `columns` is compared by content (it is usually a literal);
179
188
  // `cells` by identity, since its functions may close over state — memoise it to keep this.
180
189
  const names = columns?.join("\u0000");
181
- 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
+ }),
182
195
  // eslint-disable-next-line react-hooks/exhaustive-deps
183
- [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];
184
200
  // A row and a card read the record by its display and the first fields shown beside it.
185
201
  const display = meta?.display || identity;
186
202
  const facts = shown
187
- .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))
188
207
  .slice(0, 3);
189
- // The entity's own look of a row and a card (`presented`) goes over these defaults.
190
- const look = presentationOf(listing.entity);
191
208
  // The pivot asks the server only while it is the face on screen.
192
209
  const axes = pivotAsked === undefined || present !== "pivot" || !views.includes("pivot")
193
210
  ? null
@@ -230,10 +247,22 @@ export function EntityList({ listing, api, columns: askedColumns, cells, views:
230
247
  const rowOf = (row) => over({
231
248
  name: textOf(meta, display, row[display], locale) ?? idOf(row),
232
249
  meta: [
233
- ...(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)]),
234
253
  ...facts.map((c) => textOf(meta, c.id, row[c.id], locale)).filter(Boolean),
235
254
  ].join(" · "),
236
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
+ })()),
237
266
  }, look.row?.(row));
238
267
  // Without a look of its own, the board's card is web-ui's, made of the row. With one, the
239
268
  // same card — the row's name, meta and tags — under it, and pressing it is still the list's:
@@ -290,6 +319,16 @@ export function EntityList({ listing, api, columns: askedColumns, cells, views:
290
319
  }
291
320
  : {};
292
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;
293
332
  // A row's actions: the entity's Commands, then whatever else the screen offers.
294
333
  // The trash (`trashOf`): each row is brought back from where it is, with the entity's own
295
334
  // `restore` — it can be undone, so it runs on the click; the list reads again after.
@@ -337,9 +376,9 @@ export function EntityList({ listing, api, columns: askedColumns, cells, views:
337
376
  // Emptied (or cleared with ×): the whole set again, at once.
338
377
  if (next === "" && listing.text !== "")
339
378
  listing.search("", { now: true });
340
- }, 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
341
380
  ? copy.groupsCapped(groups.buckets.length)
342
- : 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) => {
343
382
  const value = row[column.id];
344
383
  return value === null || value === undefined
345
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>;
@@ -2,21 +2,6 @@ import { type Entity } from "@sincpro/client-framework";
2
2
  import type { AnyRecord } from "@sincpro/criteria";
3
3
  import type { RecordReading } from "../../react/useRecord.js";
4
4
  import { type EntityListProps } from "../list/EntityList.js";
5
- /**
6
- * A relation of a record as a list inside it — searched, ordered and paged by the server.
7
- *
8
- * Context: the same `EntityList` a screen uses, `embedded` so it reads as a field of the record
9
- * (a one-line bar that does not stick), over `useRelated`. Its search box fills the RELATED
10
- * entity's own search template: the lines of an order are searched by product, the invoices of
11
- * a customer by number. The column that points back to this record is left out — it is the
12
- * same on every row. Use `RecordLines` when the page the record brought is all there is.
13
- *
14
- * «Agregar» opens the form of a new related record already pointing back here, where the view
15
- * says (`RecordOpening.create`: a modal that answers, in a workspace), and the list is read
16
- * again once it exists. Never a row of the table: each one is an aggregate with its own create,
17
- * rules and preview. There is none while this record does not exist yet — there is nothing to
18
- * point back to — nor when the relation is read only or the entity cannot be created.
19
- */
20
5
  export declare function RelatedList<P extends AnyRecord, T extends AnyRecord>({ record, name, entity, pageSize, ...list }: {
21
6
  record: RecordReading<P>;
22
7
  name: string;
@@ -2,13 +2,15 @@
2
2
  import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
3
3
  import {} from "@sincpro/client-framework";
4
4
  import { frameworkCopy } from "../../core/copy.js";
5
- import { defaultFields } from "../../core/present.js";
5
+ import { fieldStateOf } from "../../core/edit.js";
6
+ import { defaultFields, STAMPS } from "../../core/present.js";
6
7
  import { backReference, isKeyValue } from "../../core/relation.js";
7
8
  import { useRelated } from "../../react/useRelated.js";
8
9
  import { EntityList } from "../list/EntityList.js";
10
+ import { presentationOf } from "../list/presentation.js";
9
11
  import { useRecordOpening } from "./opening.js";
10
12
  import { Button } from "@sincpro/web-ui";
11
- import { useMemo } from "react";
13
+ import { useMemo, useRef } from "react";
12
14
  /**
13
15
  * A relation of a record as a list inside it — searched, ordered and paged by the server.
14
16
  *
@@ -18,12 +20,20 @@ import { useMemo } from "react";
18
20
  * a customer by number. The column that points back to this record is left out — it is the
19
21
  * same on every row. Use `RecordLines` when the page the record brought is all there is.
20
22
  *
23
+ * It reads as a part of the record, not as a screen: its columns are the related entity's own
24
+ * (`presented(entity, { columns })`), else its fields without the framework's stamps (created,
25
+ * updated, version) and without a key nobody reads (a UUID identity that is not its name); and a
26
+ * relation of ten records or fewer has no search bar — three dues of a payment are read, not
27
+ * searched. A screen that wants them passes `columns` / `search`.
28
+ *
21
29
  * «Agregar» opens the form of a new related record already pointing back here, where the view
22
30
  * says (`RecordOpening.create`: a modal that answers, in a workspace), and the list is read
23
31
  * again once it exists. Never a row of the table: each one is an aggregate with its own create,
24
32
  * rules and preview. There is none while this record does not exist yet — there is nothing to
25
33
  * point back to — nor when the relation is read only or the entity cannot be created.
26
34
  */
35
+ /** As many related records as are read at a glance — a picker opens with as many. */
36
+ const SHORT = 10;
27
37
  export function RelatedList({ record, name, entity, pageSize, ...list }) {
28
38
  const listing = useRelated(record, name, entity, pageSize === undefined ? {} : { pageSize });
29
39
  const opening = useRecordOpening();
@@ -33,10 +43,24 @@ export function RelatedList({ record, name, entity, pageSize, ...list }) {
33
43
  const pointing = backReference(record.record, record.meta?.fields[name], identity);
34
44
  const back = pointing?.field;
35
45
  const own = list.columns;
46
+ const look = presentationOf(entity).columns;
47
+ const meta = listing.meta;
36
48
  const columns = useMemo(() => own ??
37
- (listing.meta === null || !back
49
+ look?.filter((field) => field !== back) ??
50
+ (meta === null
38
51
  ? undefined
39
- : defaultFields(listing.meta).filter((field) => field !== back)), [own, listing.meta, back]);
52
+ : defaultFields(meta).filter((field) => field !== back &&
53
+ !STAMPS.has(field) &&
54
+ // The identity is a column only when it is the record's name (a code, a number).
55
+ (field !== meta.identity || meta.display === field || !meta.display))), [own, look, meta, back]);
56
+ // A relation of a few records is read whole; the bar comes once there is more to find, and
57
+ // stays: a search that narrowed it to one must not take away the bar that undoes it.
58
+ const long = listing.count !== null &&
59
+ (!listing.count.exact || listing.count.value > Math.min(SHORT, listing.page.size));
60
+ const searching = listing.text !== "" || listing.selection !== undefined;
61
+ const barred = useRef(false);
62
+ if (long || searching)
63
+ barred.current = true;
40
64
  const create = opening?.create;
41
65
  // The value the rows point back with.
42
66
  const here = pointing?.value;
@@ -45,8 +69,13 @@ export function RelatedList({ record, name, entity, pageSize, ...list }) {
45
69
  !back ||
46
70
  record.isNew ||
47
71
  !isKeyValue(here) ||
48
- record.edit.state(name).readonly ? null : (_jsx(Button, { size: "sm", role: "secondary", onClick: () => create(entity, { [back]: here }, listing.reload), children: frameworkCopy().record.add }));
49
- return (_jsx(EntityList, { listing: listing, embedded: true, ...list, ...(columns === undefined ? {} : { columns }), ...(adding === null && list.actions === undefined
72
+ // The relation's own hint — not whether THIS record can be written: adding stores another
73
+ // record (a customer only Commands move still gets new invoices).
74
+ fieldStateOf(record.meta, name, record.edit.values).readonly ? null : (_jsx(Button, { size: "sm", role: "secondary", onClick: () => create(entity, { [back]: here }, listing.reload), children: frameworkCopy().record.add }));
75
+ return (_jsx(EntityList, { listing: listing, embedded: true,
76
+ // The bar, not a box: a relation of records is searched like any list of records —
77
+ // named filters, the criteria builder, grouping. A screen that wants a box passes one.
78
+ search: barred.current ? "bar" : false, ...list, ...(columns === undefined ? {} : { columns }), ...(adding === null && list.actions === undefined
50
79
  ? {}
51
80
  : {
52
81
  actions: (_jsxs(_Fragment, { children: [list.actions, adding] })),
@@ -26,9 +26,14 @@ import type { ReactNode } from "react";
26
26
  * A one2many is a block: its lines (`lines`) or its related list (`list`), each with every piece
27
27
  * replaceable the screen's way.
28
28
  *
29
+ * A value the record embeds (a payment's receipt) is drawn from its definition: `name="recibo"`
30
+ * is a section of its fields, and `name="recibo.numero"` is one of them — its label and type the
31
+ * definition's, read only when the embedded value is, and written back into the value whole.
32
+ *
29
33
  * <RecordField record={invoice} name="due_date" />
30
34
  * <RecordField record={invoice} name="customer_id" />
31
35
  * <RecordField record={invoice} name="lines" lines={{ controls: { qty: Stepper } }} />
36
+ * <RecordField record={pago} name="recibo.numero" />
32
37
  */
33
38
  export declare function RecordField<T extends Record<string, unknown>>({ record, name, as, bare, lines: look, list: listed, }: {
34
39
  record: RecordReading<T>;