@sincpro/web-framework 3.0.0 → 3.2.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 (62) hide show
  1. package/README.md +29 -0
  2. package/dist/core/copy.d.ts +13 -1
  3. package/dist/core/copy.js +30 -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/list.d.ts +3 -0
  15. package/dist/core/measure.d.ts +14 -5
  16. package/dist/core/measure.js +32 -7
  17. package/dist/core/present.d.ts +51 -3
  18. package/dist/core/present.js +162 -15
  19. package/dist/core/summary.d.ts +6 -2
  20. package/dist/react/context.d.ts +26 -2
  21. package/dist/react/context.js +56 -2
  22. package/dist/react/useGroups.js +15 -4
  23. package/dist/react/useHistory.d.ts +4 -2
  24. package/dist/react/useHistory.js +20 -5
  25. package/dist/react/usePivot.js +18 -3
  26. package/dist/react/useRecord.d.ts +3 -0
  27. package/dist/react/useRecord.js +14 -2
  28. package/dist/web/Refused.d.ts +3 -3
  29. package/dist/web/Refused.js +3 -3
  30. package/dist/web/index.d.ts +3 -2
  31. package/dist/web/index.js +2 -1
  32. package/dist/web/list/EntityList.d.ts +4 -1
  33. package/dist/web/list/EntityList.js +69 -21
  34. package/dist/web/list/EntitySearchBar.d.ts +6 -2
  35. package/dist/web/list/EntitySearchBar.js +11 -3
  36. package/dist/web/list/columns.d.ts +6 -1
  37. package/dist/web/list/columns.js +81 -9
  38. package/dist/web/list/presentation.d.ts +20 -1
  39. package/dist/web/list/search.d.ts +14 -5
  40. package/dist/web/list/search.js +29 -14
  41. package/dist/web/record/ActionButton.d.ts +14 -4
  42. package/dist/web/record/ActionButton.js +45 -2
  43. package/dist/web/record/CommandButton.d.ts +10 -1
  44. package/dist/web/record/CommandButton.js +23 -4
  45. package/dist/web/record/RelatedList.d.ts +0 -15
  46. package/dist/web/record/RelatedList.js +35 -6
  47. package/dist/web/record/ServiceButton.d.ts +20 -4
  48. package/dist/web/record/ServiceButton.js +30 -5
  49. package/dist/web/record/ask.d.ts +59 -0
  50. package/dist/web/record/ask.js +59 -0
  51. package/dist/web/record/control.d.ts +2 -2
  52. package/dist/web/record/control.js +7 -3
  53. package/dist/web/record/edit.d.ts +6 -1
  54. package/dist/web/record/edit.js +56 -8
  55. package/dist/web/record/record.js +5 -2
  56. package/dist/web/workspace/SincproApp.d.ts +10 -1
  57. package/dist/web/workspace/SincproApp.js +18 -4
  58. package/dist/web/workspace/composer.d.ts +7 -2
  59. package/dist/web/workspace/composer.js +24 -4
  60. package/dist/web/workspace/record.d.ts +7 -2
  61. package/dist/web/workspace/record.js +31 -6
  62. package/package.json +7 -7
@@ -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,15 +1,16 @@
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
+ export { type AskedField, type AskField, type AskForm, askFormOf, } from "./record/ask.js";
13
14
  export { CommandButton } from "./record/CommandButton.js";
14
15
  export { RelationPicker } from "./record/control.js";
15
16
  export { dirtyOf, type FieldControl, RecordField, } from "./record/edit.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";
@@ -10,6 +10,7 @@ export { pivotOf } from "./list/pivot.js";
10
10
  export { presentationOf, presented, } from "./list/presentation.js";
11
11
  export { useRowCommands, } from "./list/rowCommands.js";
12
12
  export { facetsOf, modelOf } from "./list/search.js";
13
+ export { askFormOf, } from "./record/ask.js";
13
14
  export { CommandButton } from "./record/CommandButton.js";
14
15
  export { RelationPicker } from "./record/control.js";
15
16
  export { dirtyOf, RecordField, } from "./record/edit.js";
@@ -89,6 +89,9 @@ export type EntityListProps<T extends AnyRecord, C extends CommandBodies = Comma
89
89
  sums?: readonly string[] | false;
90
90
  /** The cuts this list offers by name: «sólo pagadas», «vencidas». */
