@sincpro/web-framework 0.4.0 → 0.4.2

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 +42 -44
  2. package/dist/core/cache.d.ts +10 -2
  3. package/dist/core/cache.js +31 -9
  4. package/dist/core/copy.d.ts +4 -0
  5. package/dist/core/copy.js +4 -0
  6. package/dist/core/edit.d.ts +5 -0
  7. package/dist/core/edit.js +6 -2
  8. package/dist/core/entity.d.ts +39 -5
  9. package/dist/core/entity.js +57 -4
  10. package/dist/core/history.js +5 -1
  11. package/dist/core/ids.d.ts +17 -0
  12. package/dist/core/ids.js +52 -0
  13. package/dist/core/index.d.ts +2 -1
  14. package/dist/core/index.js +2 -1
  15. package/dist/react/index.d.ts +2 -1
  16. package/dist/react/index.js +2 -1
  17. package/dist/react/scope.d.ts +23 -0
  18. package/dist/react/scope.js +12 -0
  19. package/dist/react/useCommand.js +1 -1
  20. package/dist/react/useListing.d.ts +1 -1
  21. package/dist/react/useListing.js +11 -11
  22. package/dist/react/useLookup.d.ts +10 -1
  23. package/dist/react/useLookup.js +29 -3
  24. package/dist/react/useRecord.d.ts +13 -2
  25. package/dist/react/useRecord.js +73 -22
  26. package/dist/web/list/rowCommands.js +2 -1
  27. package/dist/web/record/CommandButton.d.ts +3 -1
  28. package/dist/web/record/CommandButton.js +2 -2
  29. package/dist/web/record/EntityPicker.d.ts +28 -9
  30. package/dist/web/record/EntityPicker.js +54 -18
  31. package/dist/web/record/EntityTags.d.ts +5 -3
  32. package/dist/web/record/EntityTags.js +29 -6
  33. package/dist/web/record/control.d.ts +4 -4
  34. package/dist/web/record/control.js +7 -17
  35. package/dist/web/record/lines.js +12 -2
  36. package/dist/web/record/opening.d.ts +17 -3
  37. package/dist/web/record/opening.js +12 -0
  38. package/dist/web/workspace/SincproApp.d.ts +15 -4
  39. package/dist/web/workspace/SincproApp.js +18 -7
  40. package/dist/web/workspace/composer.d.ts +20 -1
  41. package/dist/web/workspace/composer.js +28 -10
  42. package/dist/web/workspace/record.js +12 -2
  43. package/dist/web/workspace/workspace.d.ts +6 -2
  44. package/dist/web/workspace/workspace.js +6 -2
  45. package/package.json +3 -3
@@ -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
+ }
@@ -26,7 +26,7 @@ export function useCommand(entity, name) {
26
26
  setError(null);
27
27
  const idempotencyKey = gesture.keyFor({ id, body });
28
28
  try {
29
- const answer = await transport.send(route.method, pathFor(route, id), body, undefined, { idempotencyKey });
29
+ const answer = await transport.send(route.method, pathFor(route, id, body), body, undefined, { idempotencyKey });
30
30
  gesture.settle(null);
31
31
  return answer;
32
32
  }
@@ -1,5 +1,5 @@
1
1
  import { type AnyRecord, type Count, type Criteria, type Dropped, type Expression, type Meta, type ReadingStatus, type Sort } from "@sincpro/criteria";
2
- import type { Entity } from "../core/entity.js";
2
+ import { type Entity } from "../core/entity.js";
3
3
  import { type ListDefinition } from "../core/list.js";
4
4
  /**
5
5
  * N records of an entity, live: what a list draws and the gestures that drive it.
@@ -1,31 +1,31 @@
1
1
  "use client";
2
2
  import { merge, resource, resumingFrom, searchOver, } from "@sincpro/criteria";
3
3
  import { useReading } from "@sincpro/criteria-react";
4
+ import { listRoute } from "../core/entity.js";
4
5
  import { isList, scopeOf } from "../core/list.js";
5
6
  import { useFramework } from "./context.js";
7
+ import { useListScope } from "./scope.js";
6
8
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
7
9
  /** How long typing has to pause before the search goes out. */
8
10
  const TYPING_PAUSE = 200;
9
- function routeOf(list, params) {
10
- const query = new URLSearchParams(Object.entries(params ?? {}).filter(([, value]) => value !== "")).toString();
11
- if (query === "")
12
- return list;
13
- return `${list}${list.includes("?") ? "&" : "?"}${query}`;
14
- }
15
11
  export function useListing(given, own = {}) {
16
12
  const { transport, locale, metas } = useFramework();
17
13
  // A named list is its entity under a fixed scope: the scope ANDs under the caller's own.
18
14
  const definition = isList(given) ? given : undefined;
19
15
  const entity = definition?.entity ?? given;
20
- 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 ? [] : [{ where: cut }]),
21
+ ];
22
+ const options = scopes.length === 0
21
23
  ? own
