@sincpro/web-framework 0.4.1 → 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.
package/README.md CHANGED
@@ -262,13 +262,9 @@ function InvoiceView({ api, resource }: ViewProps) {
262
262
  <RecordField
263
263
  record={invoice}
264
264
  name="customer_id"
265
+ // Inside a workspace the picker opens the chosen and «see all…» there by itself.
265
266
  as={({ value, set }) => (
266
- <EntityPicker
267
- entity={customers}
268
- value={String(value ?? "")}
269
- onChange={set}
270
- onBrowseAll={chooserIn(api, customers, set)}
271
- />
267
+ <EntityPicker entity={customers} value={String(value ?? "")} onChange={set} />
272
268
  )}
273
269
  />
274
270
  <RecordField record={invoice} name="notes" />
@@ -394,44 +390,46 @@ Everything is imported from `@sincpro/web-framework`.
394
390
 
395
391
  ## Where it stands
396
392
 
397
- | Piece | What it solves | Status |
398
- | -------------------------------------- | ------------------------------------------------------------------------------------------ | ------ |
399
- | `restTransport`, `memoryTransport` | The backend, or the same engine in memory | ✅ |
400
- | `defineMeta`, `metaFromSchema` | A model by hand, or completed from OpenAPI | ✅ |
401
- | `useListing`, `EntityList` | N records: criteria, search bar, builder, paging | ✅ |
402
- | `useRecord`, `factsOf`, `RecordLines` | One record: facts, relations with their real total | ✅ |
403
- | Preloaded definitions | `FrameworkProvider metas`: the model asked once, or never | ✅ |
404
- | `useLookup`, `EntityPicker` | Literal search: a many2one select, ⌘K | ✅ |
405
- | `useRecord` + `RecordField`, `dirtyOf` | Editing: hints evaluated live, preview, save with version (409), server drafts | ✅ |
406
- | `useCommand`, `CommandButton` | An entity's actions, with a dry run before what destroys | ✅ |
407
- | `useHistory` | Business events in `Record.Activity` (comments: backend first) | ✅ |
408
- | `entityView` | An entity as a composer view: list, record, ⌘K search | ✅ |
409
- | `<SincproApp>` | The application context in one place, the workspace dressed as web-ui (`webUiSkin`) | ✅ |
410
- | `useRecordInWorkspace` | A record tells the workspace its real name and its unsaved work (composer 1.0) | ✅ |
411
- | Paging by pages, ceiling on «more» | One page on screen, walked by the server's cursor: a million rows never freeze it | ✅ |
412
- | `cachedTransport` | Repeated reads from memory, forgotten when a write touches the entity (on in `SincproApp`) | ✅ |
413
- | `EntitySearchBar` | The search bar + criteria builder as a loose piece, for any `List` | ✅ |
414
- | `EntityList` views | The same set as table, rows or board | ✅ |
415
- | `useRelated`, `RelatedList` | A record's relation as a live list: searched and paged by the server, inside a form | ✅ |
416
- | `EntityPicker` chooser | «see all…» opens the whole set, searched on the server: a many2one over millions | ✅ |
417
- | `useRecord(entity, "")`, `create` | A new record: the model's defaults, saved to `create`, then it IS the record it became | ✅ |
418
- | `retryKeys`, `Idempotency-Key` | A Command or a create retried after a lost answer runs once, not twice | ✅ |
419
- | `entity.newRef()`, «New» in the list | The record's form with no id, in a page or a window; replaced by the record once created | ✅ |
420
- | `EntityPicker criteria` | A many2one narrowed by another field: the invoices OF the chosen customer | ✅ |
421
- | `chooserIn`, `entity.chooserRef()` | «see all…» as the composer's chooser: a row answers (`api.pick`) | ✅ |
422
- | `useGroups`, «Group by» | Groups counted by the server over the whole set; a group's rows read when it is opened | ✅ |
423
- | `defineList`, `listView` | A named list (a fixed scope, its columns and filters) as data, and as a workspace view | ✅ |
424
- | `EntityPicker` `browse`, `columns` | The chooser always a click away, as a table searched literally by the server | ✅ |
425
- | `useFollowed` | A detail panel follows the record the person is on, without knowing the list | ✅ |
426
- | `commands`, `useRowCommands` | An entity's Commands on each row, idempotent, offered only where `when` holds | ✅ |
427
- | `summaryOf`, `cardOf`, `relationOf` | Any record at any size: name, description, state, type, picture, who made and changed it | ✅ |
428
- | `openIn`, `RelatedRecord` | A related record opens in a modal; «Abrir en…» for the rest; never a modal over a modal | ✅ |
429
- | Literal search everywhere | Picker: the first ten, the server's search as you type; tables: «Buscar «X»» on Enter | ✅ |
430
- | `EntityTags` | A many2many as chips over thousands: the server's search, faces, the chosen never again | ✅ |
431
- | `RecordField` + `entities` | A many2one / one2many drawn from the model alone, opened where the view says | ✅ |
432
- | `EntityRecord`, `formOf` | Any entity's record screen without writing it | ✅ |
433
- | `Trail`, `Record.Pager` | Previous / next from a record, across the server's pages | ✅ |
434
- | `EntityList sums` | Each group says how much it adds up, summed by the server over all of it | ✅ |
393
+ | Piece | What it solves | Status |
394
+ | --------------------------------------- | ------------------------------------------------------------------------------------------ | ------ |
395
+ | `restTransport`, `memoryTransport` | The backend, or the same engine in memory | ✅ |
396
+ | `defineMeta`, `metaFromSchema` | A model by hand, or completed from OpenAPI | ✅ |
397
+ | `useListing`, `EntityList` | N records: criteria, search bar, builder, paging | ✅ |
398
+ | `useRecord`, `factsOf`, `RecordLines` | One record: facts, relations with their real total | ✅ |
399
+ | Preloaded definitions | `FrameworkProvider metas`: the model asked once, or never | ✅ |
400
+ | `useLookup`, `EntityPicker` | Literal search: a many2one select, ⌘K | ✅ |
401
+ | `useRecord` + `RecordField`, `dirtyOf` | Editing: hints evaluated live, preview, save with version (409), server drafts | ✅ |
402
+ | `useCommand`, `CommandButton` | An entity's actions, with a dry run before what destroys | ✅ |
403
+ | `useHistory` | Business events in `Record.Activity` (comments: backend first) | ✅ |
404
+ | `entityView` | An entity as a composer view: list, record, ⌘K search | ✅ |
405
+ | `<SincproApp>` | The application context in one place, the workspace dressed as web-ui (`webUiSkin`) | ✅ |
406
+ | `useRecordInWorkspace` | A record tells the workspace its real name and its unsaved work (composer 1.0) | ✅ |
407
+ | Paging by pages, ceiling on «more» | One page on screen, walked by the server's cursor: a million rows never freeze it | ✅ |
408
+ | `cachedTransport` | Repeated reads from memory, forgotten when a write touches the entity (on in `SincproApp`) | ✅ |
409
+ | `EntitySearchBar` | The search bar + criteria builder as a loose piece, for any `List` | ✅ |
410
+ | `EntityList` views | The same set as table, rows or board | ✅ |
411
+ | `useRelated`, `RelatedList` | A record's relation as a live list: searched and paged by the server, inside a form | ✅ |
412
+ | `EntityPicker` chooser | «see all…» opens the whole set, searched on the server: a many2one over millions | ✅ |
413
+ | `useRecord(entity, "")`, `create` | A new record: the model's defaults, saved to `create` (or `edit`), then it IS that record | ✅ |
414
+ | `retryKeys`, `Idempotency-Key` | A Command or a create retried after a lost answer runs once, not twice | ✅ |
415
+ | `entity.newRef()`, «New» in the list | The record's form with no id, in a page or a window; replaced by the record once created | ✅ |
416
+ | `EntityPicker criteria` | A many2one narrowed by another field: the invoices OF the chosen customer | ✅ |
417
+ | `chooserIn`, `entity.chooserRef()` | «see all…» as the composer's chooser: a row answers (`api.pick`) | ✅ |
418
+ | `EntityPicker` / `EntityTags` in a view | Open and choose in the workspace by themselves; the chooser carries the picker's cut | ✅ |
419
+ | `newEntityId`, `edit` on a new record | A new record born under a UUID v7 minted here: its draft and its save go through `Edit` | ✅ |
420
+ | `useGroups`, «Group by» | Groups counted by the server over the whole set; a group's rows read when it is opened | ✅ |
421
+ | `defineList`, `listView` | A named list (a fixed scope, its columns and filters) as data, and as a workspace view | ✅ |
422
+ | `EntityPicker` `browse`, `columns` | The chooser always a click away, as a table searched literally by the server | ✅ |
423
+ | `useFollowed` | A detail panel follows the record the person is on, without knowing the list | ✅ |
424
+ | `commands`, `useRowCommands` | An entity's Commands on each row, idempotent, offered only where `when` holds | ✅ |
425
+ | `summaryOf`, `cardOf`, `relationOf` | Any record at any size: name, description, state, type, picture, who made and changed it | ✅ |
426
+ | `openIn`, `RelatedRecord` | A related record opens in a modal; «Abrir en…» for the rest; never a modal over a modal | ✅ |
427
+ | Literal search everywhere | Picker: the first ten, the server's search as you type; tables: «Buscar «X»» on Enter | ✅ |
428
+ | `EntityTags` | A many2many as chips over thousands: the server's search, faces, the chosen never again | ✅ |
429
+ | `RecordField` + `entities` | A many2one / one2many drawn from the model alone, opened where the view says | ✅ |
430
+ | `EntityRecord`, `formOf` | Any entity's record screen without writing it | ✅ |
431
+ | `Trail`, `Record.Pager` | Previous / next from a record, across the server's pages | ✅ |
432
+ | `EntityList sums` | Each group says how much it adds up, summed by the server over all of it | ✅ |
435
433
 
436
434
  What it does **not** do: mobile (`sincpro_mobile` has its own core), sessions and login (the
437
435
  application's), routing (composer's), string-named widget registries, technical logs on a
@@ -1,4 +1,4 @@
1
- import type { AnyRecord } from "@sincpro/criteria";
1
+ import { type AnyRecord, type Expression } from "@sincpro/criteria";
2
2
  import type { SummaryFields } from "./summary.js";
3
3
  import type { Method } from "./transport.js";
4
4
  /**
@@ -34,8 +34,9 @@ export type Entity<T extends AnyRecord = AnyRecord> = {
34
34
  * from its customer starts with that customer (`startingValuesOf`). */
35
35
  newRef: (values?: AnyRecord) => EntityRef;
36
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;
37
+ * `query`, the list opens on that literal search — what was typed in the picker; with
38
+ * `scope`, it offers only what the picker may choose (`scopeOfRef`). */
39
+ chooserRef: (query?: string, scope?: Expression) => EntityRef;
39
40
  /** The route of its list. */
40
41
  list: string;
41
42
  /** The route of one record. */
@@ -89,6 +90,9 @@ export declare const TRAIL_PARAM = "from";
89
90
  /** What a new record starts with, as JSON: one param keeps each value's type (a number stays
90
91
  * a number), where a param per field would turn all of them into text. */
91
92
  export declare const WITH_PARAM = "with";
93
+ /** What a chooser may offer at all, as JSON: the picker's cut — its criteria, the keys it
94
+ * excludes, its named list's scope — that the list it opens ANDs under everything. */
95
+ export declare const SCOPE_PARAM = "scope";
92
96
  /**
93
97
  * What a new record's reference says it starts with (`newRef(values)`), or nothing.
94
98
  *
@@ -96,6 +100,17 @@ export declare const WITH_PARAM = "with";
96
100
  * typed in the address bar — a value that is not a JSON object is not a start, never an error.
97
101
  */
98
102
  export declare function startingValuesOf(ref: Pick<EntityRef, "params">): AnyRecord;
103
+ /**
104
+ * The cut a chooser's reference carries (`chooserRef(query, scope)`), or nothing.
105
+ *
106
+ * Context: a picker that may offer only some records — the contacts of the chosen customer, the
107
+ * tenants a project is not shared with yet — opened the workspace's chooser on the WHOLE
108
+ * entity, and offered the rest. The cut travels in the reference, so it survives a reload; read
109
+ * from an address bar it is untyped, so it is read the way criteria reads a filter from outside
110
+ * (`readExpression`), and one that does not read is no cut, never an error. It narrows what is
111
+ * OFFERED; the server still decides what may be stored.
112
+ */
113
+ export declare function scopeOfRef(ref: Pick<EntityRef, "params">): Expression | undefined;
99
114
  /** A write: its method and its path, `{id}` where the record's key goes. */
100
115
  export type WriteRoute = {
101
116
  method: Method;
@@ -1,3 +1,4 @@
1
+ import { readExpression } from "@sincpro/criteria";
1
2
  /**
2
3
  * The params that say what a reference without an id is for: `new` is the form of a record
3
4
  * that does not exist yet, `pick` is the list opened to choose one. Params, because they are
@@ -12,6 +13,9 @@ export const TRAIL_PARAM = "from";
12
13
  /** What a new record starts with, as JSON: one param keeps each value's type (a number stays
13
14
  * a number), where a param per field would turn all of them into text. */
14
15
  export const WITH_PARAM = "with";
16
+ /** What a chooser may offer at all, as JSON: the picker's cut — its criteria, the keys it
17
+ * excludes, its named list's scope — that the list it opens ANDs under everything. */
18
+ export const SCOPE_PARAM = "scope";
15
19
  /**
16
20
  * What a new record's reference says it starts with (`newRef(values)`), or nothing.
17
21
  *
@@ -32,6 +36,27 @@ export function startingValuesOf(ref) {
32
36
  return {};
33
37
  }
34
38
  }
39
+ /**
40
+ * The cut a chooser's reference carries (`chooserRef(query, scope)`), or nothing.
41
+ *
42
+ * Context: a picker that may offer only some records — the contacts of the chosen customer, the
43
+ * tenants a project is not shared with yet — opened the workspace's chooser on the WHOLE
44
+ * entity, and offered the rest. The cut travels in the reference, so it survives a reload; read
45
+ * from an address bar it is untyped, so it is read the way criteria reads a filter from outside
46
+ * (`readExpression`), and one that does not read is no cut, never an error. It narrows what is
47
+ * OFFERED; the server still decides what may be stored.
48
+ */
49
+ export function scopeOfRef(ref) {
50
+ const written = ref.params?.[SCOPE_PARAM];
51
+ if (written === undefined)
52
+ return undefined;
53
+ try {
54
+ return readExpression(JSON.parse(written));
55
+ }
56
+ catch {
57
+ return undefined;
58
+ }
59
+ }
35
60
  const METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);
36
61
  /** `"POST /invoices/{id}/confirm"` → its method and path. A write without a method is a bug. */
37
62
  export function writeRoute(text) {
@@ -91,7 +116,7 @@ export function entity(key, routes) {
91
116
  : { [WITH_PARAM]: JSON.stringify(values) }),
92
117
  },
93
118
  }),
