@sincpro/web-framework 0.4.1 → 1.0.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 (45) hide show
  1. package/README.md +48 -44
  2. package/dist/core/discovery.d.ts +47 -0
  3. package/dist/core/discovery.js +68 -0
  4. package/dist/core/edit.d.ts +35 -6
  5. package/dist/core/edit.js +57 -4
  6. package/dist/core/entity.d.ts +18 -3
  7. package/dist/core/entity.js +27 -1
  8. package/dist/core/ids.d.ts +17 -0
  9. package/dist/core/ids.js +52 -0
  10. package/dist/core/index.d.ts +3 -2
  11. package/dist/core/index.js +3 -2
  12. package/dist/core/meta.d.ts +7 -0
  13. package/dist/core/meta.js +1 -1
  14. package/dist/core/metas.d.ts +4 -5
  15. package/dist/core/rest.d.ts +8 -0
  16. package/dist/core/rest.js +62 -3
  17. package/dist/core/schema.d.ts +5 -12
  18. package/dist/core/trail.js +1 -4
  19. package/dist/react/index.d.ts +1 -0
  20. package/dist/react/index.js +1 -0
  21. package/dist/react/scope.d.ts +23 -0
  22. package/dist/react/scope.js +12 -0
  23. package/dist/react/useGroups.js +1 -2
  24. package/dist/react/useHistory.js +1 -1
  25. package/dist/react/useListing.js +14 -9
  26. package/dist/react/useLookup.js +2 -3
  27. package/dist/react/usePivot.js +0 -1
  28. package/dist/react/useRecord.d.ts +9 -2
  29. package/dist/react/useRecord.js +53 -12
  30. package/dist/react/useRelated.js +2 -2
  31. package/dist/web/list/EntitySearchBar.js +2 -2
  32. package/dist/web/list/search.js +1 -1
  33. package/dist/web/record/EntityPicker.d.ts +14 -7
  34. package/dist/web/record/EntityPicker.js +21 -6
  35. package/dist/web/record/EntityTags.d.ts +5 -3
  36. package/dist/web/record/EntityTags.js +29 -6
  37. package/dist/web/record/control.d.ts +4 -4
  38. package/dist/web/record/control.js +7 -17
  39. package/dist/web/record/lines.js +28 -11
  40. package/dist/web/record/opening.d.ts +17 -3
  41. package/dist/web/record/opening.js +12 -0
  42. package/dist/web/workspace/composer.js +9 -7
  43. package/dist/web/workspace/workspace.d.ts +6 -2
  44. package/dist/web/workspace/workspace.js +6 -2
  45. package/package.json +7 -7
@@ -9,6 +9,11 @@ import { type Transport } from "./transport.js";
9
9
  * one record (`one()`), a write (`send()`, with its `Idempotency-Key`), and its refusals as a
10
10
  * `TransportError`, the one error every screen explains.
11
11
  *