22
24
  : {
23
25
  ...own,
24
- criteria: own.criteria === undefined
25
- ? scopeOf(definition)
26
- : merge(scopeOf(definition), own.criteria),
26
+ criteria: [...scopes, ...(own.criteria === undefined ? [] : [own.criteria])].reduce((all, one) => merge(all, one)),
27
27
  };
28
- const route = routeOf(entity.list, options.params);
28
+ const route = listRoute(entity.list, options.params);
29
29
  const source = useMemo(() => resource((criteria, signal) => transport.list(route, criteria, signal)), [transport, route]);
30
30
  // Decided once, at mount: a definition already known means the server is not asked for it
31
31
  // again. Deciding it later would change the criteria and restart the reading.
@@ -1,4 +1,4 @@
1
- import type { AnyRecord, Criteria } from "@sincpro/criteria";
1
+ import { type AnyRecord, type Criteria, type Meta } from "@sincpro/criteria";
2
2
  import type { Entity } from "../core/entity.js";
3
3
  import { type ListDefinition } from "../core/list.js";
4
4
  import { type LookupOption } from "../core/lookup.js";
@@ -14,6 +14,11 @@ import { type LookupOption } from "../core/lookup.js";
14
14
  * The chosen record usually is NOT on the page on screen — a search narrowed it, or it lies
15
15
  * past the first ten — so its name is kept: from the options it was seen among, or asked of
16
16
  * the server once by its key (`chosen`).
17
+ *
18
+ * `exclude` leaves keys out of the choices — the tenants a project is already shared with — and
19
+ * the SERVER leaves them out (`not in` under `criteria`), so the ten are ten that may be chosen.
20
+ * It needs the entity's key field: until its definition is known the first ten come
21
+ * unexcluded, and the reading starts over when it arrives.
17
22
  */
