@sincpro/web-ui 2.7.0 → 2.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -316,7 +316,11 @@ const searchRecords: SearchRecords = ({ relation, path, text, keys, signal }) =>
316
316
  ? api.names(relation, keys, { signal }) // name what a filter read back carries
317
317
  : api.literalSearch(relation, text, { limit: 8, signal }); // what was typed
318
318
 
319
- <SearchProvider searchRecords={searchRecords} valueEditor={myValueEditor}>
319
+ <SearchProvider
320
+ searchRecords={searchRecords}
321
+ browseRecords={(browse) => openChooser(browse)} // your list in choosing mode, its own bar
322
+ valueEditor={myValueEditor}
323
+ >
320
324
  <App /> {/* every SearchBar, FilterBuilder and CriteriaBuilder inside */}
321
325
  </SearchProvider>;
322
326
  ```
@@ -326,13 +330,23 @@ const searchRecords: SearchRecords = ({ relation, path, text, keys, signal }) =>
326
330
  other side (`relationKey`, `id` by default) — the filter crosses it with `through`. An enum's
327
331
  words come from `translations.choices`.
328
332
 
333
+ A path is walked the same way: in «Cliente › País» the first option is «País (el registro)» —
334
+ the rule then asks for COUNTRIES, picked by name— above País's own fields, for when the
335
+ question is about a field («Código empieza con B»). «Buscar más…» opens your chooser: another
336
+ context, the relation's whole list with its own search bar (which unfolds relations too).
337
+
338
+ Who does what: web-ui draws and notifies; **web-framework** wires `searchRecords` to the
339
+ entity's literal search, `browseRecords` to the entity's list in choosing mode and `loadModel`
340
+ to the related meta — once, for every entity; composer decides where the chooser opens (a modal
341
+ over a page, beside a modal); the application only overrides what it wants.
342
+
329
343
  What can be extended, and how:
330
344
 
331
345
  | You want | Use |
332
346
  | ------------------------------------------------ | -------------------------------------------------------------------------------------------- |
333
347
  | The records of a relation, from your server | `searchRecords` (prop, or `SearchProvider` once) |
334
348
  | A record drawn your way in the dropdown | `SearchBar renderRecord` |
335
- | «Buscar más…» under the records: your chooser | `SearchBar onBrowseRecords(field, text)` + `withValue` |
349
+ | «Buscar más…» under the records: your chooser | `browseRecords` (prop or `SearchProvider`), bar and builder; answer with `choose` |
336
350
  | A field's value drawn your way in the builder | `valueEditor` (prop or `SearchProvider`): answer `undefined` to keep ours |
337
351
  | A list that opens filtered (defaults, a link) | `queryField` + `valuesCriteria` / `conditionCriteria` / `toggleNamed` |
338
352
  | One more value into a chip, by code | `withValue(criteria, field, record)` |
@@ -1,7 +1,7 @@
1
1
  import { type ValueEditor } from "./context.js";
2
2
  import type { BuiltFilter } from "./criteria.js";
3
3
  import { type ModelDefinition } from "./model.js";
4
- import type { SearchRecords } from "./records.js";
4
+ import type { BrowseRecords, SearchRecords } from "./records.js";
5
5
  export interface BuiltSort {
6
6
  field: string;
7
7
  descending?: boolean;
@@ -55,13 +55,16 @@ export interface BuiltCriteria {
55
55
  grouping?: BuiltGrouping;
56
56
  specification?: Record<string, Record<string, never>>;
57
57
  }
58
- export declare function CriteriaBuilder({ model, initial, focus, onApply, onCancel, searchRecords: ownSearchRecords, valueEditor: ownValueEditor, }: {
58
+ export declare function CriteriaBuilder({ model, initial, focus, onApply, onCancel, searchRecords: ownSearchRecords, browseRecords: ownBrowseRecords, valueEditor: ownValueEditor, }: {
59
59
  model: ModelDefinition;
60
60
  /** The criteria that was already set. Reopening has to continue where it was left. */
61
61
  initial?: BuiltCriteria;
62
62
  /** Searches the records of a relation: a rule can then be about a relation itself, its
63
63
  * records picked by name (see `records.ts`). Absent, the `SearchProvider`'s. */
64
64
  searchRecords?: SearchRecords;
65
+ /** «Buscar más…» under a relation's records: the application's chooser. Absent, the
66
+ * provider's. */
67
+ browseRecords?: BrowseRecords;
65
68
  /** The application's own value controls (see `ValueEditor`). Absent, the provider's. */
66
69
  valueEditor?: ValueEditor;
67
70
  /**
@@ -72,10 +72,11 @@ function nextGrain(grain) {
72
72
  const at = GRAINS.indexOf(grain ?? null);
73
73
  return GRAINS[(at + 1) % GRAINS.length] ?? null;
74
74
  }
75
- export function CriteriaBuilder({ model, initial, focus, onApply, onCancel, searchRecords: ownSearchRecords, valueEditor: ownValueEditor, }) {
75
+ export function CriteriaBuilder({ model, initial, focus, onApply, onCancel, searchRecords: ownSearchRecords, browseRecords: ownBrowseRecords, valueEditor: ownValueEditor, }) {
76
76
  const surface = useSurface();
77
77
  const settings = useSearchSettings({
78
78
  ...(ownSearchRecords === undefined ? {} : { searchRecords: ownSearchRecords }),
79
+ ...(ownBrowseRecords === undefined ? {} : { browseRecords: ownBrowseRecords }),
79
80
  ...(ownValueEditor === undefined ? {} : { valueEditor: ownValueEditor }),
80
81
  });
81
82
  /* A filter read back carries keys; with records searchable, the rules about records are
@@ -126,7 +126,7 @@ function Levels({ models, start, canChoose, canFollow, onChoose, }) {
126
126
  const offerSelf = relationField !== undefined &&
127
127
  relationName !== undefined &&
128
128
  canChoose(relationField, relationName, at.slice(0, -1));
129
- const rows = level.status !== "ready"
129
+ const listed = level.status !== "ready"
130
130
  ? []
131
131
  : Object.entries(level.model.fields)
132
132
  .map(([name, field]) => ({
@@ -136,12 +136,21 @@ function Levels({ models, start, canChoose, canFollow, onChoose, }) {
136
136
  choose: canChoose(field, name, at),
137
137
  follow: canFollow(field, name, at),
138
138
  }))
139
- .filter((row) => row.choose || row.follow)
140
- .filter((row) => {
141
- const q = fold(query.trim());
142
- return q === "" || fold(row.label).includes(q) || fold(row.name).includes(q);
143
- })
144
- .sort((a, b) => a.label.localeCompare(b.label, copy.locale));
139
+ .filter((row) => row.choose || row.follow);
140
+ /* The column that identifies a to-one relation —its foreign key, «País» next to «País ›»—
141
+ is the same question with two rows, and the bare one asks for a key nobody knows. While
142
+ the relation itself is listed, its column is not. */
143
+ const naming = new Set(listed
144
+ .filter((row) => isRelation(row.field) && row.field.many !== true)
145
+ .map((row) => row.field.identifiedBy)
146
+ .filter((one) => one !== null && one !== undefined));
147
+ const rows = listed
148
+ .filter((row) => !naming.has(row.name))
149
+ .filter((row) => {
150
+ const q = fold(query.trim());
151
+ return q === "" || fold(row.label).includes(q) || fold(row.name).includes(q);
152
+ })
153
+ .sort((a, b) => a.label.localeCompare(b.label, copy.locale));
145
154
  return (_jsxs("div", { onKeyDown: onKeyDown, className: "flex min-w-0 flex-col gap-2", children: [at.length === 0 ? null : (_jsxs("div", { className: "flex min-w-0 items-center gap-1", children: [_jsx(IconButton, { icon: ChevronLeft, label: copy.fieldPath.back, onClick: back }), _jsx("p", { className: "min-w-0 flex-1 truncate text-meta font-medium text-ink", children: here })] })), _jsx(SearchField, { value: query, onChange: setQuery, "aria-label": copy.fieldPath.search, placeholder: copy.fieldPath.search }), level.status === "loading" ? (_jsx(Skeleton, { rows: 4, label: copy.fieldPath.loading })) : level.status === "failed" ? (_jsx(Failed, { heading: copy.fieldPath.failed, sentence: copy.fieldPath.failedHint, detail: `${at.join(".") || "/"} — ${level.error}`, action: _jsx(Button, { role: "secondary", size: "sm", onClick: () => setAttempt((n) => n + 1), children: copy.attachments.retry }) })) : rows.length === 0 && !offerSelf ? (_jsx("p", { className: "px-2 py-3 text-meta text-muted", children: copy.fieldPath.empty })) : (_jsxs(ListBox, { "aria-label": at.length === 0 ? copy.fieldPath.search : here, className: "max-h-72 min-w-0 overflow-auto outline-0", onAction: (key) => {
146
155
  const name = String(key);
147
156
  if (name === SELF)
@@ -2,7 +2,7 @@ import { type ValueEditor } from "./context.js";
2
2
  import type { BuiltFilter, CriteriaJoin, RecordKey, RecordOption, ThroughMatch } from "./criteria.js";
3
3
  import { type ModelDefinition } from "./model.js";
4
4
  import { type LoadModel, type ModelCache } from "./paths.js";
5
- import { type RecordTarget, type SearchRecords } from "./records.js";
5
+ import { type BrowseRecords, type RecordTarget, type SearchRecords } from "./records.js";
6
6
  /** Whether this is one of the shapes the filter recognises — condition, or `all`/`any`/
7
7
  * `negate` group. A valid JSON that is none of these —`{}`, `{"foo": 1}`, a loose array—
8
8
  * is not a filter this component knows how to draw, and is treated as a shape error instead of
@@ -102,7 +102,10 @@ export declare function recordOps(target: RecordTarget): string[];
102
102
  * Only on the record's own fields: a relation of a related record needs its model, and a row
103
103
  * that stays a plain condition still filters the same.
104
104
  */
105
- export declare function liftRecords(node: TreeNode, model: ModelDefinition): TreeNode;
105
+ export declare function liftRecords(node: TreeNode, model: ModelDefinition,
106
+ /** The model at the end of a path of relations, when it already arrived: with it, a rule
107
+ * about records past a relation —«Cliente > País es Bolivia»— is recognised too. */
108
+ modelAt?: (path: readonly string[]) => ModelDefinition | undefined): TreeNode;
106
109
  /** The names of the records a tree has chosen, by relation and key: what says them in a
107
110
  * sentence (`describeFilter`) once the tree is applied. */
108
111
  export declare function namesOf(node: TreeNode): RecordNames;
@@ -159,7 +162,7 @@ export declare function ExpressionView({ node, model, depth, modelAt, at, }: {
159
162
  /** The path up to here (through the outer `through`s). */
160
163
  at?: readonly string[];
161
164
  }): import("react").JSX.Element;
162
- export declare function SelectionTree({ model, group, onChange, depth, focus, loadModel, models: shared, searchRecords: ownSearchRecords, valueEditor: ownValueEditor, }: {
165
+ export declare function SelectionTree({ model, group, onChange, depth, focus, loadModel, models: shared, searchRecords: ownSearchRecords, browseRecords: ownBrowseRecords, valueEditor: ownValueEditor, }: {
163
166
  model: ModelDefinition;
164
167
  group: TreeGroup;
165
168
  onChange: (next: TreeGroup) => void;
@@ -167,6 +170,9 @@ export declare function SelectionTree({ model, group, onChange, depth, focus, lo
167
170
  /** Searches the records of a relation: with it a rule can be about a relation ITSELF,
168
171
  * its records picked by name (see `records.ts`). Absent, the `SearchProvider`'s. */
169
172
  searchRecords?: SearchRecords;
173
+ /** «Buscar más…» under a relation's records: the application's chooser. Absent, the
174
+ * provider's. */
175
+ browseRecords?: BrowseRecords;
170
176
  /** The application's own value controls (see `ValueEditor`). Absent, the provider's. */
171
177
  valueEditor?: ValueEditor;
172
178
  /**
@@ -194,7 +200,7 @@ export declare function SelectionTree({ model, group, onChange, depth, focus, lo
194
200
  /** The model cache the rules share. The outer tree builds it. */
195
201
  models?: ModelCache;
196
202
  }): import("react").JSX.Element;
197
- export declare function FilterBuilder({ model, initial, onApply, onCancel, loadModel, models: shared, searchRecords: ownSearchRecords, valueEditor: ownValueEditor, }: {
203
+ export declare function FilterBuilder({ model, initial, onApply, onCancel, loadModel, models: shared, searchRecords: ownSearchRecords, browseRecords: ownBrowseRecords, valueEditor: ownValueEditor, }: {
198
204
  model: ModelDefinition;
199
205
  /** The model at the end of a path of relations. With this, a rule can ask about
200
206
  * a field of a related record: «alguna línea con algún impuesto con monto > 10».
@@ -212,6 +218,9 @@ export declare function FilterBuilder({ model, initial, onApply, onCancel, loadM
212
218
  onCancel?: () => void;
213
219
  /** Searches the records of a relation (see `records.ts`). Absent, the `SearchProvider`'s. */
214
220
  searchRecords?: SearchRecords;
221
+ /** «Buscar más…» under a relation's records: the application's chooser. Absent, the
222
+ * provider's. */
223
+ browseRecords?: BrowseRecords;
215
224
  /** The application's own value controls (see `ValueEditor`). Absent, the provider's. */
216
225
  valueEditor?: ValueEditor;
217
226
  }): import("react").JSX.Element;
@@ -372,25 +372,37 @@ function unnamed(keys) {
372
372
  * Only on the record's own fields: a relation of a related record needs its model, and a row
373
373
  * that stays a plain condition still filters the same.
374
374
  */
375
- export function liftRecords(node, model) {
375
+ export function liftRecords(node, model,
376
+ /** The model at the end of a path of relations, when it already arrived: with it, a rule
377
+ * about records past a relation —«Cliente > País es Bolivia»— is recognised too. */
378
+ modelAt) {
376
379
  if (node.kind === "group") {
377
- return { ...node, children: node.children.map((child) => liftRecords(child, model)) };
380
+ return {
381
+ ...node,
382
+ children: node.children.map((child) => liftRecords(child, model, modelAt)),
383
+ };
378
384
  }
385
+ if (node.target !== undefined)
386
+ return node;
379
387
  const hops = node.through ?? [];
388
+ const at = (path) => path.length === 0 ? model : modelAt?.(path.map((hop) => hop.field));
380
389
  const keys = () => node.values !== undefined
381
390
  ? node.values.map((one) => one.id)
382
391
  : typeof node.raw === "string" || typeof node.raw === "number"
383
392
  ? [node.raw]
384
393
  : [];
385
- if (hops.length === 0) {
386
- for (const name of Object.keys(model.fields)) {
387
- const target = recordTarget(model, name);
394
+ /* A to-one relation compared by its column, in the model the rule's field lives in. */
395
+ const here = at(hops);
396
+ if (here !== undefined) {
397
+ for (const name of Object.keys(here.fields)) {
398
+ const target = recordTarget(here, name);
388
399
  if (target === undefined || target.many || target.column !== node.field)
389
400
  continue;
390
401
  if (!recordOps(target).includes(node.operator))
391
402
  return node;
392
403
  return {
393
404
  kind: "condition",
405
+ ...(hops.length === 0 ? {} : { through: hops }),
394
406
  field: name,
395
407
  operator: node.operator,
396
408
  value: "",
@@ -398,20 +410,23 @@ export function liftRecords(node, model) {
398
410
  ...(WITHOUT_VALUE.has(node.operator) ? {} : { values: unnamed(keys()) }),
399
411
  };
400
412
  }
401
- return node;
402
413
  }
403
- const [hop] = hops;
404
- if (hops.length !== 1 || hop === undefined || hop.match === "all")
414
+ /* A to-many relation crossed to its key: the LAST hop is the relation. */
415
+ const last = hops.at(-1);
416
+ if (last === undefined || last.match === "all")
405
417
  return node;
406
- const target = recordTarget(model, hop.field);
418
+ const before = hops.slice(0, -1);
419
+ const owner = at(before);
420
+ const target = owner === undefined ? undefined : recordTarget(owner, last.field);
407
421
  if (target === undefined || !target.many || node.field !== target.key)
408
422
  return node;
409
423
  if (node.operator !== "in" && node.operator !== "=")
410
424
  return node;
411
425
  return {
412
426
  kind: "condition",
413
- field: hop.field,
414
- operator: hop.match === "none" ? "not in" : "in",
427
+ ...(before.length === 0 ? {} : { through: before }),
428
+ field: last.field,
429
+ operator: last.match === "none" ? "not in" : "in",
415
430
  value: "",
416
431
  target,
417
432
  values: unnamed(keys()),
@@ -461,10 +476,11 @@ export function useRecordNames(tree, searchRecords, apply) {
461
476
  return node.children.forEach(walk);
462
477
  if (node.target === undefined)
463
478
  return;
479
+ const path = [...(node.through ?? []).map((hop) => hop.field), node.target.name];
464
480
  for (const one of node.values ?? []) {
465
481
  if (one.name !== "")
466
482
  continue;
467
- const asked = missing.get(node.target.name) ?? { target: node.target, keys: [] };
483
+ const asked = missing.get(node.target.name) ?? { target: node.target, path, keys: [] };
468
484
  asked.keys.push(one.id);
469
485
  missing.set(node.target.name, asked);
470
486
  }
@@ -477,9 +493,9 @@ export function useRecordNames(tree, searchRecords, apply) {
477
493
  if (searchRecords === undefined || missing.size === 0)
478
494
  return;
479
495
  const controller = new AbortController();
480
- void Promise.all([...missing.values()].map(({ target, keys }) => searchRecords({
496
+ void Promise.all([...missing.values()].map(({ target, path, keys }) => searchRecords({
481
497
  relation: target.relation,
482
- path: [target.name],
498
+ path,
483
499
  text: "",
484
500
  keys,
485
501
  signal: controller.signal,
@@ -494,6 +510,24 @@ export function useRecordNames(tree, searchRecords, apply) {
494
510
  // eslint-disable-next-line react-hooks/exhaustive-deps
495
511
  }, [key]);
496
512
  }
513
+ /** The paths whose models a tree needs to recognise its rules about records past a relation:
514
+ * every prefix of the hops of a rule that is not one yet. */
515
+ function pathsToLift(node) {
516
+ const out = new Map();
517
+ const walk = (one) => {
518
+ if (one.kind === "group")
519
+ return one.children.forEach(walk);
520
+ if (one.target !== undefined)
521
+ return;
522
+ const fields = (one.through ?? []).map((hop) => hop.field);
523
+ for (let end = 1; end <= fields.length; end++) {
524
+ const path = fields.slice(0, end);
525
+ out.set(path.join("."), path);
526
+ }
527
+ };
528
+ walk(node);
529
+ return [...out.values()];
530
+ }
497
531
  function stringifyFilter(filter) {
498
532
  return filter === undefined ? "" : JSON.stringify(filter, null, 2);
499
533
  }
@@ -638,19 +672,16 @@ export function ExpressionView({ node, model, depth = 0, modelAt, at = [], }) {
638
672
  /* ---------------------------------------------------------------------- *
639
673
  * A GROUP, DRAWN — the piece that calls itself to nest.
640
674
  * ---------------------------------------------------------------------- */
641
- export function SelectionTree({ model, group, onChange, depth = 0, focus, loadModel, models: shared, searchRecords: ownSearchRecords, valueEditor: ownValueEditor, }) {
675
+ export function SelectionTree({ model, group, onChange, depth = 0, focus, loadModel, models: shared, searchRecords: ownSearchRecords, browseRecords: ownBrowseRecords, valueEditor: ownValueEditor, }) {
642
676
  const names = filterableNames(model);
643
677
  const copy = useUiCopy();
644
678
  const surface = useSurface();
645
679
  const models = useModelCache(model, loadModel, shared);
646
- const { searchRecords, valueEditor } = useSearchSettings({
680
+ const extend = useSearchSettings({
647
681
  ...(ownSearchRecords === undefined ? {} : { searchRecords: ownSearchRecords }),
682
+ ...(ownBrowseRecords === undefined ? {} : { browseRecords: ownBrowseRecords }),
648
683
  ...(ownValueEditor === undefined ? {} : { valueEditor: ownValueEditor }),
649
684
  });
650
- const extend = {
651
- ...(searchRecords === undefined ? {} : { searchRecords }),
652
- ...(valueEditor === undefined ? {} : { valueEditor }),
653
- };
654
685
  const box = surface === "chrome"
655
686
  ? "border-chrome-ink/20 bg-chrome text-chrome-ink"
656
687
  : "border-ink/15 bg-surface text-ink";
@@ -701,7 +732,7 @@ function bare(child) {
701
732
  ...(child.target === undefined ? {} : { target: child.target }),
702
733
  };
703
734
  }
704
- function ConditionRow({ model, models, child, box, focused, onChange, actions, searchRecords, valueEditor, }) {
735
+ function ConditionRow({ model, models, child, box, focused, onChange, actions, searchRecords, browseRecords, valueEditor, }) {
705
736
  const copy = useUiCopy();
706
737
  const hops = child.through ?? [];
707
738
  const path = child.field === "" ? [] : [...hops.map((hop) => hop.field), child.field];
@@ -787,13 +818,14 @@ function ConditionRow({ model, models, child, box, focused, onChange, actions, s
787
818
  /* The application's control first, for the fields it draws its own way; the builder's
788
819
  for the rest. */
789
820
  (valueEditor?.(editor) ??
790
- (WITH_RANGE.has(child.operator) ? (_jsxs("span", { className: "flex min-w-0 flex-1 basis-40 items-center gap-1", children: [_jsx("input", { type: inputType(type), value: child.value, onChange: (event) => onChange({ ...bare(child), value: event.target.value }), placeholder: copy.builder.from, className: `min-w-0 flex-1 rounded-control border px-2 py-1 text-meta ${box}` }), _jsx("span", { className: "shrink-0 text-micro text-muted", children: copy.search.and }), _jsx("input", { type: inputType(type), value: child.upper ?? "", onChange: (event) => onChange({ ...bare(child), upper: event.target.value }), placeholder: copy.builder.to, className: `min-w-0 flex-1 rounded-control border px-2 py-1 text-meta ${box}` })] })) : (_jsx(RuleValue, { props: editor, ...(target === undefined ? {} : { target }), ...(searchRecords === undefined ? {} : { searchRecords }), box: box, inputType: inputType(type) }))))), actions] }));
821
+ (WITH_RANGE.has(child.operator) ? (_jsxs("span", { className: "flex min-w-0 flex-1 basis-40 items-center gap-1", children: [_jsx("input", { type: inputType(type), value: child.value, onChange: (event) => onChange({ ...bare(child), value: event.target.value }), placeholder: copy.builder.from, className: `min-w-0 flex-1 rounded-control border px-2 py-1 text-meta ${box}` }), _jsx("span", { className: "shrink-0 text-micro text-muted", children: copy.search.and }), _jsx("input", { type: inputType(type), value: child.upper ?? "", onChange: (event) => onChange({ ...bare(child), upper: event.target.value }), placeholder: copy.builder.to, className: `min-w-0 flex-1 rounded-control border px-2 py-1 text-meta ${box}` })] })) : (_jsx(RuleValue, { props: editor, ...(target === undefined ? {} : { target }), ...(searchRecords === undefined ? {} : { searchRecords }), ...(browseRecords === undefined ? {} : { browseRecords }), relationLabel: steps?.at(-1)?.label ?? child.field, box: box, inputType: inputType(type) }))))), actions] }));
791
822
  }
792
- export function FilterBuilder({ model, initial, onApply, onCancel, loadModel, models: shared, searchRecords: ownSearchRecords, valueEditor: ownValueEditor, }) {
823
+ export function FilterBuilder({ model, initial, onApply, onCancel, loadModel, models: shared, searchRecords: ownSearchRecords, browseRecords: ownBrowseRecords, valueEditor: ownValueEditor, }) {
793
824
  const names = filterableNames(model);
794
825
  const models = useModelCache(model, loadModel, shared);
795
826
  const settings = useSearchSettings({
796
827
  ...(ownSearchRecords === undefined ? {} : { searchRecords: ownSearchRecords }),
828
+ ...(ownBrowseRecords === undefined ? {} : { browseRecords: ownBrowseRecords }),
797
829
  ...(ownValueEditor === undefined ? {} : { valueEditor: ownValueEditor }),
798
830
  });
799
831
  /* A filter read back carries keys; with records searchable, the rules about records are
@@ -815,6 +847,23 @@ export function FilterBuilder({ model, initial, onApply, onCancel, loadModel, mo
815
847
  const [rawText, setRawText] = useState(() => stringifyFilter(initial ?? treeToFilter(tree)));
816
848
  const [rawError, setRawError] = useState(null);
817
849
  useRecordNames(tree, settings.searchRecords, (named) => setTree((current) => named(current)));
850
+ /* A rule past a relation —«Cliente > País es Bolivia»— is recognised once the models along
851
+ its path arrive: they are asked here, and the tree read again with them. */
852
+ const hopPaths = pathsToLift(tree);
853
+ useEffect(() => {
854
+ if (settings.searchRecords === undefined || !models.canLoad || hopPaths.length === 0)
855
+ return;
856
+ let alive = true;
857
+ void Promise.all(hopPaths.map((path) => models.get(path).catch(() => undefined))).then(() => {
858
+ if (alive)
859
+ setTree((current) => liftRecords(current, model, models.peek));
860
+ });
861
+ return () => {
862
+ alive = false;
863
+ };
864
+ // Asked again only when the paths to look at change.
865
+ // eslint-disable-next-line react-hooks/exhaustive-deps
866
+ }, [hopPaths.map((path) => path.join(".")).join("|")]);
818
867
  /* Touching the tree rewrites the JSON so it shows exactly what the tree now says,
819
868
  and drops any read-only view that may have been left. */
820
869
  function updateTree(next) {
@@ -1,16 +1,20 @@
1
1
  import type { ValueEditorProps } from "./context.js";
2
- import type { RecordTarget, SearchRecords } from "./records.js";
2
+ import type { BrowseRecords, RecordTarget, SearchRecords } from "./records.js";
3
3
  /** The comparisons that take several values. */
4
4
  export declare function takesMany(operator: string): boolean;
5
5
  /**
6
6
  * The builder's own value control for a rule — what is drawn when the application's
7
7
  * `valueEditor` does not answer for the field.
8
8
  */
9
- export declare function RuleValue({ props, target, searchRecords, box, inputType, }: {
9
+ export declare function RuleValue({ props, target, searchRecords, browseRecords, relationLabel, box, inputType, }: {
10
10
  props: ValueEditorProps;
11
11
  /** The rule asks about records of a relation. */
12
12
  target?: RecordTarget;
13
13
  searchRecords?: SearchRecords;
14
+ /** «Buscar más…» under the records: the application's chooser. */
15
+ browseRecords?: BrowseRecords;
16
+ /** How the relation reads, for the chooser's title: «País». */
17
+ relationLabel?: string;
14
18
  /** The look of the row's other controls, for the native ones. */
15
19
  box: string;
16
20
  inputType: string;
@@ -64,8 +64,26 @@ function useRecordOptions(search, target, path) {
64
64
  return { ...found, search: (next) => setText(next) };
65
65
  }
66
66
  /** A relation's records: one, picked by name, or several as tags. */
67
- function RecordValue({ props, target, searchRecords, }) {
67
+ function RecordValue({ props, target, searchRecords, browseRecords, relationLabel, }) {
68
68
  const { values, onValues, path, operator, label } = props;
69
+ /* «Buscar más…»: the application's chooser over the relation —its own list, its own bar—,
70
+ on what was typed. Several add to what is there; one replaces it. */
71
+ const browse = browseRecords === undefined
72
+ ? undefined
73
+ : (text, many) => browseRecords({
74
+ relation: target.relation,
75
+ path,
76
+ label: relationLabel,
77
+ text,
78
+ many,
79
+ chosen: values,
80
+ choose: (records) => onValues(many
81
+ ? [
82
+ ...values,
83
+ ...records.filter((one) => !values.some((each) => String(each.id) === String(one.id))),
84
+ ]
85
+ : records.slice(0, 1)),
86
+ });
69
87
  const found = useRecordOptions(searchRecords, target, path);
70
88
  /* A record read back has no name until the builder asks for it (`useRecordNames`). */
71
89
  const shown = (one) => (one.name === "" ? `#${one.id}` : one.name);
