@sincpro/web-framework 0.1.0 → 0.3.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 (97) hide show
  1. package/README.md +298 -40
  2. package/dist/core/cache.js +2 -2
  3. package/dist/core/copy.d.ts +26 -0
  4. package/dist/core/copy.js +32 -0
  5. package/dist/core/edit.d.ts +48 -3
  6. package/dist/core/edit.js +79 -5
  7. package/dist/core/entity.d.ts +46 -0
  8. package/dist/core/entity.js +57 -0
  9. package/dist/core/form.d.ts +21 -0
  10. package/dist/core/form.js +30 -0
  11. package/dist/core/index.d.ts +11 -3
  12. package/dist/core/index.js +10 -2
  13. package/dist/core/lines.d.ts +53 -0
  14. package/dist/core/lines.js +120 -0
  15. package/dist/core/list.d.ts +64 -0
  16. package/dist/core/list.js +22 -0
  17. package/dist/core/lookup.d.ts +7 -2
  18. package/dist/core/lookup.js +8 -2
  19. package/dist/core/measure.d.ts +16 -0
  20. package/dist/core/measure.js +38 -0
  21. package/dist/core/memory.js +18 -4
  22. package/dist/core/relation.d.ts +28 -0
  23. package/dist/core/relation.js +30 -0
  24. package/dist/core/rest.d.ts +5 -9
  25. package/dist/core/rest.js +25 -7
  26. package/dist/core/retry.d.ts +24 -0
  27. package/dist/core/retry.js +25 -0
  28. package/dist/core/summary.d.ts +50 -0
  29. package/dist/core/summary.js +54 -0
  30. package/dist/core/trail.d.ts +44 -0
  31. package/dist/core/trail.js +70 -0
  32. package/dist/core/transport.d.ts +22 -2
  33. package/dist/react/context.d.ts +20 -1
  34. package/dist/react/context.js +10 -2
  35. package/dist/react/index.d.ts +5 -2
  36. package/dist/react/index.js +4 -1
  37. package/dist/react/useCommand.d.ts +3 -1
  38. package/dist/react/useCommand.js +12 -4
  39. package/dist/react/useGroups.d.ts +52 -0
  40. package/dist/react/useGroups.js +110 -0
  41. package/dist/react/useListing.d.ts +29 -7
  42. package/dist/react/useListing.js +49 -8
  43. package/dist/react/useLookup.d.ts +30 -5
  44. package/dist/react/useLookup.js +56 -3
  45. package/dist/react/usePivot.d.ts +33 -0
  46. package/dist/react/usePivot.js +59 -0
  47. package/dist/react/useRecord.d.ts +28 -9
  48. package/dist/react/useRecord.js +156 -18
  49. package/dist/react/useSummary.d.ts +15 -0
  50. package/dist/react/useSummary.js +22 -0
  51. package/dist/web/index.d.ts +15 -3
  52. package/dist/web/index.js +14 -2
  53. package/dist/web/list/EntityList.d.ts +69 -7
  54. package/dist/web/list/EntityList.js +281 -23
  55. package/dist/web/list/EntitySearchBar.d.ts +16 -8
  56. package/dist/web/list/EntitySearchBar.js +52 -4
  57. package/dist/web/list/columns.d.ts +0 -13
  58. package/dist/web/list/columns.js +20 -1
  59. package/dist/web/list/groups.d.ts +17 -0
  60. package/dist/web/list/groups.js +80 -0
  61. package/dist/web/list/openIn.d.ts +41 -0
  62. package/dist/web/list/openIn.js +55 -0
  63. package/dist/web/list/pivot.d.ts +23 -0
  64. package/dist/web/list/pivot.js +64 -0
  65. package/dist/web/list/presentation.d.ts +51 -0
  66. package/dist/web/list/presentation.js +20 -0
  67. package/dist/web/list/rowCommands.d.ts +41 -0
  68. package/dist/web/list/rowCommands.js +56 -0
  69. package/dist/web/record/EntityPicker.d.ts +45 -14
  70. package/dist/web/record/EntityPicker.js +64 -20
  71. package/dist/web/record/EntityTags.d.ts +38 -0
  72. package/dist/web/record/EntityTags.js +52 -0
  73. package/dist/web/record/RelatedList.d.ts +8 -1
  74. package/dist/web/record/RelatedList.js +37 -3
  75. package/dist/web/record/control.d.ts +42 -0
  76. package/dist/web/record/control.js +60 -0
  77. package/dist/web/record/edit.d.ts +27 -12
  78. package/dist/web/record/edit.js +92 -25
  79. package/dist/web/record/lines.d.ts +84 -0
  80. package/dist/web/record/lines.js +190 -0
  81. package/dist/web/record/opening.d.ts +34 -0
  82. package/dist/web/record/opening.js +10 -0
  83. package/dist/web/record/summary.d.ts +22 -0
  84. package/dist/web/record/summary.js +63 -0
  85. package/dist/web/workspace/SincproApp.d.ts +4 -1
  86. package/dist/web/workspace/SincproApp.js +2 -2
  87. package/dist/web/workspace/composer.d.ts +27 -4
  88. package/dist/web/workspace/composer.js +75 -7
  89. package/dist/web/workspace/open.d.ts +49 -0
  90. package/dist/web/workspace/open.js +51 -0
  91. package/dist/web/workspace/record.d.ts +30 -0
  92. package/dist/web/workspace/record.js +83 -0
  93. package/dist/web/workspace/skin.d.ts +0 -9
  94. package/dist/web/workspace/skin.js +25 -13
  95. package/dist/web/workspace/workspace.d.ts +33 -3
  96. package/dist/web/workspace/workspace.js +63 -4
  97. package/package.json +9 -9