12
+ * The definition of each model — what a list, a form and a select are built from — is read
13
+ * from the bounded context's discovery document (`document`, `/openapi.json` by default), once,
14
+ * and read again only when an answer says another version of its model (`model_version`); the
15
+ * document is revalidated with its `ETag`, so an unchanged one costs a `304`.
16
+ *
12
17
  * const transport = restTransport({
13
18
  * base: "/v1",
14
19
  * headers: () => ({ Authorization: `Bearer ${session.secret}` }),
@@ -21,6 +26,9 @@ export type RestOptions = {
21
26
  headers?: Record<string, string> | (() => Record<string, string>);
22
27
  /** Defaults to the global `fetch`. Inject one for tests. */
23
28
  fetch?: typeof fetch;
29
+ /** Where the bounded context's discovery document is: `"/openapi.json"` by default, at the
30
+ * origin of `base`. `null`: none is read, and the definitions come only from `metas`. */
31
+ document?: string | null;
24
32
  };
25
33
  export declare function urlOf<T>(base: string, route: string, criteria?: Criteria<T>): string;
26
34
  export declare function restTransport(options?: RestOptions): Transport;
package/dist/core/rest.js CHANGED
@@ -1,8 +1,9 @@
1
1
  import { readProblem } from "@sincpro/criteria";
2
2
  import { RestError, restSource } from "@sincpro/criteria/rest";
3
+ import { definitionOf, modelAt, } from "./discovery.js";
3
4
  import { TransportError, } from "./transport.js";
4
5
  /** The keys of an answer that are not the record: what is left is the record's own field. */
5
- const ENVELOPE = new Set(["cursor", "count", "entity_meta_data", "dropped", "draft"]);
6
+ const ENVELOPE = new Set(["cursor", "count", "model_version", "dropped", "draft", "missing"]);
6
7
  export function urlOf(base, route, criteria) {
7
8
  const url = `${base}${route}`;
8
9
  if (criteria === undefined)
@@ -10,10 +11,64 @@ export function urlOf(base, route, criteria) {
10
11
  const joiner = url.includes("?") ? "&" : "?";
11
12
  return `${url}${joiner}criteria=${encodeURIComponent(JSON.stringify(criteria))}`;
12
13
  }
14
+ /** The path a route is asked at, without its query: what a document path is matched with. */
15
+ function pathOf(url) {
16
+ const path = url.split("?")[0] ?? url;
17
+ return /^https?:\/\//.test(path) ? new URL(path).pathname : path;
18
+ }
19
+ /** Where the document is: `document` as given when absolute, else at the origin of `base`. */
20
+ function documentUrl(base, document) {
21
+ if (/^https?:\/\//.test(document) || !/^https?:\/\//.test(base))
22
+ return document;
23
+ return new URL(document, base).toString();
24
+ }
13
25
  export function restTransport(options = {}) {
14
26
  const base = options.base ?? "";
15
27
  const doFetch = options.fetch ?? ((input, init) => fetch(input, init));
16
28
  const own = () => typeof options.headers === "function" ? options.headers() : (options.headers ?? {});
29
+ // The discovery document, read once; asked again — with its ETag — when an answer says a
30
+ // version of its model the document did not.
31
+ const located = options.document === null ? null : (options.document ?? "/openapi.json");
32
+ let held;
33
+ let tag = null;
34
+ function documentRead(fresh) {
35
+ if (located === null)
36
+ return Promise.resolve(null);
37
+ if (held !== undefined && !fresh)
38
+ return held;
39
+ const before = held;
40
+ held = (async () => {
41
+ try {
42
+ const response = await doFetch(documentUrl(base, located), {
43
+ headers: { ...own(), ...(tag === null ? {} : { "If-None-Match": tag }) },
44
+ });
45
+ if (response.status === 304 && before !== undefined)
46
+ return await before;
47
+ if (!response.ok)
48
+ return null;
49
+ tag = response.headers.get("etag");
50
+ return (await response.json());
51
+ }
52
+ catch {
53
+ return null;
54
+ }
55
+ })();
56
+ return held;
57
+ }
58
+ /** The definition of the model `url` answers; read again when `version` is not the one held. */
59
+ async function definitionAt(url, method, version) {
60
+ const published = await documentRead(false);
61
+ if (published === null)
62
+ return null;
63
+ const name = modelAt(published, pathOf(url), method);
64
+ if (name === undefined)
65
+ return null;
66
+ const known = definitionOf(published, name);
67
+ if (known === undefined || !version || known.version === version)
68
+ return known?.meta ?? null;
69
+ const again = await documentRead(true);
70
+ return (again === null ? undefined : definitionOf(again, name))?.meta ?? known.meta;
71
+ }
17
72
  async function get(route, url, signal, write) {
18
73
  const headers = write
19
74
  ? {
@@ -36,7 +91,11 @@ export function restTransport(options = {}) {
36
91
  async list(route, criteria, signal) {
37
92
  const source = restSource(`${base}${route}`, { headers: own, fetch: doFetch });
38
93
  try {
39
- return await source.read(criteria, signal);
94
+ const page = await source.read(criteria, signal);
95
+ return {
96
+ ...page,
97
+ meta: page.meta ?? (await definitionAt(`${base}${route}`, "get", page.version)),
98
+ };
40
99
  }
41
100
  catch (error) {
42
101
  if (error instanceof RestError)
@@ -52,7 +111,7 @@ export function restTransport(options = {}) {
52
111
  throw new TransportError(route, 200, null, `${route} answered ${own.length} fields of its own (${own.join(", ")}); a record answers one`);
53
112
  return {
54
113
  record: answer[key],
55
- meta: answer["entity_meta_data"] ?? null,
114
+ meta: await definitionAt(urlOf(base, route), "get", answer["model_version"]),
56
115
  dropped: answer["dropped"] ?? [],
57
116
  draft: answer["draft"] ?? null,
58
117
  };
@@ -2,19 +2,12 @@ import type { Meta } from "@sincpro/criteria";
2
2
  /**
3
3
  * A model definition read from a JSON Schema — what an OpenAPI document holds.
4
4
  *
5
- * Context: what sincpro_framework's OpenAPI 3.1 describes and what it does not, checked
6
- * against a running forge:
5
+ * Context: a model a READ answers is published by sincpro_framework as its contract — JSON
6
+ * Schema with `x-sincpro` — and read by the transport (`metaFromContract`, `core/discovery`).
7
+ * What has no `x-sincpro` is a plain JSON Schema: a COMMAND's body, a value object it carries.
7
8
  *
8
- * - the records a READ answers are invisible: the framework serialises them with its own
9
- * envelope, so `GET /projects` and `GET /projects/{id}` answer schema `{}` and no
10
- * `Project` schema exists. A list's definition comes from `entity_meta_data`, at runtime
11
- * or preloaded (`FrameworkProvider metas`) — not from here;
12
- * - the COMMANDS and the value objects are described well, and better than the meta in one
13
- * place: inside a value object `entity_meta_data` sends a `Literal` and a `list[str]` as
14
- * `unknown`, where the schema says `enum: ["es", "en"]` and `array<string>`.
15
- *
16
- * So this reads a component schema into a `Meta` — the form of a Command, a value object — and
17
- * `completeMeta` fills, from it, what the server's meta left `unknown`.
9
+ * So this reads such a component schema into a `Meta` — the form of a Command, a value object —
10
+ * and `completeMeta` fills, from it, what a definition left `unknown`.
18
11
  *
19
12
  * const spec = metaFromSchema("ProjectSpecification", doc.components.schemas);
20
13
  * const fixed = completeMeta(project.fields.specification.definition, spec);
@@ -12,10 +12,7 @@ async function page(transport, trail, cursor) {
12
12
  ...trail.question,
13
13
  pagination: { ...trail.question.pagination, limit: trail.size },
14
14
  };
15
- const answer = await transport.list(trail.route, {
16
- ...resumingFrom(sized, cursor),
17
- meta: false,
18
- });
15
+ const answer = await transport.list(trail.route, resumingFrom(sized, cursor));
19
16
  return {
20
17
  ids: answer.rows.map((row) => String(row[trail.key] ?? "")),
21
18
  after: answer.cursor,
@@ -4,6 +4,7 @@
4
4
  * keeps it that way.
5
5
  */
6
6
  export { FrameworkProvider, useEntityFor, useFramework, } from "./context.js";
7
+ export { type ListScope, ListScopeProvider, useListScope, } from "./scope.js";
7
8
  export { type CommandState, type Rehearsal, useCommand, } from "./useCommand.js";
8
9
  export { type Groups, useGroups } from "./useGroups.js";
9
10
  export { useHistory } from "./useHistory.js";
@@ -4,6 +4,7 @@
4
4
  * keeps it that way.
5
5
  */
6
6
  export { FrameworkProvider, useEntityFor, useFramework, } from "./context.js";
7
+ export { ListScopeProvider, useListScope, } from "./scope.js";
7
8
  export { useCommand, } from "./useCommand.js";
8
9
  export { useGroups } from "./useGroups.js";
9
10
  export { useHistory } from "./useHistory.js";
@@ -0,0 +1,23 @@
1
+ import type { Expression } from "@sincpro/criteria";
2
+ import { type ReactNode } from "react";
3
+ /**
4
+ * A cut that every list of ONE entity reads under, given by whoever holds the screen.
5
+ *
6
+ * Context: a chooser opened by a picker (`chooserRef(query, scope)`) is the entity's own list
7
+ * view — the application's or the default — and that view builds its listing itself
8
+ * (`useListing(entity)`): nothing between the reference and the listing could narrow it, so
9
+ * the chooser offered records the picker excluded. The view that holds the list says the cut
10
+ * (`entityView`, from the reference) and `useListing` ANDs it under the list's own scope for
11
+ * that entity only — a list of another entity inside the same view is not touched. Like any
12
+ * scope it narrows what is offered; the server still decides what may be stored.
13
+ */
14
+ export type ListScope = {
15
+ key: string;
16
+ where: Expression;
17
+ };
18
+ export declare function ListScopeProvider({ value, children, }: {
19
+ value: ListScope;
20
+ children: ReactNode;
21
+ }): import("react").JSX.Element;
22
+ /** The cut the screen gave for the lists of `key`, or none. */
23
+ export declare function useListScope(key: string): Expression | undefined;
@@ -0,0 +1,12 @@
1
+ "use client";
2
+ import { jsx as _jsx } from "react/jsx-runtime";
3
+ import { createContext, useContext } from "react";
4
+ const Scope = createContext(null);
5
+ export function ListScopeProvider({ value, children, }) {
6
+ return _jsx(Scope.Provider, { value: value, children: children });
7
+ }
8
+ /** The cut the screen gave for the lists of `key`, or none. */
9
+ export function useListScope(key) {
10
+ const scope = useContext(Scope);
11
+ return scope !== null && scope.key === key ? scope.where : undefined;
12
+ }
@@ -38,7 +38,6 @@ export function useGroups(listing, options = {}) {
38
38
  return () => aborter.abort();
39
39
  const criteria = {
40
40
  ...JSON.parse(question),
41
- meta: false,
42
41
  grouping: {
43
42
  group_by: levels.map((level) => ({ ...level })),
44
43
  ...(sums === "" ? {} : { measures: measuresOf(sums.split(",")) }),
@@ -63,7 +62,7 @@ export function useGroups(listing, options = {}) {
63
62
  return;
64
63
  reading.current.add(key);
65
64
  const { grouping: _grouping, pagination: _pagination, ...own } = bucket.criteria;
66
- const first = { ...own, meta: false, pagination: { limit: pageSize } };
65
+ const first = { ...own, pagination: { limit: pageSize } };
67
66
  void transport.list(route, after === null ? first : resumingFrom(first, after)).then((page) => {
68
67
  reading.current.delete(key);
69
68
  setRows((now) => {
@@ -24,7 +24,7 @@ export function useHistory(entity, id, deps = []) {
24
24
  return;
25
25
  const aborter = new AbortController();
26
26
  const criteria = {
27
- where: {
27
+ selection: {
28
28
  all: [
29
29
  { field: "entity_type", operator: "=", value: history.type },
30
30
  { field: "entity_id", operator: "=", value: id },
@@ -4,6 +4,7 @@ import { useReading } from "@sincpro/criteria-react";
4
4
  import { listRoute } from "../core/entity.js";
5
5
  import { isList, scopeOf } from "../core/list.js";
6
6
  import { useFramework } from "./context.js";
7
+ import { useListScope } from "./scope.js";
7
8
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
8
9
  /** How long typing has to pause before the search goes out. */
9
10
  const TYPING_PAUSE = 200;
@@ -12,18 +13,22 @@ export function useListing(given, own = {}) {
12
13
  // A named list is its entity under a fixed scope: the scope ANDs under the caller's own.
13
14
  const definition = isList(given) ? given : undefined;
14
15
  const entity = definition?.entity ?? given;
15
- const options = definition === undefined
16
+ // The screen's cut for this entity (a chooser's, `ListScopeProvider`) ANDs like a scope.
17
+ const cut = useListScope(entity.key);
18
+ const scopes = [
19
+ ...(definition === undefined ? [] : [scopeOf(definition)]),
20
+ ...(cut === undefined ? [] : [{ selection: cut }]),
21
+ ];
22
+ const options = scopes.length === 0
16
23
  ? own
17
24
  : {
18
25
  ...own,
19
- criteria: own.criteria === undefined
20
- ? scopeOf(definition)
21
- : merge(scopeOf(definition), own.criteria),
26
+ criteria: [...scopes, ...(own.criteria === undefined ? [] : [own.criteria])].reduce((all, one) => merge(all, one)),
22
27
  };
23
28
  const route = listRoute(entity.list, options.params);
24
29
  const source = useMemo(() => resource((criteria, signal) => transport.list(route, criteria, signal)), [transport, route]);
25
- // Decided once, at mount: a definition already known means the server is not asked for it
26
- // again. Deciding it later would change the criteria and restart the reading.
30
+ // A definition already known draws the columns before the first page arrives; the one the
31
+ // transport reads from the discovery document comes with it.
27
32
  const [preloaded] = useState(() => metas.get(entity.key));
28
33
  const paging = options.paging ?? "pages";
29
34
  const size = options.pageSize ?? options.criteria?.pagination?.limit ?? 50;
@@ -32,7 +37,7 @@ export function useListing(given, own = {}) {
32
37
  ...options.criteria,
33
38
  pagination: { ...options.criteria?.pagination, limit: size },
34
39
  };
35
- const base = preloaded ? { ...asked, meta: false } : asked;
40
+ const base = asked;
36
41
  const reading = useReading(source, base);
37
42
  // `pages` mode: the cursor that opens each page walked so far — page 0 opens with none.
38
43
  const [cursors, setCursors] = useState([null]);
@@ -54,9 +59,9 @@ export function useListing(given, own = {}) {
54
59
  let criteria = base;
55
60
  const found = searchOver(meta, next.text);
56
61
  if (found !== undefined)
57
- criteria = merge(criteria, { where: found });
62
+ criteria = merge(criteria, { selection: found });
58
63
  if (next.where !== undefined)
59
- criteria = merge(criteria, { where: next.where });
64
+ criteria = merge(criteria, { selection: next.where });
60
65
  if (next.order.length > 0)
61
66
  criteria = merge(criteria, { order: [...next.order] });
62
67
  return criteria;
@@ -12,7 +12,7 @@ export function excluding(criteria, exclude, meta) {
12
12
  if (exclude === undefined || exclude.length === 0 || meta == null)
13
13
  return criteria;
14
14
  const out = {
15
- where: {
15
+ selection: {
16
16
  field: meta.get_id || meta.identity || "id",
17
17
  operator: "not in",
18
18
  value: [...exclude],
@@ -64,11 +64,10 @@ entity, options = {}) {
64
64
  const aborter = new AbortController();
65
65
  transport
66
66
  .list(route, {
67
- where: keys.length === 1
67
+ selection: keys.length === 1
68
68
  ? { field: key, operator: "=", value: keys[0] ?? "" }
69
69
  : { field: key, operator: "in", value: keys },
70
70
  pagination: { limit: keys.length },
71
- meta: false,
72
71
  }, aborter.signal)
73
72
  .then((page) => {
74
73
  for (const one of lookupOf(meta, page.rows, base.summary))
@@ -30,7 +30,6 @@ export function usePivot(listing, axes) {
30
30
  const [rows, columns] = JSON.parse(shape);
31
31
  const grouped = (levels) => ({
32
32
  ...JSON.parse(question),
33
- meta: false,
34
33
  grouping: {
35
34
  group_by: levels.map((level) => ({ ...level })),
36
35
  ...(sums === "" ? {} : { measures: measuresOf(sums.split(",")) }),
@@ -30,6 +30,12 @@ import { type Draft } from "../core/transport.js";
30
30
  * holds the answer and the screen decides where to go. Given the REFERENCE it was opened
31
31
  * with, a new record starts with what the reference carries over the defaults
32
32
  * (`newRef(values)`): an invoice created from its customer starts with that customer.
33
+ * - **creating by `Edit`** — sincpro_framework creates a new record under the id the CLIENT
34
+ * mints (a UUID v7), and its draft shares it from the first draft save. So a new record of
35
+ * an entity that declares `edit`, keyed by `id`, gets its key HERE (`newEntityId`), once:
36
+ * `keep()` stores its draft and `save()` stores it through the same `Edit` route, under
37
+ * that key — a retry names the same record, never a second one — and the hook becomes it.
38
+ * Its `id` stays `""` until it is stored: until then it does not exist.
33
39
  *
34
40
  * const invoice = useRecord(invoices, ""); // a new one
35
41
  * const invoice = useRecord(invoices, "F-2026-7"); // an existing one
@@ -59,7 +65,8 @@ export type Editing = {
59
65
  set: (name: string, value: unknown) => void;
60
66
  state: (name: string) => FieldState;
61
67
  /** A cell of a list of records — line `index` of `name`, its `field`: the line model's hints
62
- * over that line, refined by what the server's preview said of it (`items[index]`). */
68
+ * over that line, refined by what the server's preview said of it (`items`, by the line's
69
+ * identity, by its position when it has none). */
63
70
  cell: (name: string, index: number, field: string) => FieldState;
64
71
  /** The server's word on what did not validate, by where it points (`pathOf`): `discount`,
65
72
  * `lines/1/qty`. Read a field's — its lines' included — with `errorAt`. */
@@ -80,7 +87,7 @@ export type Editing = {
80
87
  save: () => Promise<boolean>;
81
88
  discard: () => void;
82
89
  /** Store the current edit as a draft — only when the entity declares where (`draft` or
83
- * `edit`), and the record exists: a draft is kept against a record. */
90
+ * `edit`), and the record exists or is born by `Edit` under the key minted for it. */
84
91
  keep?: () => Promise<void>;
85
92
  /** What the last create answered, when it did not say the new record's identity. */
86
93
  created: unknown;
@@ -1,6 +1,7 @@
1
1
  "use client";
2
- import { changesOf, creationOf, defaultsOf, errorsByField, fieldStateOf, lineStatesOf, missingOf, } from "../core/edit.js";
2
+ import { changesOf, computedLocally, creationOf, defaultsOf, errorsByField, fieldStateOf, lineStatesOf, missingOf, needsPreview, } from "../core/edit.js";
3
3
  import { pathFor, startingValuesOf, WITH_PARAM, } from "../core/entity.js";
4
+ import { newEntityId } from "../core/ids.js";
4
5
  import { linesAnswered } from "../core/lines.js";
5
6
  import { retryKeys } from "../core/retry.js";
6
7
  import { TransportError } from "../core/transport.js";
@@ -21,6 +22,9 @@ export function useRecord(entity, opened) {
21
22
  const isNew = id === "";
22
23
  const [created, setCreated] = useState(null);
23
24
  const creating = useRef(retryKeys());
25
+ // The key a new record is born under when it is created by `Edit`: minted once per new
26
+ // record, on the first gesture that needs it, and kept for every draft save and the save.
27
+ const minted = useRef(null);
24
28
  const [state, setState] = useState({
25
29
  status: "loading",
26
30
  record: null,
@@ -139,9 +143,34 @@ export function useRecord(entity, opened) {
139
143
  const values = useMemo(() => ({ ...record, ...computed, ...typed }), [record, computed, typed]);
140
144
  const changed = useMemo(() => changesOf(record, typed), [record, typed]);
141
145
  const version = record["version"];
146
+ // sincpro_framework's `Edit` names a record by `id`; a model keyed by another field (an
147
+ // invoice's number, the server's to give) is still created through `create`.
148
+ const byEdit = isNew &&
149
+ entity.edit !== undefined &&
150
+ (state.meta?.get_id || state.meta?.identity || "id") === "id";
151
+ /** The record's key for a write: its own, or the one minted for it while it is new. */
152
+ const keyNow = () => {
153
+ if (!byEdit)
154
+ return id;
155
+ if (minted.current?.from !== given)
156
+ minted.current = { from: given, key: newEntityId() };
157
+ return minted.current.key;
158
+ };
142
159
  const ask = (next, name) => {
143
160
  const preview = entity.preview;
144
- if (preview === undefined)
161
+ const field = name.split(".")[0] ?? name;
162
+ // What the server wrote down is computed here, as it would: a change whose every reach has
163
+ // a formula needs the server only for a rule that judges it.
164
+ const local = Array.isArray(next[field])
165
+ ? undefined
166
+ : computedLocally(state.meta, { ...record, ...next }, field);
167
+ if (local !== undefined)
168
+ setComputed((now) => ({ ...now, ...local }));
169
+ const judged = (state.meta?.fields[field]?.judged_by?.length ?? 0) > 0;
170
+ // A change that reaches nothing — no computation, no rule — has nothing to ask the server.
171
+ if (preview === undefined || !needsPreview(state.meta, field))
172
+ return;
173
+ if (local !== undefined && !judged)
145
174
  return;
146
175
  cancelPreview();
147
176
  pause.current = setTimeout(() => {
@@ -194,8 +223,10 @@ export function useRecord(entity, opened) {
194
223
  // draft version read (`0`: none) — another tab that kept first wins —, and the stored version
195
224
  // the edit started from. Without an `action` it is the server's default, `save_draft`.
196
225
  const editOf = (action) => ({
197
- id,
198
- values,
226
+ id: keyNow(),
227
+ // A new record carries what a person may write — never a field the framework writes (its
228
+ // id, its stamps), which `Edit` refuses.
229
+ values: isNew ? creationOf(state.meta, values) : values,
199
230
  changed: Object.keys(changed),
200
231
  version: draft?.version ?? 0,
201
232
  ...(typeof version === "number" ? { origin_version: version } : {}),
@@ -214,7 +245,7 @@ export function useRecord(entity, opened) {
214
245
  cell: (name, index, field) => {
215
246
  const line = (Array.isArray(values[name]) ? values[name] : [])[index];
216
247
  const definition = state.meta?.fields[name]?.definition;
217
- return fieldStateOf(definition, field, line ?? {}, lineStatesOf(fromServer, name)[index]);
248
+ return fieldStateOf(definition, field, line ?? {}, lineStatesOf(fromServer, name, line, index, definition?.identity || "id"));
218
249
  },
219
250
  errors: failure instanceof TransportError ? errorsByField(failure.problem?.errors) : {},
220
251
  advice,
@@ -227,7 +258,7 @@ export function useRecord(entity, opened) {
227
258
  restored: draft !== null && (draft.values === undefined || Object.keys(changed).length > 0),
228
259
  draft,
229
260
  save: async () => {
230
- if (isNew)
261
+ if (isNew && !byEdit)
231
262
  return create();
232
263
  const route = entity.edit ?? entity.save;
233
264
  if (route === undefined)
@@ -235,12 +266,21 @@ export function useRecord(entity, opened) {
235
266
  cancelPreview();
236
267
  setSaving(true);
237
268
  setFailure(null);
269
+ const key = keyNow();
238
270
  try {
239
- await transport.send(route.method, pathFor(route, id, values), entity.edit === undefined
271
+ await transport.send(route.method, pathFor(route, key, values), entity.edit === undefined
240
272
  ? { ...changed, ...(version === undefined ? {} : { version }) }
241
273
  : editOf("save"));
242
274
  setDraft(null);
243
- reload();
275
+ // Stored under the key it was born with: the hook becomes that record and reads it.
276
+ if (isNew) {
277
+ if (mounted.current) {
278
+ forget();
279
+ setBorn({ from: given, id: key });
280
+ }
281
+ }
282
+ else
283
+ reload();
244
284
  return true;
245
285
  }
246
286
  catch (error) {
@@ -259,23 +299,24 @@ export function useRecord(entity, opened) {
259
299
  forget();
260
300
  // The draft lives on the server: discarding only here would bring it back on the next read.
261
301
  const route = entity.edit;
262
- if (route === undefined || isNew || draft === null)
302
+ if (route === undefined || draft === null)
263
303
  return;
264
304
  setDraft(null);
265
305
  // Through the promise: a route key the record lacks is refused like any failure.
266
306
  Promise.resolve()
267
- .then(() => transport.send(route.method, pathFor(route, id, values), editOf("discard")))
307
+ .then(() => transport.send(route.method, pathFor(route, keyNow(), values), editOf("discard")))
268
308
  .then(() => mounted.current && reload())
269
309
  .catch((error) => mounted.current && refused(error));
270
310
  },
271
311
  created,
272
- ...((entity.edit ?? entity.draft) === undefined || isNew
312
+ // A draft is kept against a record: a stored one, or a new one born by `Edit` under its key.
313
+ ...((entity.edit ?? entity.draft) === undefined || (isNew && !byEdit)
273
314
  ? {}
274
315
  : {
275
316
  keep: async () => {
276
317
  const route = (entity.edit ?? entity.draft);
277
318
  try {
278
- const kept = await transport.send(route.method, pathFor(route, id, values), entity.edit === undefined ? editOf() : editOf("save_draft"));
319
+ const kept = await transport.send(route.method, pathFor(route, keyNow(), values), entity.edit === undefined ? editOf() : editOf("save_draft"));
279
320
  const now = kept.draft;
280
321
  if (now)
281
322
  setDraft({
@@ -21,9 +21,9 @@ export function useRelated(record, name, related, options = {}) {
21
21
  const value = record.record === null ? null : record.record[own];
22
22
  const scope = {
23
23
  ...options.criteria,
24
- where: {
24
+ selection: {
25
25
  all: [
26
- ...(options.criteria?.where ? [options.criteria.where] : []),
26
+ ...(options.criteria?.selection ? [options.criteria.selection] : []),
27
27
  { field: key, operator: "=", value: value },
28
28
  ],
29
29
  },
@@ -22,7 +22,7 @@ export function EntitySearchBar({ listing, filters = [], groups, seed, }) {
22
22
  if (seeded.current || seed === undefined || seed === "" || meta?.search == null)
23
23
  return;
24
24
  seeded.current = true;
25
- const where = matching(meta, seed).where;
25
+ const where = matching(meta, seed).selection;
26
26
  if (where === undefined)
27
27
  return;
28
28
  const chip = filterCriteria(where, fillCopy(ui.search.literalChip, { text: seed }));
@@ -63,7 +63,7 @@ export function EntitySearchBar({ listing, filters = [], groups, seed, }) {
63
63
  : { grouping: _jsx(GroupingLevels, { fields: groupable, control: control }) }), onOpenBuilder: () => setBuilding(true), ...(meta?.search == null
64
64
  ? {}
65
65
  : {
66
- literal: (text) => matching(meta, text).where ?? null,
66
+ literal: (text) => matching(meta, text).selection ?? null,
67
67
  }) }), building ? (_jsx(Dialog, { open: true, width: "lg", title: copy.builder, onClose: () => setBuilding(false), children: _jsx(CriteriaBuilder, { model: model, ...(whereOf(put) === undefined && listing.order.length === 0
68
68
  ? {}
69
69
  : {
@@ -54,7 +54,7 @@ function searchedFields(meta) {
54
54
  walk(value);
55
55
  }
56
56
  };
57
- walk(meta.search?.["where"]);
57
+ walk(meta.search?.["selection"]);
58
58
  return found;
59
59
  }
60
60
  /**
@@ -14,9 +14,13 @@ import { type OpenTarget } from "@sincpro/web-ui";
14
14
  * searched, ordered and paged by the server, where clicking a row answers the field. An entity
15
15
  * without a search template is filtered where it is.
16
16
  *
17
- * Inside a workspace, «open» and the chooser can be the composer's instead (`api.open`,
18
- * `api.pick`): pass `onOpen` / `onBrowseAll` and they replace the defaults — `chooserIn(api,
19
- * entity, onChange)` is that `onBrowseAll`.
17
+ * Inside a workspace, «open» and the chooser ARE the workspace's (`RecordOpening`, which
18
+ * `entityView` gives every view): the chosen record opens where the workspace puts it, and
19
+ * «Buscar más…» is the entity's own list opened to choose — carrying the picker's cut, so it
20
+ * offers only what the picker would. A picker written by hand used to open web-ui's `Dialog`
21
+ * there unless the screen remembered to pass `onBrowseAll`. The built-in chooser is for a
22
+ * picker outside any workspace, or where the workspace's must not be used (`ownChooser`).
23
+ * `onOpen` / `onBrowseAll` still replace either.
20
24
  *
21
25
  * `criteria` narrows what may be chosen — the contacts of the chosen customer — in the picker
22
26
  * and in its chooser alike; the server applies it, and a new one starts the choices over. A
@@ -38,7 +42,7 @@ import { type OpenTarget } from "@sincpro/web-ui";
38
42
  * <EntityPicker entity={activeCustomers} columns={["name", "tax_id", "city"]} … />
39
43
  * <EntityPicker entity={tenants} none="Sin tenant" exclude={sharedWith} … />
40
44
  */
41
- export declare function EntityPicker<T extends AnyRecord>({ entity, value, onChange, onOpen, openTargets, onBrowseAll, criteria, columns, browse, none, exclude, placeholder, disabled, "aria-label": ariaLabel, }: {
45
+ export declare function EntityPicker<T extends AnyRecord>({ entity, value, onChange, onOpen, openTargets, onBrowseAll, ownChooser, criteria, columns, browse, none, exclude, placeholder, disabled, "aria-label": ariaLabel, }: {
42
46
  /** What is chosen from: an entity, or a named list of it (its cut, columns and title). */
43
47
  entity: Entity<T> | ListDefinition<T>;
44
48
  /** The chooser's columns. Without it, the named list's, or every scalar field. */
@@ -59,11 +63,14 @@ export declare function EntityPicker<T extends AnyRecord>({ entity, value, onCha
59
63
  /** Open the chosen record where the person asked — in composer,
60
64
  * `(id, to) => openIn(api, entity.ref(id), to)`. */
61
65
  onOpen?: (id: string, to: OpenTarget) => void;
62
- /** Where it may open, the default first (a modal; from inside a modal, beside). */
66
+ /** Where it may open, the default first. Inside a workspace, the workspace's. */
63
67
  openTargets?: readonly OpenTarget[];
64
- /** Replace the built-in chooser — in composer, `api.pick(entity.chooserRef(), …)`. It gets
65
- * what was typed, so the list opens on the same search. */
68
+ /** Replace the chooser — the workspace's, or the built-in one. It gets what was typed, so
69
+ * the list opens on the same search. */
66
70
  onBrowseAll?: (query: string) => void;
71
+ /** The built-in chooser even inside a workspace: where an answer arriving later would land
72
+ * somewhere else — a line that committed when the focus left it. */
73
+ ownChooser?: boolean;
67
74
  placeholder?: string;
68
75
  disabled?: boolean;
69
76
  "aria-label"?: string;