@@ -77,7 +95,9 @@ function RecordValue({ props, target, searchRecords, }) {
77
95
  value: String(one.id),
78
96
  label: shown(one),
79
97
  ...(one.meta === undefined ? {} : { meta: one.meta }),
80
- })), onSearch: found.search, onChange: (next) => onValues(next
98
+ })), onSearch: found.search, ...(browse === undefined
99
+ ? {}
100
+ : { onBrowseAll: (text) => browse(text, true) }), onChange: (next) => onValues(next
81
101
  .map((id) => known.get(id))
82
102
  .filter((one) => one !== undefined)) }) }));
83
103
  }
@@ -88,7 +108,9 @@ function RecordValue({ props, target, searchRecords, }) {
88
108
  ...(one.meta === undefined ? {} : { meta: one.meta }),
89
109
  })), loading: found.loading && found.options.length === 0, ...(chosen === undefined
90
110
  ? {}
91
- : { value: String(chosen.id), valueLabel: shown(chosen) }), onSearch: found.search, onChange: (id) => {
111
+ : { value: String(chosen.id), valueLabel: shown(chosen) }), onSearch: found.search, ...(browse === undefined
112
+ ? {}
113
+ : { onBrowseAll: (text) => browse(text, false) }), onChange: (id) => {
92
114
  const one = found.options.find((each) => String(each.id) === id);
93
115
  if (one !== undefined)
94
116
  onValues([one]);
@@ -98,11 +120,11 @@ function RecordValue({ props, target, searchRecords, }) {
98
120
  * The builder's own value control for a rule — what is drawn when the application's
99
121
  * `valueEditor` does not answer for the field.
100
122
  */
101
- export function RuleValue({ props, target, searchRecords, box, inputType, }) {
123
+ export function RuleValue({ props, target, searchRecords, browseRecords, relationLabel, box, inputType, }) {
102
124
  const copy = useUiCopy();
103
125
  const { field, name, model, operator, value, onValue, values, onValues, label } = props;
104
126
  if (target !== undefined && searchRecords !== undefined) {
105
- return _jsx(RecordValue, { props: props, target: target, searchRecords: searchRecords });
127
+ return (_jsx(RecordValue, { props: props, target: target, searchRecords: searchRecords, ...(browseRecords === undefined ? {} : { browseRecords }), relationLabel: relationLabel ?? props.name }));
106
128
  }
107
129
  const choices = (field.choices ?? []).map((one) => String(one));
108
130
  const word = (one) => model === undefined ? one : choiceLabel(model, name, one, copy.locale);
@@ -1,7 +1,7 @@
1
1
  import { type BuiltCondition, type BuiltFilter, type CriteriaJoin, type CriteriaPath, type RecordOption, type SearchCriteria } from "./criteria.js";
2
2
  import type { ModelDefinition } from "./model.js";
3
3
  import { type QueryField } from "./query.js";
4
- import type { SearchRecords } from "./records.js";
4
+ import type { BrowseRecords, SearchRecords } from "./records.js";
5
5
  import type { Surface } from "../../foundations/types.js";
6
6
  import type { MenuGroup } from "../../primitives/menu/Menu.js";
7
7
  import { type ReactNode } from "react";
@@ -93,10 +93,10 @@ export type SearchBarProps = {
93
93
  * Absent, the one of the nearest `SearchProvider`.
94
94
  */
95
95
  searchRecords?: SearchRecords;
96
- /** «Buscar más…» under an unfolded relation's records: the chooser with the whole list
97
- * (`api.pick` + `List onChoose`), on what was typed. What is chosen there, the application
98
- * puts with `withValue(criteria, field, record)`. */
99
- onBrowseRecords?: (field: QueryField, text: string) => void;
96
+ /** «Buscar más…» under a relation's records: the application's chooser with the whole list
97
+ * —`List onChoose` with its own search bar—, on what was typed. What it answers lands in the
98
+ * relation's chip. Absent, the one of the nearest `SearchProvider`. */
99
+ browseRecords?: BrowseRecords;
100
100
  /** How a record found reads in the dropdown — a face, a NIT, a balance —, for one that does
101
101
  * not fit «name + meta». The row around it stays the bar's: keys, focus, choosing. */
102
102
  renderRecord?: (record: RecordOption, state: {
@@ -111,4 +111,4 @@ export type SearchBarProps = {
111
111
  /** By default it inherits it from the surface that wraps it. */
112
112
  surface?: Surface;
113
113
  };
114
- export declare function SearchBar({ facets, model, criteria, onCriteriaChange, placeholder, filters, grouping, onOpenGroup, favorites, onFilterSelect, onFavoriteSelect, onOpenBuilder, literal, searchRecords: ownSearchRecords, onBrowseRecords, renderRecord, trailing, collapseAfter, surface, }: SearchBarProps): import("react").JSX.Element;
114
+ export declare function SearchBar({ facets, model, criteria, onCriteriaChange, placeholder, filters, grouping, onOpenGroup, favorites, onFilterSelect, onFavoriteSelect, onOpenBuilder, literal, searchRecords: ownSearchRecords, browseRecords: ownBrowseRecords, renderRecord, trailing, collapseAfter, surface, }: SearchBarProps): import("react").JSX.Element;
@@ -101,11 +101,14 @@ function Group({ group, first, checks, onSelect, }) {
101
101
  ? "flex flex-col gap-0.5 pl-(--spacing-indent)"
102
102
  : "flex flex-col gap-0.5", children: options }))] }));
103
103
  }