@@ -8,7 +8,14 @@ import { type EntityListProps } from "../list/EntityList.js";
8
8
  * Context: the same `EntityList` a screen uses, `embedded` so it reads as a field of the record
9
9
  * (a one-line bar that does not stick), over `useRelated`. Its search box fills the RELATED
10
10
  * entity's own search template: the lines of an order are searched by product, the invoices of
11
- * a customer by number. Use `RecordLines` when the page the record brought is all there is.
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.
12
19
  */
13
20
  export declare function RelatedList<P extends AnyRecord, T extends AnyRecord>({ record, name, entity, pageSize, ...list }: {
14
21
  record: RecordReading<P>;
@@ -1,16 +1,50 @@
1
1
  "use client";
2
- import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { frameworkCopy } from "../../core/copy.js";
4
+ import { defaultFields } from "../../core/present.js";
3
5
  import { useRelated } from "../../react/useRelated.js";
4
6
  import { EntityList } from "../list/EntityList.js";
7
+ import { useRecordOpening } from "./opening.js";
8
+ import { Button } from "@sincpro/web-ui";
9
+ import { useMemo } from "react";
5
10
  /**
6
11
  * A relation of a record as a list inside it — searched, ordered and paged by the server.
7
12
  *
8
13
  * Context: the same `EntityList` a screen uses, `embedded` so it reads as a field of the record
9
14
  * (a one-line bar that does not stick), over `useRelated`. Its search box fills the RELATED
10
15
  * entity's own search template: the lines of an order are searched by product, the invoices of
11
- * a customer by number. Use `RecordLines` when the page the record brought is all there is.
16
+ * a customer by number. The column that points back to this record is left out — it is the
17
+ * same on every row. Use `RecordLines` when the page the record brought is all there is.
18
+ *
19
+ * «Agregar» opens the form of a new related record already pointing back here, where the view
20
+ * says (`RecordOpening.create`: a modal that answers, in a workspace), and the list is read
21
+ * again once it exists. Never a row of the table: each one is an aggregate with its own create,
22
+ * rules and preview. There is none while this record does not exist yet — there is nothing to
23
+ * point back to — nor when the relation is read only or the entity cannot be created.
12
24
  */
13
25
  export function RelatedList({ record, name, entity, pageSize, ...list }) {
14
26
  const listing = useRelated(record, name, entity, pageSize === undefined ? {} : { pageSize });
15
- return _jsx(EntityList, { listing: listing, embedded: true, search: "box", ...list });
27
+ const opening = useRecordOpening();
28
+ // Every row points back to THIS record: the column that says so is the same on all of them.
29
+ const back = record.meta?.fields[name]?.identified_by;
30
+ const own = list.columns;
31
+ const columns = useMemo(() => own ??
32
+ (listing.meta === null || !back
33
+ ? undefined
34
+ : defaultFields(listing.meta).filter((field) => field !== back)), [own, listing.meta, back]);
35
+ const create = opening?.create;
36
+ // The value the rows point back with — the same key `useRelated` scopes the list by.
37
+ const identity = record.meta?.get_id || record.meta?.identity || "id";
38
+ const here = record.record === null ? undefined : record.record[identity];
39
+ const adding = create === undefined ||
40
+ entity.create === undefined ||
41
+ !back ||
42
+ record.isNew ||
43
+ here === undefined ||
44
+ record.edit.state(name).readonly ? null : (_jsx(Button, { size: "sm", role: "secondary", onClick: () => create(entity, { [back]: here }, listing.reload), children: frameworkCopy().record.add }));
45
+ return (_jsx(EntityList, { listing: listing, embedded: true, ...list, ...(columns === undefined ? {} : { columns }), ...(adding === null && list.actions === undefined
46
+ ? {}
47
+ : {
48
+ actions: (_jsxs(_Fragment, { children: [list.actions, adding] })),
49
+ }) }));
16
50
  }
@@ -0,0 +1,42 @@
1
+ import type { AnyRecord } from "@sincpro/criteria";
2
+ import type { Entity } from "../../core/entity.js";
3
+ import type { ReactNode } from "react";
4
+ /** What a control of a field receives: its value, how to change it, and its state now. */
5
+ export type FieldControl = {
6
+ value: unknown;
7
+ set: (value: unknown) => void;
8
+ readonly: boolean;
9
+ invalid: boolean;
10
+ label: string;
11
+ /** No `Field` names it — a cell of a table: the control carries its label itself. Inside a
12
+ * `Field` it must not, or React Aria reads both and names it «Precio Precio». */
13
+ standalone?: boolean;
14
+ };
15
+ /**
16
+ * The control a field's TYPE asks for — a choice, a number, a date, a yes/no, a list of words,
17
+ * a text.
18
+ * Shared by a record's field (`RecordField`) and a line's cell and dialog (`RecordLinesEditor`):
19
+ * one rule for what a value is edited with.
20
+ */
21
+ export declare function controlFor(control: FieldControl, type: string, exact: boolean, choices: {
22
+ value: unknown;
23
+ label: string;
24
+ }[]): ReactNode;
25
+ /**
26
+ * A many2one's control: the picker of the entity it points at — the server's literal search,
27
+ * the first ten, «Buscar más…» — opening the chosen one where the view says.
28
+ *
29
+ * Context: shared by a record's field and a line. Inside a line (`ownChooser`: its row or its
30
+ * dialog) «Buscar más…» is the picker's own chooser, never the workspace's: the workspace opens
31
+ * it outside the line — a row commits when the focus leaves it, and the answer would land on a
32
+ * line no longer being written; over the line's dialog it would be a modal over a modal.
33
+ */
34
+ export declare function RelationPicker({ target, value, onChange, label, ownChooser, standalone, }: {
35
+ target: Entity;
36
+ value: string;
37
+ onChange: (id: string, chosen?: AnyRecord) => void;
38
+ label: string;
39
+ ownChooser?: boolean;
40
+ /** No `Field` names it (a cell): it carries `label` itself — as `FieldControl.standalone`. */
41
+ standalone?: boolean;
42
+ }): import("react").JSX.Element;
@@ -0,0 +1,60 @@
1
+ "use client";
2
+ import { jsx as _jsx } from "react/jsx-runtime";
3
+ import { EntityPicker } from "./EntityPicker.js";
4
+ import { useRecordOpening } from "./opening.js";
5
+ import { Checkbox, DatePicker, NumberInput, Select, TagsField, TextInput, } from "@sincpro/web-ui";
6
+ /**
7
+ * The control a field's TYPE asks for — a choice, a number, a date, a yes/no, a list of words,
8
+ * a text.
9
+ * Shared by a record's field (`RecordField`) and a line's cell and dialog (`RecordLinesEditor`):
10
+ * one rule for what a value is edited with.
11
+ */
12
+ export function controlFor(control, type, exact, choices) {
13
+ const { value, set } = control;
14
+ const named = control.standalone === true ? { "aria-label": control.label } : {};
15
+ if (choices.length > 0)
16
+ return (_jsx(Select, { value: value === null || value === undefined ? "" : String(value), options: choices.map((one) => ({ value: String(one.value), label: one.label })), onChange: set, ...named }));
17
+ switch (type) {
18
+ case "boolean":
19
+ return _jsx(Checkbox, { checked: value === true, onChange: set, label: control.label });
20
+ case "integer":
21
+ case "number":
22
+ return (_jsx(NumberInput, { value: value === null || value === undefined || value === "" ? "" : Number(value),
23
+ // A decimal travels as text so no digit is lost; the server reads it that way back.
24
+ onChange: (next) => set(next === "" ? null : exact ? String(next) : next), ...named }));
25
+ case "date":
26
+ return (_jsx(DatePicker, { value: typeof value === "string" && value !== "" ? value : null, onChange: set, ...named }));
27
+ case "text[]": {
28
+ // A list of words is chips: each word is its own key, and typing a new one adds it.
29
+ const words = Array.isArray(value) ? value.map(String) : [];
30
+ return (_jsx(TagsField, { value: words, options: words.map((word) => ({ value: word, label: word })), onChange: set, onCreate: (word) => word, ...named }));
31
+ }
32
+ default:
33
+ return (_jsx(TextInput, { value: value === null || value === undefined ? "" : String(value), onChange: set, ...named }));
34
+ }
35
+ }
36
+ /**
37
+ * A many2one's control: the picker of the entity it points at — the server's literal search,
38
+ * the first ten, «Buscar más…» — opening the chosen one where the view says.
39
+ *
40
+ * Context: shared by a record's field and a line. Inside a line (`ownChooser`: its row or its
41
+ * dialog) «Buscar más…» is the picker's own chooser, never the workspace's: the workspace opens
42
+ * it outside the line — a row commits when the focus leaves it, and the answer would land on a
43
+ * line no longer being written; over the line's dialog it would be a modal over a modal.
44
+ */
45
+ export function RelationPicker({ target, value, onChange, label, ownChooser = false, standalone = false, }) {
46
+ const opening = useRecordOpening();
47
+ return (_jsx(EntityPicker, { entity: target, value: value, onChange: onChange,
48
+ // «Buscar más…» is an option of the picker already: no second button beside it.
49
+ browse: false, ...(standalone ? { "aria-label": label } : {}), ...(opening === null
50
+ ? {}
51
+ : {
52
+ onOpen: (chosen, to) => opening.open(target.ref(chosen), to),
53
+ openTargets: opening.targets,
54
+ ...(ownChooser || opening.choose === undefined
55
+ ? {}
56
+ : {
57
+ onBrowseAll: (query) => opening.choose?.(target, (id) => onChange(id), query),
58
+ }),
59
+ }) }));
60
+ }
@@ -1,4 +1,9 @@
1
+ import { type AnyRecord } from "@sincpro/criteria";
1
2
  import type { RecordReading } from "../../react/useRecord.js";
3
+ import type { EntityListProps } from "../list/EntityList.js";
4
+ import { type FieldControl } from "./control.js";
5
+ import { type LinesLook } from "./lines.js";
6
+ export type { FieldControl } from "./control.js";
2
7
  import { type DirtyState } from "@sincpro/web-ui";
3
8
  import type { ReactNode } from "react";
4
9
  /**
@@ -9,24 +14,34 @@ import type { ReactNode } from "react";
9
14
  * Context: forge's forms wrote `<Field label="Nombre" required><TextInput … /></Field>` once per
10
15
  * field, with the label, the «required» and the value plumbing by hand, while the server already
11
16
  * said all three. Here a field is a NAME. The control by type is a default, never the only way:
12
- * `as` draws any control — a many2one with `EntityPicker`, a rich text, a domain widget — and
13
- * still receives the value, the setter and the state.
17
+ * `as` draws any control — a rich text, a domain widget — and still receives the value, the
18
+ * setter and the state.
19
+ *
20
+ * A many2one needs no `as`: the model says what it points at (`relation: "Cliente"`, the key
21
+ * `customer_id` it is written by), the application declared that entity
22
+ * (`SincproApp entities`), so the field is an `EntityPicker` of it — the server's literal
23
+ * search, the ten first, «Buscar más…» — and, read-only, the record's name as a link. Where it
24
+ * opens is the view's (`RecordOpening`: a modal in a workspace, nothing outside one).
25
+ *
26
+ * A one2many is a block: its lines (`lines`) or its related list (`list`), each with every piece
27
+ * replaceable the screen's way.
14
28
  *
15
29
  * <RecordField record={invoice} name="due_date" />
16
- * <RecordField record={invoice} name="customer_id"
17
- * as={({ value, set }) => <EntityPicker entity={customers} value={String(value)} onChange={set} />} />
30
+ * <RecordField record={invoice} name="customer_id" />
31
+ * <RecordField record={invoice} name="lines" lines={{ controls: { qty: Stepper } }} />
18
32
  */
19
- export type FieldControl = {
20
- value: unknown;
21
- set: (value: unknown) => void;
22
- readonly: boolean;
23
- invalid: boolean;
24
- label: string;
25
- };
26
- export declare function RecordField<T extends Record<string, unknown>>({ record, name, as, }: {
33
+ export declare function RecordField<T extends Record<string, unknown>>({ record, name, as, bare, lines: look, list: listed, }: {
27
34
  record: RecordReading<T>;
28
35
  name: string;
29
36
  as?: (control: FieldControl) => ReactNode;
37
+ /** The control without its label — inside a page or a section that already names it. */
38
+ bare?: boolean;
39
+ /** Lines (a one2many of no entity of its own), the screen's way: where a line is written,
40
+ * which columns, a cell or a control of its own, columns that are not fields, the dialog. */
41
+ lines?: LinesLook;
42
+ /** A one2many of a declared entity, the screen's way: anything `EntityList` takes — its
43
+ * cells, row actions, commands, faces of its own. What it passes wins over the defaults. */
44
+ list?: Omit<EntityListProps<AnyRecord>, "listing" | "embedded">;
30
45
  }): import("react").JSX.Element | null;
31
46
  /**
32
47
  * The record's «save / discard», for `<Record dirty={…}>`: present only while something changed,
@@ -2,16 +2,88 @@
2
2
  import { jsx as _jsx } from "react/jsx-runtime";
3
3
  import { choicesOf } from "@sincpro/criteria";
4
4
  import { frameworkCopy } from "../../core/copy.js";
5
+ import { errorAt } from "../../core/edit.js";
6
+ import { editableLines } from "../../core/lines.js";
5
7
  import { textOf, viewOf } from "../../core/present.js";
6
- import { Checkbox, DatePicker, Field, NumberInput, ReadValue, Select, TextArea, TextInput, } from "@sincpro/web-ui";
7
- export function RecordField({ record, name, as, }) {
8
+ import { relationFieldOf } from "../../core/relation.js";
9
+ import { useEntityFor, useFramework } from "../../react/context.js";
10
+ import { controlFor, RelationPicker, } from "./control.js";
11
+ import { RecordLinesEditor } from "./lines.js";
12
+ import { useRecordOpening } from "./opening.js";
13
+ import { RecordLines } from "./record.js";
14
+ import { RelatedList } from "./RelatedList.js";
15
+ import { Checkbox, Field, FormSection, ReadValue, RelationValue, } from "@sincpro/web-ui";
16
+ /**
17
+ * One field of a record being edited, from the model: its word, whether it is required or
18
+ * read-only now (the hints, evaluated over what is on screen), the server's error for it, and a
19
+ * control chosen by its type.
20
+ *
21
+ * Context: forge's forms wrote `<Field label="Nombre" required><TextInput … /></Field>` once per
22
+ * field, with the label, the «required» and the value plumbing by hand, while the server already
23
+ * said all three. Here a field is a NAME. The control by type is a default, never the only way:
24
+ * `as` draws any control — a rich text, a domain widget — and still receives the value, the
25
+ * setter and the state.
26
+ *
27
+ * A many2one needs no `as`: the model says what it points at (`relation: "Cliente"`, the key
28
+ * `customer_id` it is written by), the application declared that entity
29
+ * (`SincproApp entities`), so the field is an `EntityPicker` of it — the server's literal
30
+ * search, the ten first, «Buscar más…» — and, read-only, the record's name as a link. Where it
31
+ * opens is the view's (`RecordOpening`: a modal in a workspace, nothing outside one).
32
+ *
33
+ * A one2many is a block: its lines (`lines`) or its related list (`list`), each with every piece
34
+ * replaceable the screen's way.
35
+ *
36
+ * <RecordField record={invoice} name="due_date" />
37
+ * <RecordField record={invoice} name="customer_id" />
38
+ * <RecordField record={invoice} name="lines" lines={{ controls: { qty: Stepper } }} />
39
+ */
40
+ export function RecordField({ record, name, as, bare = false, lines: look, list: listed, }) {
8
41
  const { meta, locale, edit } = record;
9
42
  const view = viewOf(meta, name, locale);
10
43
  const state = edit.state(name);
44
+ const relation = relationFieldOf(meta, name);
45
+ const target = useEntityFor(relation?.target);
46
+ const opening = useRecordOpening();
47
+ const { metas } = useFramework();
11
48
  if (!state.visible)
12
49
  return null;
50
+ // A one2many is a BLOCK, named by a section — never a `Field`: web-ui's controls read the
51
+ // id and the label of the `Field` around them, and every cell and the list's search bar
52
+ // took the same id and the relation's name.
53
+ // A one2many of a declared entity is that entity's own list, filtered to this record by
54
+ // the server — never the page the record happened to bring — and a row opens its record.
55
+ // A one2many of no declared entity (the lines of an invoice): edited inside the record as a
56
+ // whole list (`RecordLinesEditor`) — or, when the record brought only a page, that page read
57
+ // only with its real total.
58
+ if (as === undefined && relation?.field.type === "one2many" && target === undefined) {
59
+ // Editable when the record holds ALL its lines; a page of them stays read only.
60
+ const whole = editableLines(edit.values[name]);
61
+ const lines = whole === null ? (_jsx(RecordLines, { record: record.record ?? {}, meta: meta, name: name, locale: locale })) : (_jsx(RecordLinesEditor, { record: record, name: name, lines: whole, ...(look === undefined ? {} : { look }) }));
62
+ return bare ? lines : _jsx(FormSection, { title: view.label, children: lines });
63
+ }
64
+ if (as === undefined && relation?.field.type === "one2many" && target !== undefined) {
65
+ const list = (_jsx(RelatedList, { record: record, name: name, entity: target, ...(opening === null
66
+ ? {}
67
+ : (() => {
68
+ const refOf = (row) => {
69
+ const known = metas.get(target.key);
70
+ const key = known?.get_id || known?.identity || "id";
71
+ return target.ref(String(row[key]));
72
+ };
73
+ // A press opens where the view says first; «Abrir en…» offers every other place.
74
+ return {
75
+ onOpen: (row) => opening.open(refOf(row), opening.targets[0] ?? "page"),
76
+ onOpenIn: (row, to) => opening.open(refOf(row), to),
77
+ openTargets: opening.targets,
78
+ // Not on a page, a list inside the form starts as rows; the table stays a click
79
+ // away.
80
+ ...(opening.narrow === true ? { views: ["rows", "table"] } : {}),
81
+ };
82
+ })()), ...listed }));
83
+ return bare ? list : _jsx(FormSection, { title: view.label, children: list });
84
+ }
13
85
  const value = edit.values[name];
14
- const error = edit.errors[name];
86
+ const error = errorAt(edit.errors, name);
15
87
  const control = {
16
88
  value,
17
89
  set: (next) => edit.set(name, next),
@@ -20,30 +92,25 @@ export function RecordField({ record, name, as, }) {
20
92
  label: view.label,
21
93
  };
22
94
  const field = meta?.fields[name];
95
+ /** A many2one of a declared entity: chosen by the server's literal search, opened where the
96
+ * view says. Written by its key; read by the record it points at. */
97
+ function manyToOne() {
98
+ if (relation === undefined || target === undefined)
99
+ return null;
100
+ const key = edit.values[relation.key];
101
+ const id = key === null || key === undefined ? "" : String(key);
102
+ if (state.readonly)
103
+ return (_jsx(RelationValue, { name: textOf(meta, relation.relation, edit.values[relation.relation], locale) ?? id, ...(opening === null || id === ""
104
+ ? {}
105
+ : {
106
+ onOpenIn: (to) => opening.open(target.ref(id), to),
107
+ openTargets: opening.targets,
108
+ }) }));
109
+ return (_jsx(RelationPicker, { target: target, value: id, onChange: (next) => edit.set(relation.key, next), label: view.label }));
110
+ }
23
111
  if (view.type === "boolean" && as === undefined)
24
112
  return (_jsx(Checkbox, { checked: value === true, onChange: control.set, label: view.label, disabled: state.readonly }));
25
- return (_jsx(Field, { label: view.label, required: state.required && !state.readonly, ...(view.help === undefined ? {} : { hint: view.help }), ...(error === undefined ? {} : { error }), children: as !== undefined ? (as(control)) : state.readonly ? (_jsx(ReadValue, { value: textOf(meta, name, value, locale) ?? "—" })) : (controlFor(control, view.type, field?.exact === true, choicesOf(meta, name, locale))) }));
26
- }
27
- function controlFor(control, type, exact, choices) {
28
- const { value, set } = control;
29
- if (choices.length > 0)
30
- return (_jsx(Select, { value: value === null || value === undefined ? "" : String(value), options: choices.map((one) => ({ value: String(one.value), label: one.label })), onChange: set }));
31
- switch (type) {
32
- case "integer":
33
- case "number":
34
- return (_jsx(NumberInput, { value: value === null || value === undefined || value === "" ? "" : Number(value),
35
- // A decimal travels as text so no digit is lost; the server reads it that way back.
36
- onChange: (next) => set(next === "" ? null : exact ? String(next) : next) }));
37
- case "date":
38
- return (_jsx(DatePicker, { value: typeof value === "string" && value !== "" ? value : null, onChange: set }));
39
- case "text[]":
40
- return (_jsx(TextArea, { value: Array.isArray(value) ? value.join("\n") : "", onChange: (next) => set(next
41
- .split("\n")
42
- .map((line) => line.trim())
43
- .filter(Boolean)) }));
44
- default:
45
- return (_jsx(TextInput, { value: value === null || value === undefined ? "" : String(value), onChange: set }));
46
- }
113
+ return (_jsx(Field, { label: view.label, required: state.required && !state.readonly, ...(view.help === undefined ? {} : { hint: view.help }), ...(error === undefined ? {} : { error }), children: as !== undefined ? (as(control)) : relation !== undefined && !relation.many && target !== undefined ? (manyToOne()) : state.readonly ? (_jsx(ReadValue, { value: textOf(meta, name, value, locale) ?? "—" })) : (controlFor(control, view.type, field?.exact === true, choicesOf(meta, name, locale))) }));
47
114
  }
48
115
  /**
49
116
  * The record's «save / discard», for `<Record dirty={…}>`: present only while something changed,
@@ -0,0 +1,84 @@
1
+ import { type AnyRecord } from "@sincpro/criteria";
2
+ import { type LineAdding } from "../../core/lines.js";
3
+ import type { RecordReading } from "../../react/useRecord.js";
4
+ import { type FieldControl } from "./control.js";
5
+ import { type LineEditorState } from "@sincpro/web-ui";
6
+ import { type ReactNode } from "react";
7
+ /** What a control of the screen's own receives for a field of a line: the field's value and
8
+ * how to change it, as any field control, plus the whole line — a widget may write several
9
+ * fields at once (a product and its price). */
10
+ export type LineControl = FieldControl & {
11
+ line: AnyRecord;
12
+ setLine: (next: AnyRecord) => void;
13
+ };
14
+ /** A column that is not a field of the line — its delivery, its buttons: read only. */
15
+ export type LineColumn = {
16
+ /** Must not be the name of a field of the line. */
17
+ id: string;
18
+ header: string;
19
+ cell: (line: AnyRecord) => ReactNode;
20
+ /** What the lines' search reads in it. */
21
+ text?: (line: AnyRecord) => string;
22
+ numeric?: boolean;
23
+ };
24
+ /**
25
+ * How the lines look and are written, when the screen wants it its way — every piece optional,
26
+ * every one falling back to the model's.
27
+ *
28
+ * Context: «defaults, never cages». The model decides the columns and their controls; a screen
29
+ * can choose and order the columns, draw a cell its way, write a field with a widget of its
30
+ * own (in the cell and in the dialog), add columns that are not fields (a line's picking with a
31
+ * button that opens it), or write the whole dialog. What it does not get to do is break where
32
+ * a line is written: a field with its own control fits a cell, and a required field left out of
33
+ * the columns sends the line to the dialog (`addingOf`).
34
+ */
35
+ export type LinesLook = {
36
+ /** Where a line is written: the table when it can be (the default), or the dialog. */
37
+ adding?: LineAdding;
38
+ /** The fields drawn as columns, in order. The dialog still holds every field. */
39
+ columns?: readonly string[];
40
+ /** A field's cell drawn the screen's way, while it reads. */
41
+ cells?: Readonly<Partial<Record<string, (line: AnyRecord) => ReactNode>>>;
42
+ /** A field written with the screen's own widget — in its cell and in the dialog. */
43
+ controls?: Readonly<Partial<Record<string, (control: LineControl) => ReactNode>>>;
44
+ /** Columns that are not fields, after the fields. */
45
+ extra?: readonly LineColumn[];
46
+ /** The whole line's dialog, the screen's way. */
47
+ editor?: (draft: AnyRecord, set: (next: AnyRecord) => void, state: LineEditorState) => ReactNode;
48
+ };
49
+ /**
50
+ * The lines of an aggregate, edited inside its record: web-ui's `LineItems` over the record's
51
+ * edit — what the screen holds is the whole list, and every change writes it back with
52
+ * `edit.set(name, next)`, so it is dirty, previewed, saved and discarded like any field.
53
+ *
54
+ * Context: a one2many of no entity of its own (the lines of an invoice) used to be drawn read
55
+ * only (`RecordLines`). sincpro_framework writes such lines in the aggregate's own command, as
56
+ * the whole list in order; a new line goes without an id (`core/lines`). What `LineItems` does
57
+ * — add, edit, remove with «Deshacer», reorder — is the screen's: only the list that results
58
+ * travels. Each column is a field of the line model (`meta.fields[name].definition`, its
59
+ * scalars: `lineFields`), its control the one its type asks for — a many2one, the picker of its
60
+ * entity (`LineValue`) — its state the line model's hints over the line refined by the server's
61
+ * `items[i]` (`edit.cell`). A server error or warning that points into a cell
62
+ * (`#/values/lines/1/qty`, `["lines", 1, "price"]`) is said IN that cell (web-ui 1.6
63
+ * `cellState`); one about the line as a whole, on the line (`flag`).
64
+ *
65
+ * WHERE a line is written is one decision (`addingOf`): in the TABLE — «Agregar una línea» is
66
+ * its last row, a row is written where it is, the pencil opens the whole line in its dialog —
67
+ * whenever every column a person writes fits a cell; in the DIALOG otherwise, or when the
68
+ * screen asks (`look.adding="editor"`), and then the cells only read. The screen may draw it
69
+ * its way (`LinesLook`) without breaking that rule. A row that cannot be finished where
70
+ * it was opened is a trap, so «inline» is never forced. On a narrow box web-ui draws the lines
71
+ * as cards that open the dialog.
72
+ *
73
+ * Only a WHOLE list is editable: a record that brought one page of 1 000 lines draws them read
74
+ * only (`RecordLines`, «se muestran 50 de 1000»), because a page written back whole deletes
75
+ * every line it did not bring.
76
+ */
77
+ export declare function RecordLinesEditor<T extends AnyRecord>({ record, name, lines, look, }: {
78
+ record: RecordReading<T>;
79
+ name: string;
80
+ /** The list as on screen (`editableLines(edit.values[name])`), never a page. */
81
+ lines: readonly AnyRecord[];
82
+ /** The screen's way, piece by piece. */
83
+ look?: LinesLook;
84
+ }): import("react").JSX.Element;
@@ -0,0 +1,190 @@
1
+ "use client";
2
+ import { jsx as _jsx } from "react/jsx-runtime";
3
+ import { choicesOf } from "@sincpro/criteria";
4
+ import { adviceAt, defaultsOf, errorAt, pathOf } from "../../core/edit.js";
5
+ import { addingOf, blankLine, lineFields, lineKey, moved, sameLine, writtenInCell, } from "../../core/lines.js";
6
+ import { textOf, viewOf } from "../../core/present.js";
7
+ import { entityFor, relationFieldOf, } from "../../core/relation.js";
8
+ import { useEntityFor, useFramework } from "../../react/context.js";
9
+ import { controlFor, RelationPicker, } from "./control.js";
10
+ import { Field, LineItems, ReadValue, } from "@sincpro/web-ui";
11
+ import { useRef } from "react";
12
+ /** How a field of a line reads: a many2one's key by the name of what it points at. */
13
+ function textIn(definition, field, relation, line, locale) {
14
+ const named = relation === undefined
15
+ ? null
16
+ : textOf(definition, relation.relation, line[relation.relation], locale);
17
+ return named ?? textOf(definition, field, line[field], locale) ?? "";
18
+ }
19
+ /**
20
+ * One field of a line, written — in its cell or in its dialog: a many2one of a declared entity
21
+ * is its picker, anything else the control its type asks for.
22
+ *
23
+ * Context: every change is a COPY of the line that keeps its local key (`sameLine`): a new
24
+ * line has no id, and a row whose key changed is another row to the table — it would lose the
25
+ * focus mid-word. A chosen record is kept beside its key so the cell names it at once.
26
+ */
27
+ function LineValue({ definition, field, line, set, label, invalid, locale, inCell, own, }) {
28
+ const relation = relationFieldOf(definition, field);
29
+ const target = useEntityFor(relation?.target);
30
+ const write = (changes) => set(sameLine(line, { ...line, ...changes }));
31
+ if (own !== undefined)
32
+ return own({
33
+ value: line[field],
34
+ set: (next) => write({ [field]: next }),
35
+ readonly: false,
36
+ invalid,
37
+ label,
38
+ standalone: inCell,
39
+ line,
40
+ setLine: (next) => set(sameLine(line, next)),
41
+ });
42
+ if (relation !== undefined && !relation.many && target !== undefined) {
43
+ const key = line[relation.key];
44
+ return (_jsx(RelationPicker, { target: target, value: key === null || key === undefined ? "" : String(key), label: label, ownChooser: true, standalone: inCell, onChange: (id, chosen) => write({ [relation.key]: id, [relation.relation]: chosen ?? null }) }));
45
+ }
46
+ return controlFor({
47
+ value: line[field],
48
+ set: (next) => write({ [field]: next }),
49
+ readonly: false,
50
+ invalid,
51
+ label,
52
+ standalone: inCell,
53
+ }, viewOf(definition, field, locale).type, definition?.fields[field]?.exact === true, choicesOf(definition, field, locale));
54
+ }
55
+ /**
56
+ * The lines of an aggregate, edited inside its record: web-ui's `LineItems` over the record's
57
+ * edit — what the screen holds is the whole list, and every change writes it back with
58
+ * `edit.set(name, next)`, so it is dirty, previewed, saved and discarded like any field.
59
+ *
60
+ * Context: a one2many of no entity of its own (the lines of an invoice) used to be drawn read
61
+ * only (`RecordLines`). sincpro_framework writes such lines in the aggregate's own command, as
62
+ * the whole list in order; a new line goes without an id (`core/lines`). What `LineItems` does
63
+ * — add, edit, remove with «Deshacer», reorder — is the screen's: only the list that results
64
+ * travels. Each column is a field of the line model (`meta.fields[name].definition`, its
65
+ * scalars: `lineFields`), its control the one its type asks for — a many2one, the picker of its
66
+ * entity (`LineValue`) — its state the line model's hints over the line refined by the server's
67
+ * `items[i]` (`edit.cell`). A server error or warning that points into a cell
68
+ * (`#/values/lines/1/qty`, `["lines", 1, "price"]`) is said IN that cell (web-ui 1.6
69
+ * `cellState`); one about the line as a whole, on the line (`flag`).
70
+ *
71
+ * WHERE a line is written is one decision (`addingOf`): in the TABLE — «Agregar una línea» is
72
+ * its last row, a row is written where it is, the pencil opens the whole line in its dialog —
73
+ * whenever every column a person writes fits a cell; in the DIALOG otherwise, or when the
74
+ * screen asks (`look.adding="editor"`), and then the cells only read. The screen may draw it
75
+ * its way (`LinesLook`) without breaking that rule. A row that cannot be finished where
76
+ * it was opened is a trap, so «inline» is never forced. On a narrow box web-ui draws the lines
77
+ * as cards that open the dialog.
78
+ *
79
+ * Only a WHOLE list is editable: a record that brought one page of 1 000 lines draws them read
80
+ * only (`RecordLines`, «se muestran 50 de 1000»), because a page written back whole deletes
81
+ * every line it did not bring.
82
+ */
83
+ export function RecordLinesEditor({ record, name, lines, look = {}, }) {
84
+ const { meta, locale, edit } = record;
85
+ const { entities, metas } = useFramework();
86
+ const definition = meta?.fields[name]?.definition ?? null;
87
+ const identity = definition?.identity || "id";
88
+ const fields = lineFields(definition);
89
+ const shown = look.columns === undefined ? fields : look.columns.filter((one) => fields.includes(one));
90
+ const controls = look.controls ?? {};
91
+ const own = new Set(Object.keys(controls));
92
+ const declared = (target) => entityFor(entities, target, metas.get) !== undefined;
93
+ const adding = addingOf(definition, {
94
+ declared,
95
+ shown,
96
+ own,
97
+ ...(look.adding === undefined ? {} : { asked: look.adding }),
98
+ });
99
+ const writing = !edit.state(name).readonly;
100
+ // Once per render, not per cell: 2 000 lines × 8 fields asked the model 16 000 times.
101
+ const relations = new Map(fields.map((field) => [field, relationFieldOf(definition, field)]));
102
+ const keyOf = (line) => lineKey(line, identity);
103
+ // Where each line is, by its key — once per render: a `findIndex` per line drawn made the
104
+ // flags of 2 000 lines cost 50 ms (quadratic); with the map, a fraction of one.
105
+ const positions = new Map(lines.map((one, i) => [keyOf(one), i]));
106
+ const indexOf = (line) => positions.get(keyOf(line)) ?? lines.length;
107
+ // A callback of `LineItems` can run long after its render — «Deshacer» in a toast, seconds
108
+ // after the line went — so every change starts from the list on screen NOW, never the one of
109
+ // the render that made the callback.
110
+ const now = useRef(lines);
111
+ now.current = lines;
112
+ const write = (change) => edit.set(name, change(now.current));
113
+ const drawn = new Set(shown);
114
+ const fieldColumns = shown.map((field) => {
115
+ const view = viewOf(definition, field, locale);
116
+ const relation = relations.get(field);
117
+ const inCell = writing &&
118
+ adding === "inline" &&
119
+ definition !== null &&
120
+ definition.fields[field]?.readonly !== true &&
121
+ (own.has(field) || writtenInCell(definition, field, declared));
122
+ const ownCell = look.cells?.[field];
123
+ return {
124
+ id: field,
125
+ header: view.label,
126
+ value: (line) => line[field],
127
+ // Drawn as read: «Cemento 50 kg», not «CEM-50»; «1.552,00», not «1552.00».
128
+ cell: ownCell ?? ((line) => textIn(definition, field, relation, line, locale)),
129
+ text: (line) => textIn(definition, field, relation, line, locale),
130
+ numeric: view.type === "number" || view.type === "integer",
131
+ ...(inCell
132
+ ? {
133
+ edit: (line, set) => (_jsx(LineValue, { definition: definition, field: field, line: line, set: set, label: view.label, invalid: false, locale: locale, inCell: true, own: controls[field] })),
134
+ }
135
+ : {}),
136
+ };
137
+ });
138
+ const columns = [
139
+ ...fieldColumns,
140
+ ...(look.extra ?? []).map((one) => ({
141
+ id: one.id,
142
+ header: one.header,
143
+ value: () => null,
144
+ cell: one.cell,
145
+ ...(one.text === undefined ? {} : { text: one.text }),
146
+ ...(one.numeric === undefined ? {} : { numeric: one.numeric }),
147
+ })),
148
+ ];
149
+ return (_jsx(LineItems, { lines: lines, columns: columns, getLineId: keyOf, mode: writing ? "edit" : "read", adding: adding, onChange: (key, next) => write((all) => all.map((one) => (keyOf(one) === key ? sameLine(one, next) : one))), newLine: () => blankLine(defaultsOf(definition), identity), onAdd: (line) => write((all) => [...all, line]), onRemove: (key) => write((all) => all.filter((one) => keyOf(one) !== key)), onRestore: (line, index) => write((all) => [...all.slice(0, index), line, ...all.slice(index)]), onReorder: (key, before) => write((all) => moved(all, identity, key, before)),
150
+ // A cell says its own (web-ui 1.6 `cellState`): the line model's hints refined by the
151
+ // server's `items[i]`, the error pointing at it (under its value) and its warning.
152
+ cellState: (line, column) => {
153
+ const index = indexOf(line);
154
+ const at = `${name}/${index}/${column}`;
155
+ const state = edit.cell(name, index, column);
156
+ const error = errorAt(edit.errors, at);
157
+ const warned = adviceAt(edit.advice, at)[0];
158
+ return {
159
+ readonly: state.readonly,
160
+ required: state.required,
161
+ hidden: !state.visible,
162
+ ...(error === undefined ? {} : { error }),
163
+ ...(warned === undefined ? {} : { flag: { tone: "warn", label: warned.message } }),
164
+ };
165
+ },
166
+ // The line's own flag: what points at the line and at no cell drawn — the line as a
167
+ // whole, or a field it has no column for (an id the server does not know).
168
+ flag: (line) => {
169
+ const at = `${name}/${indexOf(line)}`;
170
+ const onLine = (key) => key === at ||
171
+ (key.startsWith(`${at}/`) && !drawn.has(key.slice(at.length + 1).split("/")[0]));
172
+ const error = Object.entries(edit.errors).find(([key]) => onLine(key))?.[1];
173
+ if (error !== undefined)
174
+ return { tone: "bad", label: error };
175
+ const warned = edit.advice.find((one) => onLine(pathOf(one.path ?? [one.field ?? ""])));
176
+ return warned === undefined ? null : { tone: "warn", label: warned.message };
177
+ }, editor: (draft, set, state) => {
178
+ if (look.editor !== undefined)
179
+ return look.editor(draft, set, state);
180
+ const index = indexOf(draft);
181
+ return (_jsx("div", { className: "grid gap-3", children: fields.map((field) => {
182
+ const state = edit.cell(name, index, field);
183
+ if (!state.visible)
184
+ return null;
185
+ const view = viewOf(definition, field, locale);
186
+ const error = edit.errors[`${name}/${index}/${field}`];
187
+ return (_jsx(Field, { label: view.label, required: state.required && !state.readonly, ...(error === undefined ? {} : { error }), children: state.readonly ? (_jsx(ReadValue, { value: textIn(definition, field, relations.get(field), draft, locale) || "—" })) : (_jsx(LineValue, { definition: definition, field: field, line: draft, set: set, label: view.label, invalid: error !== undefined, locale: locale, inCell: false, own: controls[field] })) }, field));
188
+ }) }));
189
+ } }));
190
+ }