91
91
  filters?: readonly NamedFilter<T>[];
92
+ /** The fields the search bar offers to look a typed text up in. Without it, the list
93
+ * definition's, else the entity's search template's, else its display (`facetsOf`). */
94
+ facets?: readonly string[];
92
95
  /** The fields «Group by» offers, in this order — among those the model lets split the set.
93
96
  * Without it, the list definition's, else every one the model does. */
94
97
  groupable?: readonly string[];
@@ -132,4 +135,4 @@ export type EntityFace<T> = {
132
135
  render: (set: ListSet<T>) => ReactNode;
133
136
  };
134
137
  export type View = "table" | "rows" | "board" | "sheet" | "pivot";
135
- export declare function EntityList<T extends AnyRecord, C extends CommandBodies = CommandBodies>({ listing, api, columns: askedColumns, cells, views: askedViews, title: askedTitle, description: askedDescription, crumbs, actions, onOpen, onPeek, openTargets, onOpenIn, pivot: pivotAsked, empty, search, sums, filters: askedFilters, groupable: askedGroupable, selectable, selectionActions, embedded, create, commands, rowActions: askedRowActions, faces, }: EntityListProps<T, C>): import("react").JSX.Element;
138
+ export declare function EntityList<T extends AnyRecord, C extends CommandBodies = CommandBodies>({ listing, api, columns: askedColumns, cells, views: askedViews, title: askedTitle, description: askedDescription, crumbs, actions, onOpen, onPeek, openTargets, onOpenIn, pivot: pivotAsked, empty, search, sums, filters: askedFilters, facets: askedFacets, groupable: askedGroupable, selectable, selectionActions, embedded, create, commands, rowActions: askedRowActions, faces, }: EntityListProps<T, C>): import("react").JSX.Element;
@@ -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";
@@ -32,16 +33,19 @@ const TRAILS = 50;
32
33
  const NO_COMMANDS = [];
33
34
  /** What a list offers when nobody said: every face that needs no configuration. */
34
35
  const EVERY_VIEW = ["table", "rows", "board", "sheet"];