18
23
  export type Lookup = {
19
24
  options: LookupOption[];
@@ -31,6 +36,8 @@ export type Lookup = {
31
36
  * not known yet are asked of the server in one question. */
32
37
  chosenAll: LookupOption[];
33
38
  };
39
+ /** What may be chosen: the screen's own cut, without the keys it excludes. */
40
+ export declare function excluding<T extends AnyRecord>(criteria: Criteria<T> | undefined, exclude: readonly string[] | undefined, meta: Meta | null | undefined): Criteria<T> | undefined;
34
41
  export declare function useLookup<T extends AnyRecord>(
35
42
  /** The entity, or a named list of it: «active customers» chooses only those. */
36
43
  entity: Entity<T> | ListDefinition<T>, options?: {
@@ -44,4 +51,6 @@ entity: Entity<T> | ListDefinition<T>, options?: {
44
51
  value?: string;
45
52
  /** The keys chosen in a many2many, to keep their names (`chosenAll`). */
46
53
  values?: readonly string[];
54
+ /** Keys never offered — those already chosen elsewhere. Left out by the server. */
55
+ exclude?: readonly string[];
47
56
  }): Lookup;
@@ -1,4 +1,5 @@
1
1
  "use client";
2
+ import { merge } from "@sincpro/criteria";
2
3
  import { isList } from "../core/list.js";
3
4
  import { lookupOf } from "../core/lookup.js";
4
5
  import { useFramework } from "./context.js";
@@ -6,17 +7,42 @@ import { useListing } from "./useListing.js";
6
7
  import { useEffect, useRef, useState } from "react";
7
8
  /** Ten: what a dropdown shows without scrolling, and what Odoo's many2one asks for. */
8
9
  const FIRST = 10;
10
+ /** What may be chosen: the screen's own cut, without the keys it excludes. */
11
+ export function excluding(criteria, exclude, meta) {
12
+ if (exclude === undefined || exclude.length === 0 || meta == null)
13
+ return criteria;
14
+ const out = {
15
+ where: {
16
+ field: meta.get_id || meta.identity || "id",
17
+ operator: "not in",
18
+ value: [...exclude],
19
+ },
20
+ };
21
+ return criteria === undefined ? out : merge(criteria, out);
22
+ }
9
23
  export function useLookup(
10
24
  /** The entity, or a named list of it: «active customers» chooses only those. */
11
25
  entity, options = {}) {
12
- const { transport } = useFramework();
26
+ const { transport, metas } = useFramework();
27
+ const base = isList(entity) ? entity.entity : entity;
28
+ // The key field to exclude by comes with the definition: known already, or with the first
29
+ // answer — then this renders again and the reading starts over without the excluded.
30
+ const [definition, setDefinition] = useState(() => ({
31
+ key: base.key,
32
+ meta: metas.get(base.key),
33
+ }));
34
+ const keyed = definition.key === base.key ? definition.meta : metas.get(base.key);
35
+ const scope = excluding(options.criteria, options.exclude, keyed);
13
36
  // «More», not pages: a choice list grows downwards, and its ceiling keeps it light.
14
37
  const listing = useListing(entity, {
15
38
  paging: "more",
16
39
  pageSize: options.pageSize ?? FIRST,
17
- ...(options.criteria === undefined ? {} : { criteria: options.criteria }),
40
+ ...(scope === undefined ? {} : { criteria: scope }),
18
41
  });
19
- const base = isList(entity) ? entity.entity : entity;
42
+ useEffect(() => {
43
+ if (keyed === undefined && listing.meta !== null)
44
+ setDefinition({ key: base.key, meta: listing.meta });
45
+ }, [keyed, listing.meta, base.key]);
20
46
  const choices = lookupOf(listing.meta, listing.rows, base.summary);
21
47
  // Every choice seen is remembered: the chosen are named even after the page moved on.
22
48
  const seen = useRef(new Map());
@@ -18,6 +18,11 @@ import { type Draft } from "../core/transport.js";
18
18
  * in between, the server answers 409 and the screen says so instead of overwriting.
19
19
  * - **drafts** — an edit kept between requests (sincpro_framework's `Drafts`) comes back with
20
20
  * the record and is shown as restored; `keep()` stores the current one.
21
+ * - **`Edit`** — an entity that declares `edit` speaks sincpro_framework's `Edit` on it for all
22
+ * three: `keep()` is `save_draft`, `save()` is `save` — the record whole, the fields changed,
23
+ * the draft version read and the stored version it started from — and `discard()` is
24
+ * `discard`, which drops the draft on the server too. Without it, a save sends the changed
25
+ * fields and the version to `save`.
21
26
  * - **creating** — with no id it is a record that does not exist yet: it starts from the
22
27
  * defaults the model publishes, previews like any other, and `save()` sends it to the
23
28
  * entity's `create` route with an `Idempotency-Key` (a retry never creates two). When the
@@ -25,6 +30,12 @@ import { type Draft } from "../core/transport.js";
25
30
  * holds the answer and the screen decides where to go. Given the REFERENCE it was opened
26
31
  * with, a new record starts with what the reference carries over the defaults
27
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.
28
39
  *
29
40
  * const invoice = useRecord(invoices, ""); // a new one
30
41
  * const invoice = useRecord(invoices, "F-2026-7"); // an existing one
@@ -74,8 +85,8 @@ export type Editing = {
74
85
  draft: Draft | null;
75
86
  save: () => Promise<boolean>;
76
87
  discard: () => void;
77
- /** Store the current edit as a draft — only when the entity declares where, and the record
78
- * exists: a draft is kept against a record. */
88
+ /** Store the current edit as a draft — only when the entity declares where (`draft` or
89
+ * `edit`), and the record exists or is born by `Edit` under the key minted for it. */
79
90
  keep?: () => Promise<void>;
80
91
  /** What the last create answered, when it did not say the new record's identity. */
81
92
  created: unknown;
@@ -1,6 +1,7 @@
1
1
  "use client";
2
2
  import { changesOf, creationOf, defaultsOf, errorsByField, fieldStateOf, lineStatesOf, missingOf, } 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,16 +143,38 @@ 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
161
  if (preview === undefined)
145
162
  return;
146
163
  cancelPreview();
147
164
  pause.current = setTimeout(() => {
165
+ // A key of the route (`{tenant_id}`) is a field of the record on screen. One it lacks is
166
+ // a preview not asked — never an error thrown out of a timer.
167
+ let path;
168
+ try {
169
+ path = pathFor(preview, isNew ? undefined : id, { ...record, ...next });
170
+ }
171
+ catch {
172
+ return;
173
+ }
148
174
  const aborter = new AbortController();
149
175
  asking.current = aborter;
150
176
  transport
151
- .send(preview.method, pathFor(preview, isNew ? undefined : id), {
177
+ .send(preview.method, path, {
152
178
  id: isNew ? null : id,
153
179
  values: isNew ? { ...record, ...next } : changesOf(record, next),
154
180
  changed: [name],
@@ -181,6 +207,19 @@ export function useRecord(entity, opened) {
181
207
  else
182
208
  setFailure(error);
183
209
  };
210
+ // sincpro_framework's `Edit`: the record as the form holds it, whole; the fields changed; the
211
+ // draft version read (`0`: none) — another tab that kept first wins —, and the stored version
212
+ // the edit started from. Without an `action` it is the server's default, `save_draft`.
213
+ const editOf = (action) => ({
214
+ id: keyNow(),
215
+ // A new record carries what a person may write — never a field the framework writes (its
216
+ // id, its stamps), which `Edit` refuses.
217
+ values: isNew ? creationOf(state.meta, values) : values,
218
+ changed: Object.keys(changed),
219
+ version: draft?.version ?? 0,
220
+ ...(typeof version === "number" ? { origin_version: version } : {}),
221
+ ...(action === undefined ? {} : { action }),
222
+ });
184
223
  const edit = {
185
224
  values,
186
225
  changed,
@@ -207,21 +246,29 @@ export function useRecord(entity, opened) {
207
246
  restored: draft !== null && (draft.values === undefined || Object.keys(changed).length > 0),
208
247
  draft,
209
248
  save: async () => {
210
- if (isNew)
249
+ if (isNew && !byEdit)
211
250
  return create();
212
- const route = entity.save;
251
+ const route = entity.edit ?? entity.save;
213
252
  if (route === undefined)
214
253
  throw new Error(`${entity.key} declares no save route`);
215
254
  cancelPreview();
216
255
  setSaving(true);
217
256
  setFailure(null);
257
+ const key = keyNow();
218
258
  try {
219
- await transport.send(route.method, pathFor(route, id), {
220
- ...changed,
221
- ...(version === undefined ? {} : { version }),
222
- });
259
+ await transport.send(route.method, pathFor(route, key, values), entity.edit === undefined
260
+ ? { ...changed, ...(version === undefined ? {} : { version }) }
261
+ : editOf("save"));
223
262
  setDraft(null);
224
- reload();
263
+ // Stored under the key it was born with: the hook becomes that record and reads it.
264
+ if (isNew) {
265
+ if (mounted.current) {
266
+ forget();
267
+ setBorn({ from: given, id: key });
268
+ }
269
+ }
270
+ else
271
+ reload();
225
272
  return true;
226
273
  }
227
274
  catch (error) {
@@ -236,24 +283,28 @@ export function useRecord(entity, opened) {
236
283
  setSaving(false);
237
284
  }
238
285
  },
239
- discard: forget,
286
+ discard: () => {
287
+ forget();
288
+ // The draft lives on the server: discarding only here would bring it back on the next read.
289
+ const route = entity.edit;
290
+ if (route === undefined || draft === null)
291
+ return;
292
+ setDraft(null);
293
+ // Through the promise: a route key the record lacks is refused like any failure.
294
+ Promise.resolve()
295
+ .then(() => transport.send(route.method, pathFor(route, keyNow(), values), editOf("discard")))
296
+ .then(() => mounted.current && reload())
297
+ .catch((error) => mounted.current && refused(error));
298
+ },
240
299
  created,
241
- ...(entity.draft === undefined || isNew
300
+ // A draft is kept against a record: a stored one, or a new one born by `Edit` under its key.
301
+ ...((entity.edit ?? entity.draft) === undefined || (isNew && !byEdit)
242
302
  ? {}
243
303
  : {
244
304
  keep: async () => {
245
- const route = entity.draft;
246
- // sincpro_framework's `Edit`: the record as the form holds it, whole; the fields
247
- // changed; the draft version read (`0`: none) — another tab that kept first wins —,
248
- // and the stored version the edit started from.
305
+ const route = (entity.edit ?? entity.draft);
249
306
  try {
250
- const kept = await transport.send(route.method, pathFor(route, id), {
251
- id,
252
- values,
253
- changed: Object.keys(changed),
254
- version: draft?.version ?? 0,
255
- ...(typeof version === "number" ? { origin_version: version } : {}),
256
- });
307
+ const kept = await transport.send(route.method, pathFor(route, keyNow(), values), entity.edit === undefined ? editOf() : editOf("save_draft"));
257
308
  const now = kept.draft;
258
309
  if (now)
259
310
  setDraft({
@@ -281,7 +332,7 @@ export function useRecord(entity, opened) {
281
332
  const body = creationOf(state.meta, values);
282
333
  const idempotencyKey = creating.current.keyFor(body);
283
334
  try {
284
- const answer = await transport.send(route.method, pathFor(route), body, undefined, { idempotencyKey });
335
+ const answer = await transport.send(route.method, pathFor(route, undefined, body), body, undefined, { idempotencyKey });
285
336
  creating.current.settle(null);
286
337
  if (!mounted.current)
287
338
  return true;
@@ -24,7 +24,8 @@ export function useRowCommands(listing, commands) {
24
24
  setRunning((now) => new Set(now).add(gesture));
25
25
  setError(null);
26
26
  try {
27
- await transport.send(route.method, pathFor(route, id), body, undefined, {
27
+ // A key of the route beyond `{id}` (`{tenant_id}`) is the row's, unless the body says it.
28
+ await transport.send(route.method, pathFor(route, id, { ...row, ...body }), body, undefined, {
28
29
  idempotencyKey: retry.keyFor(body),
29
30
  });
30
31
  retry.settle(null);
@@ -9,7 +9,7 @@ import type { Entity } from "../../core/entity.js";
9
9
  * shows THAT in the window: the confirmation is the consequence, in the server's words, not a
10
10
  * question. A refusal is shown where it happened, with what to do.
11
11
  */
12
- export declare function CommandButton<T extends AnyRecord, R = unknown>({ entity, command, id, body, label, destructive, role, onDone, }: {
12
+ export declare function CommandButton<T extends AnyRecord, R = unknown>({ entity, command, id, body, label, destructive, role, disabled, onDone, }: {
13
13
  entity: Entity<T>;
14
14
  command: string;
15
15
  id?: string;
@@ -18,5 +18,7 @@ export declare function CommandButton<T extends AnyRecord, R = unknown>({ entity
18
18
  /** Asks the server what it would do before doing it. */
19
19
  destructive?: boolean;
20
20
  role?: "primary" | "secondary" | "ghost";
21
+ /** Not offered right now — «Mover» with no other tenant chosen. The server still decides. */
22
+ disabled?: boolean;
21
23
  onDone?: (answer: R) => void;
22
24
  }): import("react").JSX.Element;
@@ -14,7 +14,7 @@ import { useState } from "react";
14
14
  * shows THAT in the window: the confirmation is the consequence, in the server's words, not a
15
15
  * question. A refusal is shown where it happened, with what to do.
16
16
  */
17
- export function CommandButton({ entity, command, id, body, label, destructive = false, role = "secondary", onDone, }) {
17
+ export function CommandButton({ entity, command, id, body, label, destructive = false, role = "secondary", disabled = false, onDone, }) {
18
18
  const copy = frameworkCopy().command;
19
19
  const action = useCommand(entity, command);
20
20
  const [open, setOpen] = useState(false);
@@ -36,5 +36,5 @@ export function CommandButton({ entity, command, id, body, label, destructive =
36
36
  setOpen(false);
37
37
  action.reset();
38
38
  };
39
- return (_jsxs(_Fragment, { children: [_jsx(Button, { size: "sm", role: destructive ? "secondary" : role, disabled: action.busy, onClick: () => void (destructive ? ask() : run()), children: label }), open ? (_jsx(Dialog, { open: true, title: label, onClose: close, footer: destructive && action.error === null ? (_jsxs("div", { className: "flex justify-end gap-2", children: [_jsx(Button, { size: "sm", role: "secondary", onClick: close, children: copy.cancel }), _jsx(Button, { size: "sm", role: "primary", disabled: action.busy || action.rehearsal === null, onClick: () => void run(), children: copy.confirm })] })) : undefined, children: action.error !== null ? (_jsx(Refused, { error: action.error })) : action.rehearsal === null ? (_jsx("p", { className: "text-meta text-muted", children: copy.rehearsing })) : (_jsx("p", { className: "text-ink", children: action.rehearsal.text })) })) : null] }));
39
+ return (_jsxs(_Fragment, { children: [_jsx(Button, { size: "sm", role: destructive ? "secondary" : role, disabled: disabled || action.busy, onClick: () => void (destructive ? ask() : run()), children: label }), open ? (_jsx(Dialog, { open: true, title: label, onClose: close, footer: destructive && action.error === null ? (_jsxs("div", { className: "flex justify-end gap-2", children: [_jsx(Button, { size: "sm", role: "secondary", onClick: close, children: copy.cancel }), _jsx(Button, { size: "sm", role: "primary", disabled: action.busy || action.rehearsal === null, onClick: () => void run(), children: copy.confirm })] })) : undefined, children: action.error !== null ? (_jsx(Refused, { error: action.error })) : action.rehearsal === null ? (_jsx("p", { className: "text-meta text-muted", children: copy.rehearsing })) : (_jsx("p", { className: "text-ink", children: action.rehearsal.text })) })) : null] }));
40
40
  }
@@ -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
@@ -28,10 +32,17 @@ import { type OpenTarget } from "@sincpro/web-ui";
28
32
  * way to the server's literal search. The chooser is a table — the columns the list declares,
29
33
  * or `columns` — searched by the entity's literal search on the server.
30
34
  *
35
+ * A field that may stay empty offers that as a choice (`none`): «Ninguno», or the screen's own
36
+ * word («Sin tenant»), answered as `""`. web-ui's `Picker` has no way to clear a choice, so it
37
+ * is the first option, while nothing is typed. `exclude` leaves keys out of the choices — the
38
+ * tenants a project is already shared with —, in the picker and its chooser, and the SERVER
39
+ * leaves them out (`useLookup exclude`).
40
+ *
31
41
  * <EntityPicker entity={customers} value={id} onChange={set} />
32
42
  * <EntityPicker entity={activeCustomers} columns={["name", "tax_id", "city"]} … />
43
+ * <EntityPicker entity={tenants} none="Sin tenant" exclude={sharedWith} … />
33
44
  */
34
- export declare function EntityPicker<T extends AnyRecord>({ entity, value, onChange, onOpen, openTargets, onBrowseAll, criteria, columns, browse, 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, }: {
35
46
  /** What is chosen from: an entity, or a named list of it (its cut, columns and title). */
36
47
  entity: Entity<T> | ListDefinition<T>;
37
48
  /** The chooser's columns. Without it, the named list's, or every scalar field. */
@@ -40,18 +51,26 @@ export declare function EntityPicker<T extends AnyRecord>({ entity, value, onCha
40
51
  browse?: boolean;
41
52
  /** Which records may be chosen at all: applied by the server under what is typed. */
42
53
  criteria?: Criteria<T>;
54
+ /** The field may stay empty: a first choice that answers `""` — `true` says «Ninguno», a
55
+ * text is the screen's own word for it. */
56
+ none?: boolean | string;
57
+ /** Keys never offered — those already chosen elsewhere. Left out by the server. */
58
+ exclude?: readonly string[];
43
59
  value?: string;
44
- /** The key chosen, and its record when the choice brought it — what a line keeps beside the
45
- * key so its cell names the choice without asking again. */
60
+ /** The key chosen (`""` for `none`), and its record when the choice brought it — what a line
61
+ * keeps beside the key so its cell names the choice without asking again. */
46
62
  onChange: (id: string, chosen?: T) => void;
47
63
  /** Open the chosen record where the person asked — in composer,
48
64
  * `(id, to) => openIn(api, entity.ref(id), to)`. */
49
65
  onOpen?: (id: string, to: OpenTarget) => void;
50
- /** 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. */
51
67
  openTargets?: readonly OpenTarget[];
52
- /** Replace the built-in chooser — in composer, `api.pick(entity.chooserRef(), …)`. It gets
53
- * 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. */
54
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;
55
74
  placeholder?: string;
56
75
  disabled?: boolean;
57
76
  "aria-label"?: string;
@@ -3,10 +3,12 @@ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-run
3
3
  import { nameOf } from "@sincpro/criteria";
4
4
  import { frameworkCopy } from "../../core/copy.js";
5
5
  import { isList } from "../../core/list.js";
6
+ import { useFramework } from "../../react/context.js";
6
7
  import { useListing } from "../../react/useListing.js";
7
- import { useLookup } from "../../react/useLookup.js";
8
+ import { excluding, useLookup } from "../../react/useLookup.js";
8
9
  import { EntityList } from "../list/EntityList.js";
9
10
  import { over, presentationOf } from "../list/presentation.js";
11
+ import { chooserScopeOf, useRecordOpening } from "./opening.js";
10
12
  import { Dialog, IconButton, Picker } from "@sincpro/web-ui";
11
13
  import { TextSearch } from "lucide-react";
12
14
  import { useState } from "react";
@@ -22,9 +24,13 @@ import { useState } from "react";
22
24
  * searched, ordered and paged by the server, where clicking a row answers the field. An entity
23
25
  * without a search template is filtered where it is.
24
26
  *
25
- * Inside a workspace, «open» and the chooser can be the composer's instead (`api.open`,
26
- * `api.pick`): pass `onOpen` / `onBrowseAll` and they replace the defaults — `chooserIn(api,
27
- * entity, onChange)` is that `onBrowseAll`.
27
+ * Inside a workspace, «open» and the chooser ARE the workspace's (`RecordOpening`, which
28
+ * `entityView` gives every view): the chosen record opens where the workspace puts it, and
29
+ * «Buscar más…» is the entity's own list opened to choose — carrying the picker's cut, so it
30
+ * offers only what the picker would. A picker written by hand used to open web-ui's `Dialog`
31
+ * there unless the screen remembered to pass `onBrowseAll`. The built-in chooser is for a
32
+ * picker outside any workspace, or where the workspace's must not be used (`ownChooser`).
33
+ * `onOpen` / `onBrowseAll` still replace either.
28
34
  *
29
35
  * `criteria` narrows what may be chosen — the contacts of the chosen customer — in the picker
30
36
  * and in its chooser alike; the server applies it, and a new one starts the choices over. A
@@ -36,27 +42,57 @@ import { useState } from "react";
36
42
  * way to the server's literal search. The chooser is a table — the columns the list declares,
37
43
  * or `columns` — searched by the entity's literal search on the server.
38
44
  *
45
+ * A field that may stay empty offers that as a choice (`none`): «Ninguno», or the screen's own
46
+ * word («Sin tenant»), answered as `""`. web-ui's `Picker` has no way to clear a choice, so it
47
+ * is the first option, while nothing is typed. `exclude` leaves keys out of the choices — the
48
+ * tenants a project is already shared with —, in the picker and its chooser, and the SERVER
49
+ * leaves them out (`useLookup exclude`).
50
+ *
39
51
  * <EntityPicker entity={customers} value={id} onChange={set} />
40
52
  * <EntityPicker entity={activeCustomers} columns={["name", "tax_id", "city"]} … />
53
+ * <EntityPicker entity={tenants} none="Sin tenant" exclude={sharedWith} … />
41
54
  */
42
- export function EntityPicker({ entity, value, onChange, onOpen, openTargets, onBrowseAll, criteria, columns, browse = true, placeholder, disabled, "aria-label": ariaLabel, }) {
55
+ export function EntityPicker({ entity, value, onChange, onOpen, openTargets, onBrowseAll, ownChooser = false, criteria, columns, browse = true, none, exclude, placeholder, disabled, "aria-label": ariaLabel, }) {
56
+ const base = isList(entity) ? entity.entity : entity;
57
+ const { metas } = useFramework();
58
+ const opening = useRecordOpening();
43
59
  const lookup = useLookup(entity, {
44
60
  ...(criteria === undefined ? {} : { criteria }),
45
61
  ...(value === undefined ? {} : { value }),
62
+ ...(exclude === undefined ? {} : { exclude }),
46
63
  });
47
- const person = (isList(entity) ? entity.entity : entity).summary.person === true;
64
+ // The chooser opens after the picker read the definition: it excludes from its first page.
65
+ const scope = excluding(criteria, exclude, metas.get(base.key));
66
+ const person = base.summary.person === true;
67
+ const nothing = none === undefined || none === false || lookup.text !== ""
68
+ ? []
69
+ : [{ id: "", name: none === true ? frameworkCopy().picker.none : none }];
48
70
  const look = presentationOf(entity).option;
49
71
  const [choosing, setChoosing] = useState(false);
50
- const browseAll = onBrowseAll ?? (() => setChoosing(true));
51
- const picker = (_jsx(Picker, { items: lookup.options.map((one) => over({
52
- id: one.id,
53
- name: one.label,
54
- ...(one.detail === undefined ? {} : { meta: one.detail, haystack: one.detail }),
55
- // A person or a company is chosen by their face: the photo, or their initials.
56
- ...(person ? { avatar: one.image ?? true } : {}),
57
- },
58
- // The entity's own look of a choice, over the default (`presented`).
59
- look === undefined || one.record === undefined ? undefined : look(one.record))), ...(value === undefined ? {} : { value }), ...(lookup.chosen === undefined
72
+ const opens = onOpen ??
73
+ (opening === null
74
+ ? undefined
75
+ : (id, to) => opening.open(base.ref(id), to));
76
+ const targets = openTargets ?? opening?.targets;
77
+ const choose = ownChooser ? undefined : opening?.choose;
78
+ const browseAll = onBrowseAll ??
79
+ (choose === undefined
80
+ ? () => setChoosing(true)
81
+ : (query) => choose(base, (id) => onChange(id), query, chooserScopeOf(entity, scope)));
82
+ const picker = (_jsx(Picker, { items: [
83
+ ...nothing,
84
+ ...lookup.options.map((one) => over({
85
+ id: one.id,
86
+ name: one.label,
87
+ ...(one.detail === undefined ? {} : { meta: one.detail, haystack: one.detail }),
88
+ // A person or a company is chosen by their face: the photo, or their initials.
89
+ ...(person ? { avatar: one.image ?? true } : {}),
90
+ },
91
+ // The entity's own look of a choice, over the default (`presented`).
92
+ look === undefined || one.record === undefined
93
+ ? undefined
94
+ : look(one.record))),
95
+ ], ...(value === undefined ? {} : { value }), ...(lookup.chosen === undefined
60
96
  ? {}
61
97
  : {
62
98
  valueLabel: (lookup.chosen.record === undefined || look === undefined
@@ -64,8 +100,8 @@ export function EntityPicker({ entity, value, onChange, onOpen, openTargets, onB
64
100
  : look(lookup.chosen.record).name) ?? lookup.chosen.label,
65
101
  }), onChange: (id) => onChange(id, lookup.options.find((one) => one.id === id)?.record), ...(lookup.searchable ? { onSearch: lookup.search } : {}),
66
102
  // «Loading» only before there is anything: refining keeps the ten on screen.
67
- loading: lookup.loading && lookup.options.length === 0, ...(onOpen === undefined ? {} : { onOpen }), ...(openTargets === undefined ? {} : { openTargets }), onBrowseAll: browseAll, ...(placeholder === undefined ? {} : { placeholder }), ...(disabled === undefined ? {} : { disabled }), ...(ariaLabel === undefined ? {} : { "aria-label": ariaLabel }) }));
68
- return (_jsxs(_Fragment, { children: [browse ? (_jsxs("span", { className: "flex min-w-0 items-start gap-1", children: [_jsx("span", { className: "min-w-0 flex-1", children: picker }), _jsx(IconButton, { icon: TextSearch, label: frameworkCopy().picker.browse, onClick: () => browseAll(lookup.text), ...(disabled === undefined ? {} : { disabled }) })] })) : (picker), choosing ? (_jsx(Chooser, { entity: entity, ...(columns === undefined ? {} : { columns }), ...(criteria === undefined ? {} : { criteria }), onChoose: (id, row) => {
103
+ loading: lookup.loading && lookup.options.length === 0, ...(opens === undefined || value === "" ? {} : { onOpen: opens }), ...(targets === undefined ? {} : { openTargets: targets }), onBrowseAll: browseAll, ...(placeholder === undefined ? {} : { placeholder }), ...(disabled === undefined ? {} : { disabled }), ...(ariaLabel === undefined ? {} : { "aria-label": ariaLabel }) }));
104
+ return (_jsxs(_Fragment, { children: [browse ? (_jsxs("span", { className: "flex min-w-0 items-start gap-1", children: [_jsx("span", { className: "min-w-0 flex-1", children: picker }), _jsx(IconButton, { icon: TextSearch, label: frameworkCopy().picker.browse, onClick: () => browseAll(lookup.text), ...(disabled === undefined ? {} : { disabled }) })] })) : (picker), choosing ? (_jsx(Chooser, { entity: entity, ...(columns === undefined ? {} : { columns }), ...(scope === undefined ? {} : { criteria: scope }), onChoose: (id, row) => {
69
105
  onChange(id, row);
70
106
  setChoosing(false);
71
107
  }, onClose: () => setChoosing(false) })) : null] }));