94
- chooserRef: (query) => ({
119
+ chooserRef: (query, scope) => ({
95
120
  domain,
96
121
  kind,
97
122
  params: {
@@ -99,6 +124,7 @@ export function entity(key, routes) {
99
124
  ...(query === undefined || query.trim() === ""
100
125
  ? {}
101
126
  : { [QUERY_PARAM]: query.trim() }),
127
+ ...(scope === undefined ? {} : { [SCOPE_PARAM]: JSON.stringify(scope) }),
102
128
  },
103
129
  }),
104
130
  list: routes.list,
@@ -0,0 +1,17 @@
1
+ /**
2
+ * A new record's key, minted where the record is born: a UUID v7 as 32 hex characters —
3
+ * sincpro_framework's `new_entity_id`.
4
+ *
5
+ * Context: sincpro_framework's `Edit` creates a new record under the id the CLIENT names («a
6
+ * UUID v7 it mints»), and the draft and the stored record share it from the first draft save.
7
+ * A form that waited for the server to name it could neither keep a draft of a new record nor
8
+ * reach the edit route at all (`PUT /invoices/{id}/edit` needs the id in its path). The layout
9
+ * is the backend's (RFC 9562): 48 bits of unix milliseconds, the version, a 12-bit counter
10
+ * within the millisecond, the variant and 62 random bits — so ids minted here sort by when
11
+ * they were minted, like the server's, and ordering by `id` is still ordering by creation.
12
+ *
13
+ * newEntityId() // "019a4c2e7f1074a8b13fa739ccbdcd53"
14
+ */
15
+ export declare function newEntityId(now?: number): string;
16
+ /** A key that is a UUID v7 as sincpro_framework writes it: 32 hex, version 7, variant `10`. */
17
+ export declare function isEntityId(text: string): boolean;
@@ -0,0 +1,52 @@
1
+ /**
2
+ * A new record's key, minted where the record is born: a UUID v7 as 32 hex characters —
3
+ * sincpro_framework's `new_entity_id`.
4
+ *
5
+ * Context: sincpro_framework's `Edit` creates a new record under the id the CLIENT names («a
6
+ * UUID v7 it mints»), and the draft and the stored record share it from the first draft save.
7
+ * A form that waited for the server to name it could neither keep a draft of a new record nor
8
+ * reach the edit route at all (`PUT /invoices/{id}/edit` needs the id in its path). The layout
9
+ * is the backend's (RFC 9562): 48 bits of unix milliseconds, the version, a 12-bit counter
10
+ * within the millisecond, the variant and 62 random bits — so ids minted here sort by when
11
+ * they were minted, like the server's, and ordering by `id` is still ordering by creation.
12
+ *
13
+ * newEntityId() // "019a4c2e7f1074a8b13fa739ccbdcd53"
14
+ */
15
+ const COUNTER_MAX = 0xfff;
16
+ let lastMillis = -1;
17
+ let counter = 0;
18
+ function randomBytes(count) {
19
+ return globalThis.crypto.getRandomValues(new Uint8Array(count));
20
+ }
21
+ function hex(value, digits) {
22
+ return value.toString(16).padStart(digits, "0");
23
+ }
24
+ export function newEntityId(now = Date.now()) {
25
+ // The clock never runs backwards for these ids: the same millisecond (or an earlier one, a
26
+ // clock moved back) counts up; a full counter borrows the next millisecond.
27
+ let millis = now;
28
+ if (millis <= lastMillis) {
29
+ millis = lastMillis;
30
+ counter += 1;
31
+ if (counter > COUNTER_MAX) {
32
+ millis += 1;
33
+ counter = 0;
34
+ }
35
+ }
36
+ else {
37
+ // A fresh millisecond starts the counter at a random point of its lower half: room to count.
38
+ const [high = 0, low = 0] = randomBytes(2);
39
+ counter = ((high << 8) | low) & 0x7ff;
40
+ }
41
+ lastMillis = millis;
42
+ const tail = randomBytes(8);
43
+ tail[0] = ((tail[0] ?? 0) & 0x3f) | 0x80; // the variant, `10`
44
+ return (hex(millis, 12) +
45
+ "7" + // the version
46
+ hex(counter, 3) +
47
+ Array.from(tail, (byte) => hex(byte, 2)).join(""));
48
+ }
49
+ /** A key that is a UUID v7 as sincpro_framework writes it: 32 hex, version 7, variant `10`. */
50
+ export function isEntityId(text) {
51
+ return /^[0-9a-f]{12}7[0-9a-f]{3}[89ab][0-9a-f]{15}$/.test(text);
52
+ }
@@ -6,9 +6,10 @@
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
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, listRoute, NEW_PARAM, pathFor, PICK_PARAM, QUERY_PARAM, startingValuesOf, TRAIL_PARAM, WITH_PARAM, type WriteRoute, writeRoute, } from "./entity.js";
9
+ export { type Entity, entity, type EntityRef, type EntityRoutes, listRoute, NEW_PARAM, pathFor, PICK_PARAM, QUERY_PARAM, SCOPE_PARAM, scopeOfRef, startingValuesOf, TRAIL_PARAM, WITH_PARAM, type WriteRoute, writeRoute, } from "./entity.js";
10
10
  export { type FormLayout, formOf } from "./form.js";
11
11
  export { type HistoryEntry, historyOf } from "./history.js";
12
+ export { isEntityId, newEntityId } from "./ids.js";
12
13
  export { addingOf, type AddingRule, blankLine, type Declared, editableLines, type LineAdding, lineFields, lineKey, linesAnswered, moved, sameLine, writtenInCell, } from "./lines.js";
13
14
  export { defineList, type GroupLevel, isList, type ListDefinition, type ListSpec, type NamedFilter, scopeOf, } from "./list.js";
14
15
  export { lookupOf, type LookupOption } from "./lookup.js";
@@ -6,9 +6,10 @@
6
6
  export { cachedTransport, } from "./cache.js";
7
7
  export { ENGLISH_FRAMEWORK_COPY, frameworkCopy, installFrameworkCopy, SPANISH_FRAMEWORK_COPY, } from "./copy.js";
8
8
  export { adviceAt, changesOf, creationOf, defaultsOf, errorAt, errorsByField, fieldStateOf, lineStatesOf, missingOf, pathOf, } from "./edit.js";
9
- export { entity, listRoute, NEW_PARAM, pathFor, PICK_PARAM, QUERY_PARAM, startingValuesOf, TRAIL_PARAM, WITH_PARAM, writeRoute, } from "./entity.js";
9
+ export { entity, listRoute, NEW_PARAM, pathFor, PICK_PARAM, QUERY_PARAM, SCOPE_PARAM, scopeOfRef, startingValuesOf, TRAIL_PARAM, WITH_PARAM, writeRoute, } from "./entity.js";
10
10
  export { formOf } from "./form.js";
11
11
  export { historyOf } from "./history.js";
12
+ export { isEntityId, newEntityId } from "./ids.js";
12
13
  export { addingOf, blankLine, editableLines, lineFields, lineKey, linesAnswered, moved, sameLine, writtenInCell, } from "./lines.js";
13
14
  export { defineList, isList, scopeOf, } from "./list.js";
14
15
  export { lookupOf } from "./lookup.js";
@@ -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
+ }
@@ -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,13 +13,17 @@ 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 ? [] : [{ where: 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]);
@@ -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
@@ -80,7 +86,7 @@ export type Editing = {
80
86
  save: () => Promise<boolean>;
81
87
  discard: () => void;
82
88
  /** 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. */
89
+ * `edit`), and the record exists or is born by `Edit` under the key minted for it. */
84
90
  keep?: () => Promise<void>;
85
91
  /** What the last create answered, when it did not say the new record's identity. */
86
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,6 +143,19 @@ 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)
@@ -194,8 +211,10 @@ export function useRecord(entity, opened) {
194
211
  // draft version read (`0`: none) — another tab that kept first wins —, and the stored version
195
212
  // the edit started from. Without an `action` it is the server's default, `save_draft`.
196
213
  const editOf = (action) => ({
197
- id,
198
- values,
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,
199
218
  changed: Object.keys(changed),
200
219
  version: draft?.version ?? 0,
201
220
  ...(typeof version === "number" ? { origin_version: version } : {}),
@@ -227,7 +246,7 @@ export function useRecord(entity, opened) {
227
246
  restored: draft !== null && (draft.values === undefined || Object.keys(changed).length > 0),
228
247
  draft,
229
248
  save: async () => {
230
- if (isNew)
249
+ if (isNew && !byEdit)
231
250
  return create();
232
251
  const route = entity.edit ?? entity.save;
233
252
  if (route === undefined)
@@ -235,12 +254,21 @@ export function useRecord(entity, opened) {
235
254
  cancelPreview();
236
255
  setSaving(true);
237
256
  setFailure(null);
257
+ const key = keyNow();
238
258
  try {
239
- await transport.send(route.method, pathFor(route, id, values), entity.edit === undefined
259
+ await transport.send(route.method, pathFor(route, key, values), entity.edit === undefined
240
260
  ? { ...changed, ...(version === undefined ? {} : { version }) }
241
261
  : editOf("save"));
242
262
  setDraft(null);
243
- 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();
244
272
  return true;
245
273
  }
246
274
  catch (error) {
@@ -259,23 +287,24 @@ export function useRecord(entity, opened) {
259
287
  forget();
260
288
  // The draft lives on the server: discarding only here would bring it back on the next read.
261
289
  const route = entity.edit;
262
- if (route === undefined || isNew || draft === null)
290
+ if (route === undefined || draft === null)
263
291
  return;
264
292
  setDraft(null);
265
293
  // Through the promise: a route key the record lacks is refused like any failure.
266
294
  Promise.resolve()
267
- .then(() => transport.send(route.method, pathFor(route, id, values), editOf("discard")))
295
+ .then(() => transport.send(route.method, pathFor(route, keyNow(), values), editOf("discard")))
268
296
  .then(() => mounted.current && reload())
269
297
  .catch((error) => mounted.current && refused(error));
270
298
  },
271
299
  created,
272
- ...((entity.edit ?? 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)
273
302
  ? {}
274
303
  : {
275
304
  keep: async () => {
276
305
  const route = (entity.edit ?? entity.draft);
277
306
  try {
278
- const kept = await transport.send(route.method, pathFor(route, id, values), entity.edit === undefined ? editOf() : editOf("save_draft"));
307
+ const kept = await transport.send(route.method, pathFor(route, keyNow(), values), entity.edit === undefined ? editOf() : editOf("save_draft"));
279
308
  const now = kept.draft;
280
309
  if (now)
281
310
  setDraft({
@@ -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;
@@ -8,6 +8,7 @@ import { useListing } from "../../react/useListing.js";
8
8
  import { excluding, useLookup } from "../../react/useLookup.js";
9
9
  import { EntityList } from "../list/EntityList.js";
10
10
  import { over, presentationOf } from "../list/presentation.js";
11
+ import { chooserScopeOf, useRecordOpening } from "./opening.js";
11
12
  import { Dialog, IconButton, Picker } from "@sincpro/web-ui";
12
13
  import { TextSearch } from "lucide-react";
13
14
  import { useState } from "react";
@@ -23,9 +24,13 @@ import { useState } from "react";
23
24
  * searched, ordered and paged by the server, where clicking a row answers the field. An entity
24
25
  * without a search template is filtered where it is.
25
26
  *
26
- * Inside a workspace, «open» and the chooser can be the composer's instead (`api.open`,
27
- * `api.pick`): pass `onOpen` / `onBrowseAll` and they replace the defaults — `chooserIn(api,
28
- * 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.
29
34
  *
30
35
  * `criteria` narrows what may be chosen — the contacts of the chosen customer — in the picker
31
36
  * and in its chooser alike; the server applies it, and a new one starts the choices over. A
@@ -47,9 +52,10 @@ import { useState } from "react";
47
52
  * <EntityPicker entity={activeCustomers} columns={["name", "tax_id", "city"]} … />
48
53
  * <EntityPicker entity={tenants} none="Sin tenant" exclude={sharedWith} … />
49
54
  */
50
- export function EntityPicker({ entity, value, onChange, onOpen, openTargets, onBrowseAll, criteria, columns, browse = true, none, exclude, 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, }) {
51
56
  const base = isList(entity) ? entity.entity : entity;
52
57
  const { metas } = useFramework();
58
+ const opening = useRecordOpening();
53
59
  const lookup = useLookup(entity, {
54
60
  ...(criteria === undefined ? {} : { criteria }),
55
61
  ...(value === undefined ? {} : { value }),
@@ -63,7 +69,16 @@ export function EntityPicker({ entity, value, onChange, onOpen, openTargets, onB
63
69
  : [{ id: "", name: none === true ? frameworkCopy().picker.none : none }];
64
70
  const look = presentationOf(entity).option;
65
71
  const [choosing, setChoosing] = useState(false);
66
- const browseAll = onBrowseAll ?? (() => setChoosing(true));
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)));
67
82
  const picker = (_jsx(Picker, { items: [
68
83
  ...nothing,
69
84
  ...lookup.options.map((one) => over({
@@ -85,7 +100,7 @@ export function EntityPicker({ entity, value, onChange, onOpen, openTargets, onB
85
100
  : look(lookup.chosen.record).name) ?? lookup.chosen.label,
86
101
  }), onChange: (id) => onChange(id, lookup.options.find((one) => one.id === id)?.record), ...(lookup.searchable ? { onSearch: lookup.search } : {}),
87
102
  // «Loading» only before there is anything: refining keeps the ten on screen.
88
- loading: lookup.loading && lookup.options.length === 0, ...(onOpen === undefined || value === "" ? {} : { onOpen }), ...(openTargets === undefined ? {} : { openTargets }), onBrowseAll: browseAll, ...(placeholder === undefined ? {} : { placeholder }), ...(disabled === undefined ? {} : { disabled }), ...(ariaLabel === undefined ? {} : { "aria-label": ariaLabel }) }));
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 }) }));
89
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) => {
90
105
  onChange(id, row);
91
106
  setChoosing(false);
@@ -13,9 +13,11 @@ import { type OpenTarget } from "@sincpro/web-ui";
13
13
  * once by their keys. A person or a company (`entity(…, { summary: { person: true } })`) is
14
14
  * chosen by their face.
15
15
  *
16
- * Opening a chip is the composer's (`onOpen` — a preview by default: a chip is a glance at one
17
- * of many), and «Buscar más…» is the list that adds (`onBrowseAll`, `api.pick` with the list in
18
- * its choosing mode). Without a workspace a chip is a value.
16
+ * Inside a workspace, opening a chip and «Buscar más…» are the workspace's (`RecordOpening`),
17
+ * as for a many2one: a chip opens where the workspace puts it, and «Buscar más…» is the
18
+ * entity's list opened to choose, offering neither what `criteria` leaves out nor the chips
19
+ * already on — the record answered there is added. `onOpen` / `onBrowseAll` replace either.
20
+ * Without a workspace a chip is a value.
19
21
  *
20
22
  * <EntityTags entity={people} value={followers} onChange={setFollowers} />
21
23
  */
@@ -1,9 +1,12 @@
1
1
  "use client";
2
2
  import { jsx as _jsx } from "react/jsx-runtime";
3
3
  import { isList } from "../../core/list.js";
4
- import { useLookup } from "../../react/useLookup.js";
4
+ import { useFramework } from "../../react/context.js";
5
+ import { excluding, useLookup } from "../../react/useLookup.js";
5
6
  import { presentationOf } from "../list/presentation.js";
7
+ import { chooserScopeOf, useRecordOpening } from "./opening.js";
6
8
  import { TagsField } from "@sincpro/web-ui";
9
+ import { useRef } from "react";
7
10
  /**
8
11
  * A many2many: put SEVERAL records of an entity on this one — the followers of an invoice,
9
12
  * the products of a promotion — as web-ui's `TagsField` chips, fed by `useLookup`.
@@ -15,18 +18,38 @@ import { TagsField } from "@sincpro/web-ui";
15
18
  * once by their keys. A person or a company (`entity(…, { summary: { person: true } })`) is
16
19
  * chosen by their face.
17
20
  *
18
- * Opening a chip is the composer's (`onOpen` — a preview by default: a chip is a glance at one
19
- * of many), and «Buscar más…» is the list that adds (`onBrowseAll`, `api.pick` with the list in
20
- * its choosing mode). Without a workspace a chip is a value.
21
+ * Inside a workspace, opening a chip and «Buscar más…» are the workspace's (`RecordOpening`),
22
+ * as for a many2one: a chip opens where the workspace puts it, and «Buscar más…» is the
23
+ * entity's list opened to choose, offering neither what `criteria` leaves out nor the chips
24
+ * already on — the record answered there is added. `onOpen` / `onBrowseAll` replace either.
25
+ * Without a workspace a chip is a value.
21
26
  *
22
27
  * <EntityTags entity={people} value={followers} onChange={setFollowers} />
23
28
  */
24
29
  export function EntityTags({ entity, value, onChange, criteria, onOpen, openTarget, onBrowseAll, placeholder, disabled, "aria-label": ariaLabel, }) {
30
+ const { metas } = useFramework();
31
+ const opening = useRecordOpening();
32
+ const base = isList(entity) ? entity.entity : entity;
33
+ // «Buscar más…» answers after the chooser closes: it adds to the chips on screen THEN.
34
+ const now = useRef(value);
35
+ now.current = value;
36
+ const opens = onOpen ??
37
+ (opening === null
38
+ ? undefined
39
+ : (id, to) => opening.open(base.ref(id), to));
40
+ const choose = opening?.choose;
41
+ const browseAll = onBrowseAll ??
42
+ (choose === undefined
43
+ ? undefined
44
+ : (query) => choose(base, (id) => {
45
+ if (!now.current.includes(id))
46
+ onChange([...now.current, id]);
47
+ }, query, chooserScopeOf(entity, excluding(criteria, value, metas.get(base.key)))));
25
48
  const lookup = useLookup(entity, {
26
49
  ...(criteria === undefined ? {} : { criteria }),
27
50
  values: value,
28
51
  });
29
- const person = (isList(entity) ? entity.entity : entity).summary.person === true;
52
+ const person = base.summary.person === true;
30
53
  const look = presentationOf(entity).option;
31
54
  // A chip says a name and shows a face; the list under it also the datum that tells two apart
32
55
  // (web-ui 1.5 `TagOption.meta`, never on the chip). Of the entity's look of a choice, those
@@ -48,5 +71,5 @@ export function EntityTags({ entity, value, onChange, criteria, onOpen, openTarg
48
71
  ...lookup.options.map(asTag),
49
72
  ...lookup.chosenAll.filter((one) => !offered.has(one.id)).map(asTag),
50
73
  ];
51
- return (_jsx(TagsField, { value: value, onChange: onChange, options: options, ...(lookup.searchable ? { onSearch: lookup.search } : {}), ...(onOpen === undefined ? {} : { onOpen }), ...(openTarget === undefined ? {} : { openTarget }), ...(onBrowseAll === undefined ? {} : { onBrowseAll }), ...(placeholder === undefined ? {} : { placeholder }), ...(disabled === undefined ? {} : { disabled }), ...(ariaLabel === undefined ? {} : { "aria-label": ariaLabel }) }));
74
+ return (_jsx(TagsField, { value: value, onChange: onChange, options: options, ...(lookup.searchable ? { onSearch: lookup.search } : {}), ...(opens === undefined ? {} : { onOpen: opens }), ...(openTarget === undefined ? {} : { openTarget }), ...(browseAll === undefined ? {} : { onBrowseAll: browseAll }), ...(placeholder === undefined ? {} : { placeholder }), ...(disabled === undefined ? {} : { disabled }), ...(ariaLabel === undefined ? {} : { "aria-label": ariaLabel }) }));
52
75
  }
@@ -27,10 +27,10 @@ export declare function controlFor(control: FieldControl, type: string, exact: b
27
27
  * A many2one's control: the picker of the entity it points at — the server's literal search,
28
28
  * the first ten, «Buscar más…» — opening the chosen one where the view says.
29
29
  *
30
- * Context: shared by a record's field and a line. Inside a line (`ownChooser`: its row or its
31
- * dialog) «Buscar más…» is the picker's own chooser, never the workspace's: the workspace opens
32
- * it outside the line — a row commits when the focus leaves it, and the answer would land on a
33
- * line no longer being written; over the line's dialog it would be a modal over a modal.
30
+ * Context: shared by a record's field and a line. Where it opens is `EntityPicker`'s — the
31
+ * workspace's when there is one. Inside a line the lines editor gives an opening without the
32
+ * workspace's chooser (`RecordLinesEditor`), so «Buscar más…» is the picker's own there;
33
+ * `ownChooser` asks for it anywhere else.
34
34
  */
35
35
  export declare function RelationPicker({ target, value, onChange, label, ownChooser, standalone, }: {
36
36
  target: Entity;
@@ -2,7 +2,6 @@
2
2
  import { jsx as _jsx } from "react/jsx-runtime";
3
3
  import { instantOf, timeZoneNow, wallTimeOf } from "../../core/zone.js";
4
4
  import { EntityPicker } from "./EntityPicker.js";
5
- import { useRecordOpening } from "./opening.js";
6
5
  import { Checkbox, DatePicker, DateTimePicker, NumberInput, Select, TagsField, TextInput, } from "@sincpro/web-ui";
7
6
  /**
8
7
  * The control a field's TYPE asks for — a choice, a number, a date, a date and time, a yes/no, a
@@ -44,24 +43,15 @@ export function controlFor(control, type, exact, choices) {
44
43
  * A many2one's control: the picker of the entity it points at — the server's literal search,
45
44
  * the first ten, «Buscar más…» — opening the chosen one where the view says.
46
45
  *
47
- * Context: shared by a record's field and a line. Inside a line (`ownChooser`: its row or its
48
- * dialog) «Buscar más…» is the picker's own chooser, never the workspace's: the workspace opens
49
- * it outside the line — a row commits when the focus leaves it, and the answer would land on a
50
- * line no longer being written; over the line's dialog it would be a modal over a modal.
46
+ * Context: shared by a record's field and a line. Where it opens is `EntityPicker`'s — the
47
+ * workspace's when there is one. Inside a line the lines editor gives an opening without the
48
+ * workspace's chooser (`RecordLinesEditor`), so «Buscar más…» is the picker's own there;
49
+ * `ownChooser` asks for it anywhere else.
51
50
  */
52
51
  export function RelationPicker({ target, value, onChange, label, ownChooser = false, standalone = false, }) {
53
- const opening = useRecordOpening();
52
+ // Opening the chosen record and «Buscar más…» are the workspace's when there is one: the
53
+ // picker reads it (`RecordOpening`); a line keeps its own chooser.
54
54
  return (_jsx(EntityPicker, { entity: target, value: value, onChange: onChange,
55
55
  // «Buscar más…» is an option of the picker already: no second button beside it.
56
- browse: false, ...(standalone ? { "aria-label": label } : {}), ...(opening === null
57
- ? {}
58
- : {
59
- onOpen: (chosen, to) => opening.open(target.ref(chosen), to),
60
- openTargets: opening.targets,
61
- ...(ownChooser || opening.choose === undefined
62
- ? {}
63
- : {
64
- onBrowseAll: (query) => opening.choose?.(target, (id) => onChange(id), query),
65
- }),
66
- }) }));
56
+ browse: false, ownChooser: ownChooser, ...(standalone ? { "aria-label": label } : {}) }));
67
57
  }
@@ -7,6 +7,7 @@ import { textOf, viewOf } from "../../core/present.js";
7
7
  import { entityFor, relationFieldOf, } from "../../core/relation.js";
8
8
  import { useEntityFor, useFramework } from "../../react/context.js";
9
9
  import { controlFor, RelationPicker, } from "./control.js";
10
+ import { RecordOpeningProvider, useRecordOpening, } from "./opening.js";
10
11
  import { Field, LineItems, ReadValue, } from "@sincpro/web-ui";
11
12
  import { useRef } from "react";
12
13
  /** How a field of a line reads: a many2one's key by the name of what it points at. */
@@ -41,7 +42,7 @@ function LineValue({ definition, field, line, set, label, invalid, locale, inCel
41
42
  });
42
43
  if (relation !== undefined && !relation.many && target !== undefined) {
43
44
  const key = line[relation.key];
44
- return (_jsx(RelationPicker, { target: target, value: key === null || key === undefined ? "" : String(key), label: label, ownChooser: true, standalone: inCell, onChange: (id, chosen) => write({ [relation.key]: id, [relation.relation]: chosen ?? null }) }));
45
+ return (_jsx(RelationPicker, { target: target, value: key === null || key === undefined ? "" : String(key), label: label, standalone: inCell, onChange: (id, chosen) => write({ [relation.key]: id, [relation.relation]: chosen ?? null }) }));
45
46
  }
46
47
  return controlFor({
47
48
  value: line[field],
@@ -83,6 +84,7 @@ function LineValue({ definition, field, line, set, label, invalid, locale, inCel
83
84
  export function RecordLinesEditor({ record, name, lines, look = {}, }) {
84
85
  const { meta, locale, edit } = record;
85
86
  const { entities, metas } = useFramework();
87
+ const opening = useRecordOpening();
86
88
  const definition = meta?.fields[name]?.definition ?? null;
87
89
  const identity = definition?.identity || "id";
88
90
  const fields = lineFields(definition);
@@ -146,7 +148,7 @@ export function RecordLinesEditor({ record, name, lines, look = {}, }) {
146
148
  ...(one.numeric === undefined ? {} : { numeric: one.numeric }),
147
149
  })),
148
150
  ];
149
- return (_jsx(LineItems, { lines: lines, columns: columns, getLineId: keyOf, mode: writing ? "edit" : "read", adding: adding, onChange: (key, next) => write((all) => all.map((one) => (keyOf(one) === key ? sameLine(one, next) : one))), newLine: () => blankLine(defaultsOf(definition), identity), onAdd: (line) => write((all) => [...all, line]), onRemove: (key) => write((all) => all.filter((one) => keyOf(one) !== key)), onRestore: (line, index) => write((all) => [...all.slice(0, index), line, ...all.slice(index)]), onReorder: (key, before) => write((all) => moved(all, identity, key, before)),
151
+ const table = (_jsx(LineItems, { lines: lines, columns: columns, getLineId: keyOf, mode: writing ? "edit" : "read", adding: adding, onChange: (key, next) => write((all) => all.map((one) => (keyOf(one) === key ? sameLine(one, next) : one))), newLine: () => blankLine(defaultsOf(definition), identity), onAdd: (line) => write((all) => [...all, line]), onRemove: (key) => write((all) => all.filter((one) => keyOf(one) !== key)), onRestore: (line, index) => write((all) => [...all.slice(0, index), line, ...all.slice(index)]), onReorder: (key, before) => write((all) => moved(all, identity, key, before)),
150
152
  // A cell says its own (web-ui 1.6 `cellState`): the line model's hints refined by the
151
153
  // server's `items[i]`, the error pointing at it (under its value) and its warning.
152
154
  cellState: (line, column) => {
@@ -187,4 +189,12 @@ export function RecordLinesEditor({ record, name, lines, look = {}, }) {
187
189
  return (_jsx(Field, { label: view.label, required: state.required && !state.readonly, ...(error === undefined ? {} : { error }), children: state.readonly ? (_jsx(ReadValue, { value: textIn(definition, field, relations.get(field), draft, locale) || "—" })) : (_jsx(LineValue, { definition: definition, field: field, line: draft, set: set, label: view.label, invalid: error !== undefined, locale: locale, inCell: false, own: controls[field] })) }, field));
188
190
  }) }));
189
191
  } }));
192
+ // Inside a line «Buscar más…» is the picker's own chooser, never the workspace's — the
193
+ // screen's own controls included: the workspace opens it outside the line, a row commits when
194
+ // the focus leaves it, and the answer would land on a line no longer being written (over the
195
+ // line's dialog, a modal over a modal). Opening a chosen record is still the workspace's.
196
+ if (opening === null || opening.choose === undefined)
197
+ return table;
198
+ const { choose: _, ...inLine } = opening;
199
+ return _jsx(RecordOpeningProvider, { value: inLine, children: table });
190
200
  }
@@ -1,5 +1,6 @@
1
- import type { AnyRecord } from "@sincpro/criteria";
1
+ import { type AnyRecord, type Criteria, type Expression } from "@sincpro/criteria";
2
2
  import type { Entity, EntityRef } from "../../core/entity.js";
3
+ import { type ListDefinition } from "../../core/list.js";
3
4
  import type { OpenTarget } from "@sincpro/web-ui";
4
5
  import { type ReactNode } from "react";
5
6
  /**
@@ -11,6 +12,12 @@ import { type ReactNode } from "react";
11
12
  * does not decide: the view that holds it says how to open (`entityView` fills it with the
12
13
  * composer's `openIn` and the places allowed from where the view is), and a field asks. Without
13
14
  * it a related record is a value, not a door.
15
+ *
16
+ * Every picker of an entity reads it by itself — `RecordField`, and an `EntityPicker` or
17
+ * `EntityTags` a screen writes by hand — so inside a workspace a record and a chooser always
18
+ * open in the workspace; what a screen passes (`onOpen`, `onBrowseAll`) still wins. Where the
19
+ * workspace's chooser must not be used — a line being written, whose answer would land on a line
20
+ * that already committed — the holder gives an opening without `choose`.
14
21
  */
15
22
  export type RecordOpening = {
16
23
  open: (ref: EntityRef, to: OpenTarget) => void;
@@ -20,8 +27,9 @@ export type RecordOpening = {
20
27
  * (a table of seven columns in 760 px breaks every number and date into three lines). */
21
28
  narrow?: boolean;
22
29
  /** «Buscar más…»: the entity's own list opened to choose (in composer, a modal that answers),
23
- * on what was typed. Without it the picker brings its own chooser. */
24
- choose?: (entity: Entity, answer: (id: string) => void, query: string) => void;
30
+ * on what was typed, offering only what `scope` lets the picker choose (`chooserScopeOf`).
31
+ * Without it the picker brings its own chooser. */
32
+ choose?: (entity: Entity, answer: (id: string) => void, query: string, scope?: Expression) => void;
25
33
  /** «Agregar» on a one2many: the form of a new record of `entity`, starting with `values`
26
34
  * (the key that points back here), opened where it answers; `created` once it exists.
27
35
  * Without it a record's one2many only reads. */
@@ -32,3 +40,9 @@ export declare function RecordOpeningProvider({ value, children, }: {
32
40
  children: ReactNode;
33
41
  }): import("react").JSX.Element;
34
42
  export declare function useRecordOpening(): RecordOpening | null;
43
+ /**
44
+ * What a picker's chooser may offer: its named list's scope and its own cut (criteria, the keys
45
+ * it excludes) as ONE expression — what `chooserRef(query, scope)` carries to the workspace,
46
+ * whose list knows nothing of the picker that opened it.
47
+ */
48
+ export declare function chooserScopeOf<T extends AnyRecord>(entity: Entity<T> | ListDefinition<T>, cut: Criteria<T> | undefined): Expression | undefined;
@@ -1,5 +1,7 @@
1
1
  "use client";
2
2
  import { jsx as _jsx } from "react/jsx-runtime";
3
+ import { merge } from "@sincpro/criteria";
4
+ import { isList, scopeOf } from "../../core/list.js";
3
5
  import { createContext, useContext } from "react";
4
6
  const Opening = createContext(null);
5
7
  export function RecordOpeningProvider({ value, children, }) {
@@ -8,3 +10,13 @@ export function RecordOpeningProvider({ value, children, }) {
8
10
  export function useRecordOpening() {
9
11
  return useContext(Opening);
10
12
  }
13
+ /**
14
+ * What a picker's chooser may offer: its named list's scope and its own cut (criteria, the keys
15
+ * it excludes) as ONE expression — what `chooserRef(query, scope)` carries to the workspace,
16
+ * whose list knows nothing of the picker that opened it.
17
+ */
18
+ export function chooserScopeOf(entity, cut) {
19
+ const named = isList(entity) ? scopeOf(entity) : undefined;
20
+ const all = named === undefined ? cut : cut === undefined ? named : merge(named, cut);
21
+ return all?.where;
22
+ }
@@ -1,8 +1,9 @@
1
1
  "use client";
2
2
  import { jsx as _jsx } from "react/jsx-runtime";
3
3
  import { matching } from "@sincpro/criteria";
4
- import { listRoute, NEW_PARAM } from "../../core/entity.js";
4
+ import { listRoute, NEW_PARAM, scopeOfRef, } from "../../core/entity.js";
5
5
  import { lookupOf } from "../../core/lookup.js";
6
+ import { ListScopeProvider } from "../../react/scope.js";
6
7
  import { useListing } from "../../react/useListing.js";
7
8
  import { EntityList } from "../list/EntityList.js";
8
9
  import { presentationOf } from "../list/presentation.js";
@@ -26,7 +27,7 @@ function InWorkspace({ api, children }) {
26
27
  open: (ref, to) => openIn(api, ref, to),
27
28
  targets,
28
29
  narrow: api.surface !== "page",
29
- choose: (entity, answer, query) => api.pick(entity.chooserRef(query), (ref) => ref.id === undefined || answer(ref.id), answering),
30
+ choose: (entity, answer, query, scope) => api.pick(entity.chooserRef(query, scope), (ref) => ref.id === undefined || answer(ref.id), answering),
30
31
  create: (entity, values, created) => api.pick(entity.newRef(values), () => created(), answering),
31
32
  };
32
33
  }, [api, targets]);
@@ -53,7 +54,11 @@ export function entityView(entity, options) {
53
54
  const One = loaded.record ?? options.record ?? recordOf(entity);
54
55
  return function EntityView(props) {
55
56
  const record = props.resource.id !== undefined || props.resource.params?.[NEW_PARAM] !== undefined;
56
- return (_jsx(InWorkspace, { api: props.api, children: record ? _jsx(One, { ...props }) : _jsx(List, { ...props }) }));
57
+ // A chooser opened by a picker offers only what the picker may choose: its cut travels in
58
+ // the reference, and the list — the application's own too — reads under it.
59
+ const cut = record ? undefined : scopeOfRef(props.resource);
60
+ const list = cut === undefined ? (_jsx(List, { ...props })) : (_jsx(ListScopeProvider, { value: { key: entity.key, where: cut }, children: _jsx(List, { ...props }) }));
61
+ return _jsx(InWorkspace, { api: props.api, children: record ? _jsx(One, { ...props }) : list });
57
62
  };
58
63
  }
59
64
  // Built once: a second open of the view must be the same component, or it would remount. A
@@ -22,8 +22,12 @@ import type { RecordReading } from "../../react/useRecord.js";
22
22
  */
23
23
  export declare function useRecordInWorkspace<T extends AnyRecord>(api: WorkspaceApi, record: RecordReading<T>): void;
24
24
  /**
25
- * «Browse everything» of an `EntityPicker` as the composer's chooser: the entity's own list
26
- * opens in a window and the row clicked there answers the field.
25
+ * «Browse everything» as the composer's chooser: the entity's own list opens in a window and
26
+ * the row clicked there answers the field.
27
+ *
28
+ * Context: an `EntityPicker` inside an `entityView` already does this by itself (its
29
+ * `RecordOpening`), carrying its cut. This is for a screen that wires a chooser by hand — a
30
+ * button of its own, another `pick` option — and it carries no cut.
27
31
  *
28
32
  * <EntityPicker entity={customers} onChange={set} onBrowseAll={chooserIn(api, customers, set)} />
29
33
  */
@@ -53,8 +53,12 @@ function newTitle(meta, locale) {
53
53
  return frameworkCopy().record.creating(nameOf(meta, locale) || "");
54
54
  }
55
55
  /**
56
- * «Browse everything» of an `EntityPicker` as the composer's chooser: the entity's own list
57
- * opens in a window and the row clicked there answers the field.
56
+ * «Browse everything» as the composer's chooser: the entity's own list opens in a window and
57
+ * the row clicked there answers the field.
58
+ *
59
+ * Context: an `EntityPicker` inside an `entityView` already does this by itself (its
60
+ * `RecordOpening`), carrying its cut. This is for a screen that wires a chooser by hand — a
61
+ * button of its own, another `pick` option — and it carries no cut.
58
62
  *
59
63
  * <EntityPicker entity={customers} onChange={set} onBrowseAll={chooserIn(api, customers, set)} />
60
64
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sincpro/web-framework",
3
- "version": "0.4.1",
3
+ "version": "0.4.2",
4
4
  "description": "The web client of sincpro_framework: entities, lists and records bound to the metadata the server publishes, drawn with @sincpro/web-ui and arranged with @sincpro/web-composer.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",