104
- export function SearchBar({ facets, model, criteria, onCriteriaChange, placeholder, filters, grouping, onOpenGroup, favorites, onFilterSelect, onFavoriteSelect, onOpenBuilder, literal, searchRecords: ownSearchRecords, onBrowseRecords, renderRecord, trailing, collapseAfter, surface, }) {
104
+ export function SearchBar({ facets, model, criteria, onCriteriaChange, placeholder, filters, grouping, onOpenGroup, favorites, onFilterSelect, onFavoriteSelect, onOpenBuilder, literal, searchRecords: ownSearchRecords, browseRecords: ownBrowseRecords, renderRecord, trailing, collapseAfter, surface, }) {
105
105
  const copy = useUiCopy();
106
106
  const sup = useSurface(surface);
107
107
  /* Its own, or the application's (`SearchProvider`): wired once for every bar. */
108
- const { searchRecords } = useSearchSettings(ownSearchRecords === undefined ? {} : { searchRecords: ownSearchRecords });
108
+ const { searchRecords, browseRecords } = useSearchSettings({
109
+ ...(ownSearchRecords === undefined ? {} : { searchRecords: ownSearchRecords }),
110
+ ...(ownBrowseRecords === undefined ? {} : { browseRecords: ownBrowseRecords }),
111
+ });
109
112
  const [text, setText] = useState("");
110
113
  const [panel, setPanel] = useState(false);
111
114
  /* Which edge of the field the panel hangs from. It is wider than the field when the
@@ -288,7 +291,7 @@ export function SearchBar({ facets, model, criteria, onCriteriaChange, placehold
288
291
  : undefined;
289
292
  if (status !== undefined)
290
293
  rows.push({ kind: "status", id: `s:${which}`, text: status, ...nested });
291
- if (onBrowseRecords !== undefined) {
294
+ if (browseRecords !== undefined) {
292
295
  rows.push({ kind: "more", id: `m:${which}`, field, text: query, ...nested });
293
296
  }
294
297
  return rows;
@@ -476,6 +479,40 @@ export function SearchBar({ facets, model, criteria, onCriteriaChange, placehold
476
479
  setUnfolded(null);
477
480
  input.current?.focus();
478
481
  }
482
+ /** Several values of a field at once —what a chooser answers—, into the same chip. */
483
+ function putValues(field, options) {
484
+ if (options.length === 0)
485
+ return;
486
+ const node = openGroup === null ? undefined : at(criteria, openGroup);
487
+ const into = (list) => options.reduce((all, one) => withValue(all, field, one), [...list]);
488
+ if (openGroup !== null && node?.kind === "join") {
489
+ onCriteriaChange(replaceAt(criteria, openGroup, { ...node, of: into(node.of) }));
490
+ }
491
+ else {
492
+ onCriteriaChange(into(criteria));
493
+ }
494
+ setText("");
495
+ setStep({});
496
+ setUnfolded(null);
497
+ input.current?.focus();
498
+ }
499
+ /** «Buscar más…»: the application's chooser over the relation, on what was typed. What is
500
+ * already in the relation's chip is said, so a chooser of many leaves it out. */
501
+ function browse(field, query) {
502
+ const relation = field.relation;
503
+ if (browseRecords === undefined || relation === undefined)
504
+ return;
505
+ const held = criteria.find((one) => one.id === `v:${fieldKey(field)}`);
506
+ browseRecords({
507
+ relation: relation.relation,
508
+ path: [relation.name],
509
+ label: field.label,
510
+ text: query,
511
+ many: true,
512
+ chosen: held?.kind === "filter" ? (held.values ?? []) : [],
513
+ choose: (records) => putValues(field, records),
514
+ });
515
+ }
479
516
  /** What was chosen in the dropdown, depending on what kind it is. */
480
517
  function pick(suggestion) {
481
518
  if (suggestion.kind === "field") {
@@ -537,7 +574,7 @@ export function SearchBar({ facets, model, criteria, onCriteriaChange, placehold
537
574
  if (item.kind === "suggestion")
538
575
  pick(item.suggestion);
539
576
  else if (item.kind === "more")
540
- onBrowseRecords?.(item.field, item.text);
577
+ browse(item.field, item.text);
541
578
  else if (item.kind === "advanced") {
542
579
  /* What was typed was not a question the bar could write — that is why the builder was
543
580
  chosen —: it goes, and the dropdown with it, instead of staying open behind the
@@ -1,5 +1,5 @@
1
1
  import type { FieldDefinition, ModelDefinition } from "./model.js";
2
- import type { RecordOption, SearchRecords } from "./records.js";
2
+ import type { BrowseRecords, RecordOption, SearchRecords } from "./records.js";
3
3
  import { type ReactNode } from "react";
4
4
  /** What a value control of the builder is handed: the field the rule compares, the
5
5
  * comparison, and the value — written (`value`) or chosen (`values`, with their names). */
@@ -35,10 +35,14 @@ export type ValueEditor = (props: ValueEditorProps) => ReactNode | undefined;
35
35
  export interface SearchSettings {
36
36
  /** The application's search over the records of a relation (see `records.ts`). */
37
37
  searchRecords?: SearchRecords;
38
+ /** The application's «Buscar más…»: the whole list of a relation's records, in its chooser
39
+ * —another context, with its own search bar—. Offered under the records found, in the bar
40
+ * and in the builder. */
41
+ browseRecords?: BrowseRecords;
38
42
  /** The application's own value controls in the builder. */
39
43
  valueEditor?: ValueEditor;
40
44
  }
41
- export declare function SearchProvider({ searchRecords, valueEditor, children, }: SearchSettings & {
45
+ export declare function SearchProvider({ searchRecords, browseRecords, valueEditor, children, }: SearchSettings & {
42
46
  children: ReactNode;
43
47
  }): import("react").JSX.Element;
44
48
  /** What is in force for a piece: its own props first, then the provider's. */
@@ -2,24 +2,27 @@
2
2
  import { jsx as _jsx } from "react/jsx-runtime";
3
3
  import { createContext, useContext, useMemo } from "react";
4
4
  const SearchContext = createContext({});
5
- export function SearchProvider({ searchRecords, valueEditor, children, }) {
5
+ export function SearchProvider({ searchRecords, browseRecords, valueEditor, children, }) {
6
6
  /* A provider nested inside another keeps what it does not say: a screen can swap the
7
7
  value controls and still search records the way the app does. */
8
8
  const outer = useContext(SearchContext);
9
9
  const value = useMemo(() => ({
10
10
  ...outer,
11
11
  ...(searchRecords === undefined ? {} : { searchRecords }),
12
+ ...(browseRecords === undefined ? {} : { browseRecords }),
12
13
  ...(valueEditor === undefined ? {} : { valueEditor }),
13
- }), [outer, searchRecords, valueEditor]);
14
+ }), [outer, searchRecords, browseRecords, valueEditor]);
14
15
  return _jsx(SearchContext.Provider, { value: value, children: children });
15
16
  }
16
17
  /** What is in force for a piece: its own props first, then the provider's. */
17
18
  export function useSearchSettings(own = {}) {
18
19
  const inherited = useContext(SearchContext);
19
20
  const searchRecords = own.searchRecords ?? inherited.searchRecords;
21
+ const browseRecords = own.browseRecords ?? inherited.browseRecords;
20
22
  const valueEditor = own.valueEditor ?? inherited.valueEditor;
21
23
  return {
22
24
  ...(searchRecords === undefined ? {} : { searchRecords }),
25
+ ...(browseRecords === undefined ? {} : { browseRecords }),
23
26
  ...(valueEditor === undefined ? {} : { valueEditor }),
24
27
  };
25
28
  }
@@ -10,6 +10,6 @@ export { CriteriaChips, type CriteriaChipsProps, } from "./CriteriaChips.js";
10
10
  export { choiceLabel, type FieldDefinition, fieldLabel, filterableNames, isFilterable, isNumericType, type ModelDefinition, type ModelTranslations, } from "./model.js";
11
11
  export { answers, choiceValues, conditionCriteria, defaultOp, describeCondition, fieldKey, globToLike, opLabel, type QueryDraft, type QueryField, queryField, queryFields, type QueryKind, type QuerySuggestion, readTyped, sayValues, suggest, type TypedValue, valueFor, valueLabel, valuesCriteria, type ValueShape, valuesSelection, withoutValue, withValue, } from "./query.js";
12
12
  export { SearchProvider, type SearchSettings, useSearchSettings, type ValueEditor, type ValueEditorProps, } from "./context.js";
13
- export { type RecordSearch, recordsFilter, recordsOf, type RecordTarget, recordTarget, sameKey, type SearchRecords, } from "./records.js";
13
+ export { type BrowseRecords, type RecordBrowse, type RecordSearch, recordsFilter, recordsOf, type RecordTarget, recordTarget, sameKey, type SearchRecords, } from "./records.js";
14
14
  export { RuleValue, takesMany } from "./RuleValue.js";
15
15
  export { type DatePeriod, datePeriodGroup, datePeriodOptions, type DateRange, periodId, readPeriodId, recentMonths, recentYears, resolvePeriods, } from "./datePeriods.js";
@@ -18,6 +18,29 @@ export interface RecordSearch {
18
18
  /** The application's search over the records of a relation. A few are enough — a dropdown is
19
19
  * not a page; the rest are reached by typing more. */
20
20
  export type SearchRecords = (search: RecordSearch) => Promise<readonly RecordOption[]>;
21
+ /**
22
+ * What «Buscar más…» is asked: the whole list of a relation's records, to choose from where the
23
+ * dropdown's few are not enough. The application opens its chooser —a `List onChoose` with its
24
+ * OWN search bar, in a modal or beside—, and answers with `choose`.
25
+ */
26
+ export interface RecordBrowse {
27
+ /** The aggregate on the other side — WHICH records: «Country». */
28
+ relation: string;
29
+ /** The relational field, from the root record: `["customer", "country"]`. */
30
+ path: readonly string[];
31
+ /** How the relation reads: «País». The chooser's title. */
32
+ label: string;
33
+ /** What was typed: the chooser opens on the same search. */
34
+ text: string;
35
+ /** The place takes several (a chip, «está en») or one («es»): a chooser of many ticks. */
36
+ many: boolean;
37
+ /** What is already chosen there: a chooser of many leaves it out. */
38
+ chosen: readonly RecordOption[];
39
+ /** The answer: the records chosen. */
40
+ choose: (records: readonly RecordOption[]) => void;
41
+ }
42
+ /** The application's «Buscar más…» over a relation. */
43
+ export type BrowseRecords = (browse: RecordBrowse) => void;
21
44
  /** How a relation is compared once records of it are chosen. */
22
45
  export interface RecordTarget {
23
46
  /** The relational field: «customer_id», «tags». */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sincpro/web-ui",
3
- "version": "2.7.0",
3
+ "version": "2.8.0",
4
4
  "description": "An enterprise web design system for business software — ERPs, back offices, management tools — in React and Tailwind: tokens, primitives, components and the two views every management screen is made of.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",