35
- export function EntityList({ listing, api, columns: askedColumns, cells, views: askedViews, title: askedTitle, description: askedDescription, crumbs, actions, onOpen, onPeek, openTargets, onOpenIn, pivot: pivotAsked, empty, search = "bar", sums, filters: askedFilters, groupable: askedGroupable, selectable = false, selectionActions, embedded = false, create = true, commands = NO_COMMANDS, rowActions: askedRowActions, faces, }) {
36
+ export function EntityList({ listing, api, columns: askedColumns, cells, views: askedViews, title: askedTitle, description: askedDescription, crumbs, actions, onOpen, onPeek, openTargets, onOpenIn, pivot: pivotAsked, empty, search = "bar", sums, filters: askedFilters, facets: askedFacets, groupable: askedGroupable, selectable = false, selectionActions, embedded = false, create = true, commands = NO_COMMANDS, rowActions: askedRowActions, faces, }) {
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"]);
43
46
  const filters = askedFilters ?? definition?.filters ?? [];
44
47
  const groupable = askedGroupable ?? definition?.groupable;
48
+ const facets = askedFacets ?? definition?.facets;
45
49
  const title = askedTitle ?? definition?.title;
46
50
  const description = askedDescription ?? definition?.description;
47
51
  const copy = frameworkCopy().list;
@@ -64,7 +68,7 @@ export function EntityList({ listing, api, columns: askedColumns, cells, views:
64
68
  // Opened by `api.pick` (`entity.chooserRef()`): a row ANSWERS whoever asked, it does not open.
65
69
  const choosing = api?.self.params?.[PICK_PARAM] !== undefined;
66
70
  // The record opened from a row knows the page it came from: «3 / 64» and its neighbours.
67
- const { trails } = useFramework();
71
+ const { trails, dateStyle } = useFramework();
68
72
  const trailKey = `trail:${useId()}`;
69
73
  // Kept current with the page on screen: the row and its name (`RecordLink`) open the same
70
74
  // reference, and whichever opens it, the record finds where it came from.
@@ -140,13 +144,19 @@ export function EntityList({ listing, api, columns: askedColumns, cells, views:
140
144
  const openingNow = useRef(openingIn);
141
145
  openingNow.current = openingIn;
142
146
  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)
147
+ // The column that names a row carries its link and «Abrir en…»: the identity, or — in a list
148
+ // that does not show it (a relation inside a record) — the record's name, else the first.
149
+ const named = columns === undefined || columns.includes(identity)
150
+ ? identity
151
+ : meta?.display && columns.includes(meta.display)
152
+ ? meta.display
153
+ : (columns[0] ?? identity);
154
+ const rowName = (row) => named === identity ? idOf(row) : (textOf(meta, named, row[named], locale) ?? idOf(row));
155
+ const linked = choosing || cells?.[named] !== undefined || (api === undefined && elsewhere.length === 0)
146
156
  ? cells
147
157
  : {
148
158
  ...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)] })),
159
+ [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
160
  };
151
161
  // `useCrumbs`, not `api.crumbs()`: the crumb must follow a name given later (`setTitle`).
152
162
  // Without a workspace it reads a trail that never changes — a hook cannot be skipped.
@@ -178,16 +188,24 @@ export function EntityList({ listing, api, columns: askedColumns, cells, views:
178
188
  // every cell of the table. `columns` is compared by content (it is usually a literal);
179
189
  // `cells` by identity, since its functions may close over state — memoise it to keep this.
180
190
  const names = columns?.join("\u0000");
181
- const shown = useMemo(() => columnsOf(meta, columns, { locale, ...(linked ? { cells: linked } : {}) }),
191
+ const shown = useMemo(() => columnsOf(meta, columns, {
192
+ locale,
193
+ ...(linked ? { cells: linked } : {}),
194
+ ...(look.tones === undefined ? {} : { tones: look.tones }),
195
+ }),
182
196
  // eslint-disable-next-line react-hooks/exhaustive-deps
183
- [meta, locale, names, cells, api, elsewhere.join(), openingIn === undefined]);
197
+ [meta, locale, names, cells, api, elsewhere.join(), openingIn === undefined, dateStyle]);
198
+ // A state the application gave colours to is the row's tag — and not again among its facts.
199
+ const stateField = summaryFieldsOf(meta, {}, listing.entity.summary).state;
200
+ const stateTones = stateField === undefined ? undefined : look.tones?.[stateField];
184
201
  // A row and a card read the record by its display and the first fields shown beside it.
185
202
  const display = meta?.display || identity;
186
203
  const facts = shown
187
- .filter((c) => c.id !== display && c.id !== identity && !c.defaultHidden)
204
+ .filter((c) => c.id !== display &&
205
+ c.id !== identity &&
206
+ !c.defaultHidden &&
207
+ (stateTones === undefined || c.id !== stateField))
188
208
  .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
209
  // The pivot asks the server only while it is the face on screen.
192
210
  const axes = pivotAsked === undefined || present !== "pivot" || !views.includes("pivot")
193
211
  ? null
@@ -230,10 +248,22 @@ export function EntityList({ listing, api, columns: askedColumns, cells, views:
230
248
  const rowOf = (row) => over({
231
249
  name: textOf(meta, display, row[display], locale) ?? idOf(row),
232
250
  meta: [
233
- ...(display === identity ? [] : [idOf(row)]),
251
+ // The key only where the list reads it: one that leaves it out (a relation inside a
252
+ // record) does not print a UUID on every row.
253
+ ...(display === identity || named !== identity ? [] : [idOf(row)]),
234
254
  ...facts.map((c) => textOf(meta, c.id, row[c.id], locale)).filter(Boolean),
235
255
  ].join(" · "),
236
256
  ...(elsewhere.length === 0 ? {} : { actions: openInOf(row) }),
257
+ ...(stateTones === undefined || stateField === undefined
258
+ ? {}
259
+ : (() => {
260
+ const word = textOf(meta, stateField, row[stateField], locale);
261
+ return word === null
262
+ ? {}
263
+ : {
264
+ tags: (_jsx(Tag, { tone: stateTones[String(row[stateField])] ?? "neutral", children: word })),
265
+ };
266
+ })()),
237
267
  }, look.row?.(row));
238
268
  // Without a look of its own, the board's card is web-ui's, made of the row. With one, the
239
269
  // same card — the row's name, meta and tags — under it, and pressing it is still the list's:
@@ -290,6 +320,19 @@ export function EntityList({ listing, api, columns: askedColumns, cells, views:
290
320
  }
291
321
  : {};
292
322
  const records = groups.buckets.reduce((sum, bucket) => sum + bucket.count, 0);
323
+ // The foot adds up what the model says adds up (`total`) — over the rows in hand, never a
324
+ // grouped set (each group says its own, counted by the server). While the rows are not the
325
+ // whole set the list says the figures are this page's (`pageTotals`): the server's total over
326
+ // everything filtered waits on a reading of measures (sincpro_framework, PRD_09).
327
+ const partial = listing.paging === "pages"
328
+ ? page.hasPrev || page.hasNext
329
+ : listing.hasMore || listing.capped;
330
+ // Inside a record or a panel a list is its rows: a page's sum there reads as THE total, so an
331
+ // embedded list adds up only when every row is in hand.
332
+ const totalled = !grouped &&
333
+ !(embedded && partial) &&
334
+ listing.rows.length > 0 &&
335
+ shown.some((column) => column.aggregate !== undefined && !column.defaultHidden);
293
336
  // A row's actions: the entity's Commands, then whatever else the screen offers.
294
337
  // The trash (`trashOf`): each row is brought back from where it is, with the entity's own
295
338
  // `restore` — it can be undone, so it runs on the click; the list reads again after.
@@ -309,13 +352,20 @@ export function EntityList({ listing, api, columns: askedColumns, cells, views:
309
352
  ? undefined
310
353
  : (row) => [...rowCommands.rowActions(row), ...(askedRowActions?.(row) ?? [])];
311
354
  const refused = rowCommands.error === null ? null : explain(rowCommands.error);
355
+ // The way through the set. Inside a record or a panel, only while there is more than what is
356
+ // on screen: «1–5 / 5» repeats the rows.
357
+ const fits = embedded && !partial;
358
+ const through = grouped ? (groups.status !== "ready" ? null : (_jsx("span", { className: "text-meta text-muted", children: groups.capped
359
+ ? copy.groupsCapped(groups.buckets.length)
360
+ : copy.groups(groups.buckets.length, records) }))) : fits ? null : 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] }));
361
+ const pageTotals = totalled && partial && present === "table";
362
+ // Written only when it says something: web-ui draws an embedded list's bar for any slot
363
+ // written, an empty one too.
364
+ const paging = !pageTotals && dropped.length === 0 && through === null ? null : (_jsxs(_Fragment, { children: [pageTotals ? _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) })), through] }));
312
365
  return (_jsxs(List, { items: listing.rows, keyOf: idOf, embedded: embedded, present: present, onPresentChange: setPresent, ...grouping,
313
366
  // The whole order, as web-ui 1.7 shows and sets it: ⇧-click on a header adds a field,
314
367
  // the sort menu reorders them — the same list the criteria builder writes.
315
- sort: sortStates,
316
- // The faces with no headers (rows, board) sort too, by the fields the model marks
317
- // sortable — on the server, so no `value` is given.
318
- sortable: sortable, onSortChange: (next) => listing.orderBy(next.map((one) => ({ field: one.key, descending: one.direction === "desc" }))), state: {
368
+ sort: sortStates, ...(embedded ? {} : { sortable }), onSortChange: (next) => listing.orderBy(next.map((one) => ({ field: one.key, descending: one.direction === "desc" }))), state: {
319
369
  // Only the FIRST reading shows the skeleton. Refining (typing, a filter, the next
320
370
  // page) keeps the rows on screen until the server answers: web-ui swaps the body for
321
371
  // a skeleton while `loading`, and a row that vanished under the pointer lost a click.
@@ -332,14 +382,12 @@ export function EntityList({ listing, api, columns: askedColumns, cells, views:
332
382
  }, filtered: listing.selection !== undefined || listing.text !== "", empty: {
333
383
  sentence: empty ?? copy.empty,
334
384
  whenFiltered: { sentence: copy.emptyFiltered },
335
- }, ...(selection === undefined ? {} : { selection }), ...(opening === undefined ? {} : { onOpen: opening }), ...(peeking === undefined ? {} : { onPeek: peeking, rowClick: "open" }), children: [_jsxs(List.Bar, { children: [trail === undefined || trail.length === 0 ? null : _jsx(List.Crumbs, { crumbs: trail }), embedded ? null : (_jsx(List.Identity, { title: title ?? nameOf(meta, locale), ...(description === undefined ? {} : { description }) })), search === "bar" ? (_jsx(List.Search, { children: _jsx(EntitySearchBar, { listing: listing, filters: filters, groups: groups, ...(groupable === undefined ? {} : { groupable }), ...(asked === "" ? {} : { seed: asked }) }) })) : null, search === "box" && meta?.search != null ? (_jsx(List.Search, { children: _jsx(SearchField, { value: draft, onChange: (next) => {
385
+ }, ...(selection === undefined ? {} : { selection }), ...(opening === undefined ? {} : { onOpen: opening }), ...(peeking === undefined ? {} : { onPeek: peeking, rowClick: "open" }), children: [_jsxs(List.Bar, { children: [trail === undefined || trail.length === 0 ? null : _jsx(List.Crumbs, { crumbs: trail }), embedded ? null : (_jsx(List.Identity, { title: title ?? nameOf(meta, locale), ...(description === undefined ? {} : { description }) })), search === "bar" ? (_jsx(List.Search, { children: _jsx(EntitySearchBar, { listing: listing, filters: filters, groups: groups, ...(groupable === undefined ? {} : { groupable }), ...(facets === undefined ? {} : { facets }), ...(asked === "" ? {} : { seed: asked }) }) })) : null, search === "box" && meta?.search != null ? (_jsx(List.Search, { children: _jsx(SearchField, { value: draft, onChange: (next) => {
336
386
  setDraft(next);
337
387
  // Emptied (or cleared with ×): the whole set again, at once.
338
388
  if (next === "" && listing.text !== "")
339
389
  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
341
- ? 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) => {
390
+ }, 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 }))] })), paging === null ? null : _jsx(List.Pagination, { children: paging })] }), 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
391
  const value = row[column.id];
344
392
  return value === null || value === undefined
345
393
  ? null
@@ -12,7 +12,8 @@ import type { Listing } from "../../react/useListing.js";
12
12
  * - a free text is the entity's LITERAL search — its whole template, every field at once
13
13
  * (sincpro_framework's `LiteralSearch`, the same question a many2one and ⌘K ask): it is
14
14
  * what Enter puts, unless the model reads the text as a question of its own;
15
- * - «search by name»: facets are the fields the entity's search template names first;
15
+ * - «search by name»: facets are the fields the screen names (`facets`), else the ones the
16
+ * entity's search template names — never every text field;
16
17
  * - a typed question («total > 5000») is checked against each field's operators;
17
18
  * - a named filter is one click; the builder writes what nobody foresaw (all/any/not);
18
19
  * - everything put becomes ONE `selection` the SERVER answers (`listing.filter`) — web-ui
@@ -23,7 +24,7 @@ import type { Listing } from "../../react/useListing.js";
23
24
  * <List.Search><EntitySearchBar listing={listing} filters={…} /></List.Search>
24
25
  */
25
26
  export type { NamedFilter };
26
- export declare function EntitySearchBar<T extends AnyRecord>({ listing, filters, groups, groupable: only, seed, }: {
27
+ export declare function EntitySearchBar<T extends AnyRecord>({ listing, filters, groups, groupable: only, facets: named, seed, }: {
27
28
  listing: Listing<T>;
28
29
  /** The cuts this set offers by name: «sólo pagadas», «vencidas». */
29
30
  filters?: readonly NamedFilter<T>[];
@@ -32,6 +33,9 @@ export declare function EntitySearchBar<T extends AnyRecord>({ listing, filters,
32
33
  /** The fields «Group by» offers, in this order — among those the model lets split the set.
33
34
  * Without it, every one it does. */
34
35
  groupable?: readonly string[];
36
+ /** The fields a typed text is offered to be looked up in, in order. Without it, the ones the
37
+ * entity's search template names, else its display (`facetsOf`). */
38
+ facets?: readonly string[];
35
39
  /** A text to start on, put as the literal search chip — what was typed in a picker whose
36
40
  * «Buscar más…» opened this list. */
37
41
  seed?: string;
@@ -8,13 +8,21 @@ import { CriteriaBuilder, describeFilter, Dialog, fillCopy, filterCriteria, Grou
8
8
  import { useEffect, useMemo, useRef, useState } from "react";
9
9
  /** No grouping: one constant, so the control is not handed a new array on every render. */
10
10
  const NO_LEVELS = [];
11
- export function EntitySearchBar({ listing, filters = [], groups, groupable: only, seed, }) {
11
+ export function EntitySearchBar({ listing, filters = [], groups, groupable: only, facets: named, seed, }) {
12
12
  const copy = frameworkCopy().list;
13
13
  const { meta, locale } = listing;
14
14
  const [put, setPut] = useState([]);
15
15
  const [building, setBuilding] = useState(false);
16
16
  const model = useMemo(() => (meta ? modelOf(meta, locale) : undefined), [meta, locale]);
17
- const facets = useMemo(() => (meta ? facetsOf(meta, locale) : []), [meta, locale]);
17
+ // Compared by content: a screen usually writes the list inline.
18
+ const naming = named?.join("\u0000");
19
+ const facets = useMemo(() => (meta ? facetsOf(meta, locale, named) : []),
20
+ // eslint-disable-next-line react-hooks/exhaustive-deps
21
+ [meta, locale, naming]);
22
+ // The bar's model: its text fields are only the facets — every other one is the builder's.
23
+ const asked = useMemo(() => meta
24
+ ? modelOf(meta, locale, facets.map((one) => one.id))
25
+ : undefined, [meta, locale, facets]);
18
26
  const groupable = useMemo(() => groupableOf(meta, locale, only), [meta, locale, only]);
19
27
  const ui = useUiCopy();
20
28
  const seeded = useRef(false);
@@ -43,7 +51,7 @@ export function EntitySearchBar({ listing, filters = [], groups, groupable: only
43
51
  };
44
52
  // What the bar holds, as one selection: what the builder opens on.
45
53
  const current = selectionOf(put);
46
- return (_jsxs(_Fragment, { children: [_jsx(SearchBar, { facets: facets, model: model, criteria: put, onCriteriaChange: place, placeholder: copy.searchBar, ...(filters.length === 0
54
+ return (_jsxs(_Fragment, { children: [_jsx(SearchBar, { facets: facets, model: asked ?? model, criteria: put, onCriteriaChange: place, placeholder: copy.searchBar, ...(filters.length === 0
47
55
  ? {}
48
56
  : {
49
57
  filters: [
@@ -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,13 @@
1
- import { jsx as _jsx } from "react/jsx-runtime";
2
- import { BOOKKEEPING, defaultFields, sortKeyOf, textOf, viewOf, } from "../../core/present.js";
1
+ "use client";
2
+ import { Fragment as _Fragment, jsx as _jsx } from "react/jsx-runtime";
3
+ import { frameworkCopy } from "../../core/copy.js";
4
+ import { totalOf } from "../../core/measure.js";
5
+ import { BOOKKEEPING, defaultFields, fieldMetaOf, sortKeyOf, textOf, valueAt, viewOf, } from "../../core/present.js";
6
+ import { relationFieldOf } from "../../core/relation.js";
7
+ import { useEntityFor } from "../../react/context.js";
8
+ import { useNameOf } from "../../react/useNameOf.js";
9
+ import { Tag } from "@sincpro/web-ui";
10
+ import { Check } from "lucide-react";
3
11
  /**
4
12
  * The columns of a table, from the model: name the fields, the rest follows.
5
13
  *
@@ -7,32 +15,96 @@ import { BOOKKEEPING, defaultFields, sortKeyOf, textOf, viewOf, } from "../../co
7
15
  * p.display_name`, a date formatter per screen — while the server already said what each field
8
16
  * is called and what type it holds. Here a column is a NAME: its header is the model's label,
9
17
  * 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`).
18
+ * can be ordered is what the server said (`sortable`). A cell is drawn by its TYPE: a choice is a
19
+ * tag in the tone the application declared for its value (`presented(entity, { tones })`), a
20
+ * yes/no a check, an amount the model draws as money is money. A cell that needs more — a link,
21
+ * a figure of its own — is the one thing a screen writes (`cells`). A column that holds a key of
22
+ * another record (`organo_id`, an `EntityID`) reads the record's name, as its picker does: every
23
+ * key of the page asked in ONE request per entity (`useNameOf`), the key until it answers.
24
+ *
25
+ * A column the model adds up at a list's foot (`total`: `sum`, `avg`, `min`, `max`) declares it
26
+ * (`aggregate`), with its own format: the foot reads «Bs 1.204,50» like the cells above it.
12
27
  *
13
28
  * The fields NOT named still exist: they come after, `optional` and hidden, so the columns
14
29
  * menu offers them and nobody edits the screen to see a field the server already sends.
15
30
  */
16
31
  /** The types whose value is one short thing, read whole. */
17
32
  const DATES = new Set(["date", "datetime", "time"]);
33
+ /** The model's `total` as web-ui's aggregate. */
34
+ const AGGREGATES = {
35
+ sum: "sum",
36
+ avg: "mean",
37
+ min: "min",
38
+ max: "max",
39
+ };
40
+ /** How the model adds a field up at a list's foot, as web-ui's `aggregate`. */
41
+ export function aggregateOf(meta, name) {
42
+ const total = totalOf(meta, name);
43
+ return total === undefined ? undefined : AGGREGATES[total];
44
+ }
45
+ /** A key's cell: the name of the record it points at, the key until it answers or when the
46
+ * application declared no entity for it. */
47
+ function KeyName({ target, id }) {
48
+ return _jsx(_Fragment, { children: useNameOf(useEntityFor(target), id) ?? id });
49
+ }
18
50
  function columnOf(meta, name, options, hidden) {
19
51
  const view = viewOf(meta, name, options.locale);
20
- const text = (row) => textOf(meta, name, row[name], options.locale) ?? "";
52
+ const field = fieldMetaOf(meta, name);
53
+ const raw = (row) => valueAt(meta, row, name);
54
+ const text = (row) => textOf(meta, name, raw(row), options.locale) ?? "";
21
55
  const own = options.cells?.[name];
22
56
  // 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);
57
+ const money = field?.widget === "money";
58
+ const whole = view.name === meta?.identity || view.numeric || money || DATES.has(view.type);
59
+ const tones = options.tones?.[name];
60
+ const choice = (field?.choices?.length ?? 0) > 0;
61
+ const aggregate = aggregateOf(meta, name);
62
+ // The column IS a key of another record: `customer_id` beside its relation, or a key alone.
63
+ const relation = relationFieldOf(meta, name);
64
+ const pointing = relation !== undefined && !relation.many && relation.key === name ? relation : undefined;
65
+ const named = pointing === undefined
66
+ ? undefined
67
+ : (row) => {
68
+ const key = raw(row);
69
+ if (key === null || key === undefined || key === "")
70
+ return null;
71
+ // Held beside its key, the record names itself; a key alone asks its name.
72
+ const held = pointing.relation === name
73
+ ? null
74
+ : textOf(meta, pointing.relation, row[pointing.relation], options.locale);
75
+ return held ?? _jsx(KeyName, { target: pointing.target, id: String(key) });
76
+ };
24
77
  return {
25
78
  id: name,
26
79
  header: view.label,
27
80
  field: name,
28
- value: (row) => sortKeyOf(meta, name, row[name]),
81
+ value: (row) => sortKeyOf(meta, name, raw(row)),
29
82
  cell: own ??
30
- (whole ? (row) => _jsx("span", { className: "whitespace-nowrap", children: text(row) }) : text),
83
+ named ??
84
+ (choice
85
+ ? // A state reads at a glance: its word in a tag, in the tone the application gave it.
86
+ (row) => {
87
+ const word = text(row);
88
+ return word === "" ? null : (_jsx(Tag, { tone: tones?.[String(raw(row))] ?? "neutral", children: word }));
89
+ }
90
+ : view.type === "boolean"
91
+ ? // A yes is a check and a no is nothing: a column of «sí/no» is noise to scan.
92
+ (row) => raw(row) === true ? (_jsx(Check, { role: "img", "aria-label": frameworkCopy().value.yes, className: "size-(--size-icon-sm)" })) : null
93
+ : whole
94
+ ? (row) => _jsx("span", { className: "whitespace-nowrap", children: text(row) })
95
+ : text),
31
96
  text,
32
- numeric: view.numeric,
97
+ numeric: view.numeric || money,
33
98
  sortable: view.sortable,
34
99
  ...(view.name === meta?.identity ? { mono: true } : {}),
35
100
  ...(hidden ? { optional: true, defaultHidden: true } : {}),
101
+ ...(aggregate === undefined
102
+ ? {}
103
+ : {
104
+ aggregate,
105
+ // The foot reads as the cells above it: «Bs 1.204,50», not «1204.5».
106
+ format: (value) => textOf(meta, name, value, options.locale) ?? String(value),
107
+ }),
36
108
  };
37
109
  }
38
110
  export function columnsOf(meta, names, options = {}) {