@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
package/dist/core/edit.js CHANGED
@@ -15,7 +15,13 @@ export function fieldStateOf(meta, name, values, fromServer) {
15
15
  ? true
16
16
  : holds(values, field.visible_when, meta),
17
17
  };
18
- return { ...own, ...fromServer?.[name] };
18
+ // `items` is the lines' own word, read with `lineStatesOf` — never a state of the field.
19
+ const { items: _lines, ...server } = fromServer?.[name] ?? {};
20
+ return { ...own, ...server };
21
+ }
22
+ /** Each line's states of a list of records, as the server said them — by position. */
23
+ export function lineStatesOf(fromServer, name) {
24
+ return fromServer?.[name]?.items ?? [];
19
25
  }
20
26
  /** The fields whose value differs from the record's — what a save or a draft sends. */
21
27
  export function changesOf(record, values) {
@@ -39,13 +45,81 @@ export function missingOf(meta, values, fromServer) {
39
45
  return state.required && state.visible && !state.readonly && empty;
40
46
  });
41
47
  }
42
- /** The server's word on a field that did not validate: `errors[].pointer` is a JSON pointer. */
48
+ /**
49
+ * Where the server's word points inside the record, as one key: `"discount"`, `"lines/1/qty"`.
50
+ * A JSON pointer (RFC 6901), bare (`/discount`) or as a fragment (`#/values/lines/1/qty`) — the
51
+ * command's `values/` envelope dropped, `~1`/`~0` read back — or a path (`["lines", 1, "qty"]`).
52
+ * Errors and warnings are read with the same rule, so both land on the same cell.
53
+ */
54
+ export function pathOf(at) {
55
+ if (typeof at !== "string")
56
+ return at.map(String).join("/");
57
+ const segments = at
58
+ .replace(/^#/, "")
59
+ .replace(/^\//, "")
60
+ .split("/")
61
+ .map((one) => one.replace(/~1/g, "/").replace(/~0/g, "~"));
62
+ if (segments[0] === "values" && segments.length > 1)
63
+ segments.shift();
64
+ return segments.join("/");
65
+ }
66
+ /**
67
+ * The server's word on what did not validate, by where it points (`pathOf`): a field's own
68
+ * error under its name, a line's cell's under its whole path (`lines/1/qty`). The first word for
69
+ * a place wins. `errorAt` reads a field's, its lines' included.
70
+ */
43
71
  export function errorsByField(errors) {
44
72
  const found = {};
45
73
  for (const error of errors ?? []) {
46
- const name = error.pointer.replace(/^\/(values\/)?/, "").split("/")[0] ?? "";
47
- if (name !== "" && found[name] === undefined)
48
- found[name] = error.detail;
74
+ const at = pathOf(error.pointer);
75
+ if (at !== "" && found[at] === undefined)
76
+ found[at] = error.detail;
49
77
  }
50
78
  return found;
51
79
  }
80
+ /** The error at `at` or under it (`lines` finds `lines/1/qty`): what marks a field invalid. */
81
+ export function errorAt(errors, at) {
82
+ const own = errors[at];
83
+ if (own !== undefined)
84
+ return own;
85
+ const under = Object.keys(errors).find((key) => key.startsWith(`${at}/`));
86
+ return under === undefined ? undefined : errors[under];
87
+ }
88
+ /** The warnings at `at` or under it — a line's (`lines/1`) finds its cells'. One with no path
89
+ * is placed by its field. */
90
+ export function adviceAt(advice, at) {
91
+ return advice.filter((one) => {
92
+ const key = one.path !== undefined && one.path.length > 0 ? pathOf(one.path) : (one.field ?? "");
93
+ return key === at || key.startsWith(`${at}/`);
94
+ });
95
+ }
96
+ /**
97
+ * A record that does not exist yet: the defaults the model publishes for each field
98
+ * (`FieldMeta.default`, sincpro_framework's `defaults_of`), and nothing else.
99
+ *
100
+ * defaultsOf(invoiceMeta) -> { state: "draft", payment: "cash", discount: "0" }
101
+ */
102
+ export function defaultsOf(meta) {
103
+ const values = {};
104
+ for (const [name, field] of Object.entries(meta?.fields ?? {}))
105
+ if (field.default !== null && field.default !== undefined)
106
+ values[name] = field.default;
107
+ return values;
108
+ }
109
+ /**
110
+ * What a create sends: every value on screen the caller may write. A field the model marks
111
+ * `readonly` is the server's to fill (the number, the totals), and an empty one is left for
112
+ * the server's own default — never sent as `""`.
113
+ */
114
+ export function creationOf(meta, values) {
115
+ const sent = {};
116
+ for (const [name, value] of Object.entries(values)) {
117
+ const field = meta?.fields[name];
118
+ if (field?.readonly === true)
119
+ continue;
120
+ if (value === undefined || value === null || value === "")
121
+ continue;
122
+ sent[name] = value;
123
+ }
124
+ return sent;
125
+ }
@@ -1,4 +1,5 @@
1
1
  import type { AnyRecord } from "@sincpro/criteria";
2
+ import type { SummaryFields } from "./summary.js";
2
3
  import type { Method } from "./transport.js";
3
4
  /**
4
5
  * Everything a screen needs to know about where an entity lives on the server, declared once.
@@ -13,6 +14,7 @@ import type { Method } from "./transport.js";
13
14
  *
14
15
  * export const invoices = entity<Invoice>("billing:invoice", {
15
16
  * list: "/invoices",
17
+ * create: "POST /invoices",
16
18
  * save: "PUT /invoices/{id}",
17
19
  * preview: "POST /invoices/preview",
18
20
  * commands: { confirm: "POST /invoices/{id}/confirm", cancel: "POST /invoices/{id}/cancel" },
@@ -27,12 +29,21 @@ export type Entity<T extends AnyRecord = AnyRecord> = {
27
29
  /** Where the workspace finds it: the list without an id, one record with it — the shape of a
28
30
  * composer `ResourceRef`, built here so no screen writes `{ domain, kind, id }` by hand. */
29
31
  ref: (id?: string) => EntityRef;
32
+ /** A record that does not exist yet — the form that creates one. Its view is the record's.
33
+ * With `values`, the form starts with them over the model's defaults: an invoice created
34
+ * from its customer starts with that customer (`startingValuesOf`). */
35
+ newRef: (values?: AnyRecord) => EntityRef;
36
+ /** Its list opened to CHOOSE one: a row answers whoever asked (composer's `api.pick`). With
37
+ * `query`, the list opens on that literal search — what was typed in the picker. */
38
+ chooserRef: (query?: string) => EntityRef;
30
39
  /** The route of its list. */
31
40
  list: string;
32
41
  /** The route of one record. */
33
42
  one: (id: string) => string;
34
43
  /** Its Commands, by name. */
35
44
  commands: Readonly<Record<string, WriteRoute>>;
45
+ /** How a new record is created: the list's own route, usually. */
46
+ create?: WriteRoute;
36
47
  /** How an edit is saved: the record's own route with `{id}`. */
37
48
  save?: WriteRoute;
38
49
  /** «What does this record become?» before saving — sincpro_framework's `Preview`. */
@@ -44,6 +55,12 @@ export type Entity<T extends AnyRecord = AnyRecord> = {
44
55
  route: string;
45
56
  type: string;
46
57
  };
58
+ /** Which fields are its description, state, picture… when they are not the conventional
59
+ * ones (`summaryOf`). Empty: the convention decides. */
60
+ summary: SummaryFields;
61
+ /** The aggregate it is, as a relation of another model names it (`relation: "Cliente"`).
62
+ * Without it, the `aggregate` of its model definition, once known. */
63
+ aggregate?: string;
47
64
  /** Only carries the record type; never read. */
48
65
  readonly _record?: T;
49
66
  };
@@ -52,7 +69,29 @@ export type EntityRef = {
52
69
  domain: string;
53
70
  kind: string;
54
71
  id?: string;
72
+ params?: Readonly<Record<string, string>>;
55
73
  };
74
+ /**
75
+ * The params that say what a reference without an id is for: `new` is the form of a record
76
+ * that does not exist yet, `pick` is the list opened to choose one. Params, because they are
77
+ * what a composer reference carries and survives a reload with.
78
+ */
79
+ export declare const NEW_PARAM = "new";
80
+ export declare const PICK_PARAM = "pick";
81
+ /** What was typed where the chooser was asked for: its list opens on that search. */
82
+ export declare const QUERY_PARAM = "q";
83
+ /** The list a record was opened from (its `Trail`): «3 / 64» and the arrows to its neighbours. */
84
+ export declare const TRAIL_PARAM = "from";
85
+ /** What a new record starts with, as JSON: one param keeps each value's type (a number stays
86
+ * a number), where a param per field would turn all of them into text. */
87
+ export declare const WITH_PARAM = "with";
88
+ /**
89
+ * What a new record's reference says it starts with (`newRef(values)`), or nothing.
90
+ *
91
+ * Context: a reference survives a reload and a link, so its params can be anything a person
92
+ * typed in the address bar — a value that is not a JSON object is not a start, never an error.
93
+ */
94
+ export declare function startingValuesOf(ref: Pick<EntityRef, "params">): AnyRecord;
56
95
  /** A write: its method and its path, `{id}` where the record's key goes. */
57
96
  export type WriteRoute = {
58
97
  method: Method;
@@ -64,6 +103,8 @@ export type EntityRoutes = {
64
103
  one?: string;
65
104
  /** `"POST /invoices/{id}/confirm"`, by name. */
66
105
  commands?: Readonly<Record<string, string>>;
106
+ /** `"POST /invoices"`: where a new record goes. */
107
+ create?: string;
67
108
  save?: string;
68
109
  preview?: string;
69
110
  draft?: string;
@@ -71,6 +112,11 @@ export type EntityRoutes = {
71
112
  route: string;
72
113
  type: string;
73
114
  };
115
+ /** `{ image: "logo", state: "estado_pago", person: true }` — not a route, but declared once
116
+ * with the rest of what a screen should not have to know. */
117
+ summary?: SummaryFields;
118
+ /** `"Cliente"`: what a many2one of another model calls it, so a form resolves it alone. */
119
+ aggregate?: string;
74
120
  };
75
121
  /** `"POST /invoices/{id}/confirm"` → its method and path. A write without a method is a bug. */
76
122
  export declare function writeRoute(text: string): WriteRoute;
@@ -1,3 +1,37 @@
1
+ /**
2
+ * The params that say what a reference without an id is for: `new` is the form of a record
3
+ * that does not exist yet, `pick` is the list opened to choose one. Params, because they are
4
+ * what a composer reference carries and survives a reload with.
5
+ */
6
+ export const NEW_PARAM = "new";
7
+ export const PICK_PARAM = "pick";
8
+ /** What was typed where the chooser was asked for: its list opens on that search. */
9
+ export const QUERY_PARAM = "q";
10
+ /** The list a record was opened from (its `Trail`): «3 / 64» and the arrows to its neighbours. */
11
+ export const TRAIL_PARAM = "from";
12
+ /** What a new record starts with, as JSON: one param keeps each value's type (a number stays
13
+ * a number), where a param per field would turn all of them into text. */
14
+ export const WITH_PARAM = "with";
15
+ /**
16
+ * What a new record's reference says it starts with (`newRef(values)`), or nothing.
17
+ *
18
+ * Context: a reference survives a reload and a link, so its params can be anything a person
19
+ * typed in the address bar — a value that is not a JSON object is not a start, never an error.
20
+ */
21
+ export function startingValuesOf(ref) {
22
+ const written = ref.params?.[WITH_PARAM];
23
+ if (written === undefined)
24
+ return {};
25
+ try {
26
+ const read = JSON.parse(written);
27
+ return read !== null && typeof read === "object" && !Array.isArray(read)
28
+ ? read
29
+ : {};
30
+ }
31
+ catch {
32
+ return {};
33
+ }
34
+ }
1
35
  const METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);
2
36
  /** `"POST /invoices/{id}/confirm"` → its method and path. A write without a method is a bug. */
3
37
  export function writeRoute(text) {
@@ -21,12 +55,35 @@ export function entity(key, routes) {
21
55
  domain,
22
56
  kind,
23
57
  ref: (id) => ({ domain, kind, ...(id === undefined || id === "" ? {} : { id }) }),
58
+ newRef: (values) => ({
59
+ domain,
60
+ kind,
61
+ params: {
62
+ [NEW_PARAM]: "1",
63
+ ...(values === undefined || Object.keys(values).length === 0
64
+ ? {}
65
+ : { [WITH_PARAM]: JSON.stringify(values) }),
66
+ },
67
+ }),
68
+ chooserRef: (query) => ({
69
+ domain,
70
+ kind,
71
+ params: {
72
+ [PICK_PARAM]: "1",
73
+ ...(query === undefined || query.trim() === ""
74
+ ? {}
75
+ : { [QUERY_PARAM]: query.trim() }),
76
+ },
77
+ }),
24
78
  list: routes.list,
25
79
  one: (id) => template.replace("{id}", encodeURIComponent(id)),
26
80
  commands: Object.fromEntries(Object.entries(routes.commands ?? {}).map(([name, text]) => [name, writeRoute(text)])),
81
+ ...(routes.create === undefined ? {} : { create: writeRoute(routes.create) }),
27
82
  ...(routes.save === undefined ? {} : { save: writeRoute(routes.save) }),
28
83
  ...(routes.preview === undefined ? {} : { preview: writeRoute(routes.preview) }),
29
84
  ...(routes.draft === undefined ? {} : { draft: writeRoute(routes.draft) }),
30
85
  ...(routes.history === undefined ? {} : { history: routes.history }),
86
+ summary: routes.summary ?? {},
87
+ ...(routes.aggregate === undefined ? {} : { aggregate: routes.aggregate }),
31
88
  };
32
89
  }
@@ -0,0 +1,21 @@
1
+ import type { Meta } from "@sincpro/criteria";
2
+ import { type SummaryFields } from "./summary.js";
3
+ /**
4
+ * What a record's form shows when the screen names nothing: its fields, and the pages beside
5
+ * them — read from the model, in the order it declares.
6
+ *
7
+ * Context: the default form must be useful on any entity, not a dump of every key. So:
8
+ *
9
+ * - the bookkeeping (`version`, `updated_at`) and who made and changed it are not fields: the
10
+ * paper says them on its last line (`Record.Audit`); the picture is not a text box;
11
+ * - a read-only identity is the record's name, not a field to look at;
12
+ * - a many2one is written by its KEY (`customer_id`, a picker of customers): the expanded
13
+ * relation beside it (`customer`) would be the same thing twice;
14
+ * - a one2many is a page of its own — a list, not a field;
15
+ * - a value object, and a many2many the backend cannot write yet, are left to the screen.
16
+ */
17
+ export type FormLayout = {
18
+ fields: string[];
19
+ pages: string[];
20
+ };
21
+ export declare function formOf(meta: Meta | null | undefined, summary?: SummaryFields): FormLayout;
@@ -0,0 +1,30 @@
1
+ import { BOOKKEEPING } from "./present.js";
2
+ import { summaryFieldsOf } from "./summary.js";
3
+ export function formOf(meta, summary = {}) {
4
+ if (!meta)
5
+ return { fields: [], pages: [] };
6
+ const parts = summaryFieldsOf(meta, {}, summary);
7
+ const told = new Set([parts.createdAt, parts.createdBy, parts.updatedAt, parts.updatedBy, parts.image].filter((name) => name !== undefined));
8
+ const keys = new Set(Object.values(meta.fields)
9
+ .map((field) => (field.kind === "relation" ? field.identified_by : undefined))
10
+ .filter((name) => typeof name === "string" && name in meta.fields));
11
+ const fields = [];
12
+ const pages = [];
13
+ for (const [name, field] of Object.entries(meta.fields)) {
14
+ if (BOOKKEEPING.has(name) || told.has(name))
15
+ continue;
16
+ if (name === meta.identity && field.readonly)
17
+ continue;
18
+ if (field.kind === "embedded")
19
+ continue;
20
+ if (field.kind === "relation") {
21
+ if (field.type === "one2many")
22
+ pages.push(name);
23
+ else if (!field.many && !(field.identified_by && keys.has(field.identified_by)))
24
+ fields.push(name);
25
+ continue;
26
+ }
27
+ fields.push(name);
28
+ }
29
+ return { fields, pages };
30
+ }
@@ -5,15 +5,23 @@
5
5
  */
6
6
  export { type CachedTransport, cachedTransport, type CacheOptions, } from "./cache.js";
7
7
  export { ENGLISH_FRAMEWORK_COPY, type FrameworkCopy, frameworkCopy, installFrameworkCopy, SPANISH_FRAMEWORK_COPY, } from "./copy.js";
8
- export { changesOf, errorsByField, type FieldState, fieldStateOf, type FieldStates, missingOf, } from "./edit.js";
9
- export { type Entity, entity, type EntityRef, type EntityRoutes, pathFor, type WriteRoute, writeRoute, } from "./entity.js";
8
+ export { type Advice, adviceAt, changesOf, creationOf, defaultsOf, errorAt, errorsByField, type FieldState, fieldStateOf, type FieldStates, lineStatesOf, missingOf, pathOf, type ServerFieldState, } from "./edit.js";
9
+ export { type Entity, entity, type EntityRef, type EntityRoutes, NEW_PARAM, pathFor, PICK_PARAM, QUERY_PARAM, startingValuesOf, TRAIL_PARAM, WITH_PARAM, type WriteRoute, writeRoute, } from "./entity.js";
10
+ export { type FormLayout, formOf } from "./form.js";
10
11
  export { type HistoryEntry, historyOf } from "./history.js";
12
+ export { addingOf, type AddingRule, blankLine, type Declared, editableLines, type LineAdding, lineFields, lineKey, linesAnswered, moved, sameLine, writtenInCell, } from "./lines.js";
13
+ export { defineList, type GroupLevel, isList, type ListDefinition, type ListSpec, type NamedFilter, scopeOf, } from "./list.js";
11
14
  export { lookupOf, type LookupOption } from "./lookup.js";
15
+ export { detailOf, measuresOf, sumsOf } from "./measure.js";
12
16
  export { type MemoryOptions, type MemoryTable, memoryTransport, } from "./memory.js";
13
17
  export { defineMeta, field, type FieldOptions, type MetaSpec, type Words, } from "./meta.js";
14
18
  export { type MetaStore, metaStore } from "./metas.js";
15
19
  export { BOOKKEEPING, defaultFields, type FieldView, sortKeyOf, textOf, viewOf, } from "./present.js";
16
20
  export { type Related, relatedOf } from "./related.js";
21
+ export { entityFor, type RelationField, relationFieldOf, } from "./relation.js";
17
22
  export { type RestOptions, restTransport, urlOf } from "./rest.js";
23
+ export { type RetryKeys, retryKeys, unanswered } from "./retry.js";
18
24
  export { completeMeta, type JsonSchema, metaFromSchema, type SchemaComponents, } from "./schema.js";
19
- export { type Draft, explain, type Method, type One, type Transport, TransportError, } from "./transport.js";
25
+ export { type RecordSummary, type SummaryFields, summaryFieldsOf, summaryOf, type SummaryPart, } from "./summary.js";
26
+ export { placeOf, stepIn, type Trail } from "./trail.js";
27
+ export { type Draft, explain, type Method, type One, type SendOptions, type Transport, TransportError, } from "./transport.js";
@@ -5,15 +5,23 @@
5
5
  */
6
6
  export { cachedTransport, } from "./cache.js";
7
7
  export { ENGLISH_FRAMEWORK_COPY, frameworkCopy, installFrameworkCopy, SPANISH_FRAMEWORK_COPY, } from "./copy.js";
8
- export { changesOf, errorsByField, fieldStateOf, missingOf, } from "./edit.js";
9
- export { entity, pathFor, writeRoute, } from "./entity.js";
8
+ export { adviceAt, changesOf, creationOf, defaultsOf, errorAt, errorsByField, fieldStateOf, lineStatesOf, missingOf, pathOf, } from "./edit.js";
9
+ export { entity, NEW_PARAM, pathFor, PICK_PARAM, QUERY_PARAM, startingValuesOf, TRAIL_PARAM, WITH_PARAM, writeRoute, } from "./entity.js";
10
+ export { formOf } from "./form.js";
10
11
  export { historyOf } from "./history.js";
12
+ export { addingOf, blankLine, editableLines, lineFields, lineKey, linesAnswered, moved, sameLine, writtenInCell, } from "./lines.js";
13
+ export { defineList, isList, scopeOf, } from "./list.js";
11
14
  export { lookupOf } from "./lookup.js";
15
+ export { detailOf, measuresOf, sumsOf } from "./measure.js";
12
16
  export { memoryTransport, } from "./memory.js";
13
17
  export { defineMeta, field, } from "./meta.js";
14
18
  export { metaStore } from "./metas.js";
15
19
  export { BOOKKEEPING, defaultFields, sortKeyOf, textOf, viewOf, } from "./present.js";
16
20
  export { relatedOf } from "./related.js";
21
+ export { entityFor, relationFieldOf, } from "./relation.js";
17
22
  export { restTransport, urlOf } from "./rest.js";
23
+ export { retryKeys, unanswered } from "./retry.js";
18
24
  export { completeMeta, metaFromSchema, } from "./schema.js";
25
+ export { summaryFieldsOf, summaryOf, } from "./summary.js";
26
+ export { placeOf, stepIn } from "./trail.js";
19
27
  export { explain, TransportError, } from "./transport.js";
@@ -0,0 +1,53 @@
1
+ import type { AnyRecord, Meta } from "@sincpro/criteria";
2
+ /** The key a line is drawn and found by: its identity, or a local one while it has none. */
3
+ export declare function lineKey(line: AnyRecord, identity: string): string;
4
+ /** `next` is `line` edited: it keeps the line's local key. */
5
+ export declare function sameLine<T extends AnyRecord>(line: AnyRecord, next: T): T;
6
+ /** What the server answered about the list it was sent, each line keeping its key by position. */
7
+ export declare function linesAnswered(sent: readonly AnyRecord[], answered: readonly AnyRecord[]): AnyRecord[];
8
+ /**
9
+ * The lines a form can edit, or `null` when it holds only part of them: a list written back
10
+ * whole from one page would delete every line the page did not bring.
11
+ */
12
+ export declare function editableLines(value: unknown): AnyRecord[] | null;
13
+ /** A blank line: the line model's defaults, never its identity — the server mints that. */
14
+ export declare function blankLine(defaults: AnyRecord, identity: string): AnyRecord;
15
+ /** The list with the line `key` moved before `before` (`null`: to the end). */
16
+ export declare function moved<T extends AnyRecord>(lines: readonly T[], identity: string, key: string, before: string | null): T[];
17
+ /** Where «Agregar una línea» writes the new line: a row of the table, or the line's dialog. */
18
+ export type LineAdding = "inline" | "editor";
19
+ /** Whether an aggregate of the application answers for `target` («Producto»). */
20
+ export type Declared = (target: string) => boolean;
21
+ /**
22
+ * The fields a line is drawn and written by: its scalars, as a form's — never its identity
23
+ * (the server mints it) nor the bookkeeping. A many2one is its key (`product_code`), which the
24
+ * screen names by its relation (`product`).
25
+ */
26
+ export declare function lineFields(definition: Meta | null): string[];
27
+ /**
28
+ * Whether a field of a line can be written inside its cell.
29
+ *
30
+ * Context: a cell holds a control as wide as its column. A many2one is a picker only when the
31
+ * application declared the entity it points at — otherwise its key is an id nobody types.
32
+ * A date and time, an embedded value or anything the table has no control for needs the
33
+ * dialog's room.
34
+ */
35
+ export declare function writtenInCell(definition: Meta, field: string, declared: Declared): boolean;
36
+ /** What decides where a line is written, besides its model. */
37
+ export type AddingRule = {
38
+ /** Whether the application declared the entity a relation points at. */
39
+ declared: Declared;
40
+ /** The screen's choice: «editor» always holds, «inline» only where it works. */
41
+ asked?: LineAdding;
42
+ /** The fields drawn as columns, when the screen chose them. Without it, every line field. */
43
+ shown?: readonly string[];
44
+ /** The fields the screen writes with a control of its own: they fit a cell whatever their
45
+ * type — the screen said how. */
46
+ own?: ReadonlySet<string>;
47
+ };
48
+ /**
49
+ * How «Agregar una línea» adds: in the table when every column a person may write fits a cell
50
+ * and nothing required is left out of the columns; in the dialog otherwise — a row that cannot
51
+ * be finished where it was opened is a trap.
52
+ */
53
+ export declare function addingOf(definition: Meta | null, rule: AddingRule): LineAdding;
@@ -0,0 +1,120 @@
1
+ import { BOOKKEEPING, defaultFields } from "./present.js";
2
+ import { relatedOf } from "./related.js";
3
+ import { relationFieldOf } from "./relation.js";
4
+ /**
5
+ * The lines of an aggregate as a form edits them: the whole list, in order.
6
+ *
7
+ * Context: sincpro_framework writes the lines of an aggregate in the same command as the
8
+ * aggregate — the list as the form holds it, whole and in order, with the version it was read
9
+ * at (without it, a whole list would delete a line someone else added). A line that came from
10
+ * the server carries its id; a new one goes WITHOUT one — the server refuses an id it does not
11
+ * know and mints its own. So a new line's key on screen is kept APART from the line (a weak map
12
+ * on the line object), carried to each edited copy, and matched by POSITION to what the server
13
+ * answers about the list it was sent. Adding, removing, undoing and reordering are the screen's:
14
+ * nothing about them travels but the resulting list — no per-line commands on the wire.
15
+ */
16
+ const keys = new WeakMap();
17
+ let minted = 0;
18
+ /** The key a line is drawn and found by: its identity, or a local one while it has none. */
19
+ export function lineKey(line, identity) {
20
+ const own = line[identity];
21
+ if (own !== undefined && own !== null && own !== "")
22
+ return String(own);
23
+ let key = keys.get(line);
24
+ if (key === undefined) {
25
+ key = `new-${++minted}`;
26
+ keys.set(line, key);
27
+ }
28
+ return key;
29
+ }
30
+ /** `next` is `line` edited: it keeps the line's local key. */
31
+ export function sameLine(line, next) {
32
+ const key = keys.get(line);
33
+ if (key !== undefined && !keys.has(next))
34
+ keys.set(next, key);
35
+ return next;
36
+ }
37
+ /** What the server answered about the list it was sent, each line keeping its key by position. */
38
+ export function linesAnswered(sent, answered) {
39
+ return answered.map((line, i) => (sent[i] === undefined ? line : sameLine(sent[i], line)));
40
+ }
41
+ /**
42
+ * The lines a form can edit, or `null` when it holds only part of them: a list written back
43
+ * whole from one page would delete every line the page did not bring.
44
+ */
45
+ export function editableLines(value) {
46
+ if (Array.isArray(value))
47
+ return value;
48
+ const related = relatedOf(value);
49
+ return related.partial ? null : [...related.items];
50
+ }
51
+ /** A blank line: the line model's defaults, never its identity — the server mints that. */
52
+ export function blankLine(defaults, identity) {
53
+ const { [identity]: _id, ...rest } = defaults;
54
+ return { ...rest };
55
+ }
56
+ /** The list with the line `key` moved before `before` (`null`: to the end). */
57
+ export function moved(lines, identity, key, before) {
58
+ const line = lines.find((one) => lineKey(one, identity) === key);
59
+ if (line === undefined)
60
+ return [...lines];
61
+ const rest = lines.filter((one) => one !== line);
62
+ const at = before === null
63
+ ? rest.length
64
+ : rest.findIndex((one) => lineKey(one, identity) === before);
65
+ return [
66
+ ...rest.slice(0, at < 0 ? rest.length : at),
67
+ line,
68
+ ...rest.slice(at < 0 ? rest.length : at),
69
+ ];
70
+ }
71
+ /** The value types a cell has a control for: each one fits the width of a column. */
72
+ const CELL_TYPES = new Set([
73
+ "text",
74
+ "integer",
75
+ "number",
76
+ "date",
77
+ "boolean",
78
+ "text[]",
79
+ ]);
80
+ /**
81
+ * The fields a line is drawn and written by: its scalars, as a form's — never its identity
82
+ * (the server mints it) nor the bookkeeping. A many2one is its key (`product_code`), which the
83
+ * screen names by its relation (`product`).
84
+ */
85
+ export function lineFields(definition) {
86
+ if (definition === null)
87
+ return [];
88
+ return defaultFields(definition).filter((field) => field !== definition.identity && !BOOKKEEPING.has(field));
89
+ }
90
+ /**
91
+ * Whether a field of a line can be written inside its cell.
92
+ *
93
+ * Context: a cell holds a control as wide as its column. A many2one is a picker only when the
94
+ * application declared the entity it points at — otherwise its key is an id nobody types.
95
+ * A date and time, an embedded value or anything the table has no control for needs the
96
+ * dialog's room.
97
+ */
98
+ export function writtenInCell(definition, field, declared) {
99
+ const relation = relationFieldOf(definition, field);
100
+ if (relation !== undefined)
101
+ return !relation.many && declared(relation.target);
102
+ return CELL_TYPES.has(definition.fields[field]?.type ?? "");
103
+ }
104
+ /**
105
+ * How «Agregar una línea» adds: in the table when every column a person may write fits a cell
106
+ * and nothing required is left out of the columns; in the dialog otherwise — a row that cannot
107
+ * be finished where it was opened is a trap.
108
+ */
109
+ export function addingOf(definition, rule) {
110
+ if (rule.asked === "editor" || definition === null)
111
+ return "editor";
112
+ const fields = lineFields(definition);
113
+ const shown = new Set(rule.shown ?? fields);
114
+ const writable = (field) => definition.fields[field]?.readonly !== true;
115
+ const fits = (field) => rule.own?.has(field) === true || writtenInCell(definition, field, rule.declared);
116
+ const ok = fields
117
+ .filter(writable)
118
+ .every((field) => shown.has(field) ? fits(field) : definition.fields[field]?.required !== true);
119
+ return ok ? "inline" : "editor";
120
+ }
@@ -0,0 +1,64 @@
1
+ import type { AnyRecord, Criteria, Expression, Grain, Sort } from "@sincpro/criteria";
2
+ import type { Entity, EntityRef } from "./entity.js";
3
+ /**
4
+ * A named way of looking at an entity: «Por cobrar», «Borradores», «Mis tickets».
5
+ *
6
+ * Context: an ERP rarely shows ONE list of invoices. It shows the invoices to collect, the
7
+ * drafts, the overdue ones — the same entity under a fixed cut, each with its own columns,
8
+ * its own named filters and maybe its own grouping (Odoo's window actions with a `domain`).
9
+ * Written by hand, each of those is a screen repeating `useListing` options and `EntityList`
10
+ * props. Declared once, it is data: `useListing(list)` reads it, `EntityList` draws it,
11
+ * `listView(list)` opens it in the workspace with its own «Go to».
12
+ *
13
+ * The SCOPE is the cut: always asked, ANDed under whatever is searched, filtered or grouped,
14
+ * and never in the search bar — a person cannot remove the «por cobrar» of «Por cobrar». It is
15
+ * a convenience of the screen, not protection: the server answers whatever it allows.
16
+ *
17
+ * export const porCobrar = defineList(facturas, {
18
+ * id: "por-cobrar",
19
+ * title: "Por cobrar",
20
+ * scope: { where: { field: "state", operator: "=", value: "posted" } },
21
+ * columns: ["number", "customer", "due_date", "amount_total"],
22
+ * filters: [{ id: "vencidas", label: "Vencidas", where: … }],
23
+ * });
24
+ */
25
+ export type ListDefinition<T extends AnyRecord = AnyRecord> = {
26
+ entity: Entity<T>;
27
+ /** Unique within its entity: `"por-cobrar"`. */
28
+ id: string;
29
+ /** `domain:kind-id` — how the workspace and the definitions store refer to it. */
30
+ key: string;
31
+ /** Where the workspace opens it: a kind of its own, so ⌘K can offer it by name. */
32
+ ref: () => EntityRef;
33
+ title: string;
34
+ description?: string;
35
+ /** The fixed cut, ANDed under everything a person searches or filters. */
36
+ scope?: Criteria<T>;
37
+ /** The order it opens in, before anyone clicks a header. */
38
+ order?: Sort;
39
+ /** The fields shown, in order. */
40
+ columns?: readonly string[];
41
+ /** The cuts it offers by name in the search bar. */
42
+ filters?: readonly NamedFilter<T>[];
43
+ /** The faces it offers, the first one shown. */
44
+ views?: readonly ("table" | "rows" | "board" | "sheet" | "pivot")[];
45
+ /** Grouped from the start — the server counts the groups. */
46
+ groupBy?: readonly GroupLevel[];
47
+ };
48
+ /** A cut offered by name in the search bar: «sólo pagadas», «vencidas». */
49
+ export type NamedFilter<T> = {
50
+ id: string;
51
+ label: string;
52
+ where: Expression<T>;
53
+ };
54
+ /** One level of a grouping: by which field, and by which cut of time when it is a date. */
55
+ export type GroupLevel = {
56
+ field: string;
57
+ grain?: Grain;
58
+ };
59
+ export type ListSpec<T extends AnyRecord> = Omit<ListDefinition<T>, "entity" | "key" | "ref">;
60
+ export declare function defineList<T extends AnyRecord>(entity: Entity<T>, spec: ListSpec<T>): ListDefinition<T>;
61
+ /** Whether what `useListing` was handed is a list definition rather than a bare entity. */
62
+ export declare function isList<T extends AnyRecord>(given: Entity<T> | ListDefinition<T>): given is ListDefinition<T>;
63
+ /** The criteria a definition always asks: its scope, in its order. */
64
+ export declare function scopeOf<T extends AnyRecord>(list: ListDefinition<T>): Criteria<T>;
@@ -0,0 +1,22 @@
1
+ export function defineList(entity, spec) {
2
+ if (!/^[a-z0-9][a-z0-9-]*$/.test(spec.id))
3
+ throw new Error(`list id "${spec.id}" is not kebab-case: it becomes a workspace kind`);
4
+ const kind = `${entity.kind}-${spec.id}`;
5
+ return {
6
+ ...spec,
7
+ entity,
8
+ key: `${entity.domain}:${kind}`,
9
+ ref: () => ({ domain: entity.domain, kind }),
10
+ };
11
+ }
12
+ /** Whether what `useListing` was handed is a list definition rather than a bare entity. */
13
+ export function isList(given) {
14
+ return "entity" in given && "title" in given;
15
+ }
16
+ /** The criteria a definition always asks: its scope, in its order. */
17
+ export function scopeOf(list) {
18
+ return {
19
+ ...list.scope,
20
+ ...(list.order === undefined ? {} : { order: [list.order] }),
21
+ };
22
+ }