@sincpro/web-ui 2.6.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.
@@ -1,16 +1,19 @@
1
1
  "use client";
2
2
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
+ import { useSearchSettings, } from "./context.js";
3
4
  import { FieldPath, useFieldPathSteps, useModelCache, } from "./FieldPath.js";
4
5
  import { JoinWord } from "./JoinWord.js";
5
6
  import { LazyJsonEditor } from "./LazyJsonEditor.js";
6
7
  import { fieldLabel, filterableNames, isFilterable, } from "./model.js";
7
- import { isToMany, } from "./paths.js";
8
+ import { isRelation, isToMany, } from "./paths.js";
8
9
  import { opLabel, sayCondition } from "./query.js";
10
+ import { recordsFilter, recordsOf, recordTarget, } from "./records.js";
11
+ import { RuleValue } from "./RuleValue.js";
9
12
  import { currentCopy, fillCopy, useUiCopy } from "../../foundations/copy.js";
10
13
  import { useSurface } from "../../foundations/surface.js";
11
14
  import { Button } from "../../primitives/button/index.js";
12
15
  import { FolderTree, Plus, Trash2 } from "lucide-react";
13
- import { useState } from "react";
16
+ import { useEffect, useState } from "react";
14
17
  /* ====================================================================== *
15
18
  * A FILTER SOMEBODY BUILDS, FROM WHAT THE MODEL SAYS IT ACCEPTS.
16
19
  *
@@ -43,7 +46,7 @@ import { useState } from "react";
43
46
  bar uses when building the question. Two tables means the same comparison is called two ways
44
47
  on the same screen. */
45
48
  /** Which operators take no value: asking whether something is empty needs nothing written. */
46
- const WITHOUT_VALUE = new Set(["is null"]);
49
+ const WITHOUT_VALUE = new Set(["is null", "is not null"]);
47
50
  /** Which operators compare against TWO values. «Entre el 1 y el 31» is the question everybody
48
51
  * asks about dates, and writing it as two loose rules is the way to
49
52
  * get one of the two ends wrong. */
@@ -172,28 +175,51 @@ function wrapThrough(hops, leaf) {
172
175
  return hops.reduceRight((inner, hop) => crossing(hop.field, hop.match, inner), leaf);
173
176
  }
174
177
  function conditionToFilter(node) {
175
- {
176
- if (node.field === "")
177
- return undefined;
178
+ if (node.field === "")
179
+ return undefined;
180
+ /* A rule about records: by key, the way the relation is compared — directly by its column
181
+ (a many2one) or crossing it (a to-many). «Está vacío» asks the column. */
182
+ if (node.target !== undefined) {
178
183
  if (WITHOUT_VALUE.has(node.operator)) {
179
- return { field: node.field, operator: node.operator, value: true };
180
- }
181
- if (WITH_RANGE.has(node.operator)) {
182
- /* A half-written range is not half a range: while one end is missing, the rule does not
183
- travel. */
184
- if (node.value === "" || (node.upper ?? "") === "")
185
- return undefined;
186
- return { field: node.field, operator: node.operator, value: [node.value, node.upper] };
184
+ return node.target.column === undefined
185
+ ? undefined
186
+ : { field: node.target.column, operator: node.operator, value: true };
187
187
  }
188
- /* **A rule with no value does not filter.** It used to travel with `value: ""`, and that is not «not
189
- written anything yet»: against an `=` it is «the field is the empty string», which empties the list
190
- while somebody is still typing, and against a `like` it is «contains nothing», which leaves it
191
- the same. To ask for what is empty there is the «está vacío» operator, which the
192
- model publishes on the fields that admit it — explicit, and not by omission. */
193
- if (node.value === "")
188
+ const keys = (node.values ?? []).map((one) => one.id);
189
+ if (keys.length === 0)
194
190
  return undefined;
195
- return { field: node.field, operator: node.operator, value: node.value };
191
+ return recordsFilter(node.target, keys, node.operator === "!=" || node.operator === "not in");
192
+ }
193
+ if (WITHOUT_VALUE.has(node.operator)) {
194
+ return { field: node.field, operator: node.operator, value: true };
195
+ }
196
+ if (WITH_RANGE.has(node.operator)) {
197
+ /* A half-written range is not half a range: while one end is missing, the rule does not
198
+ travel. */
199
+ if (node.value === "" || (node.upper ?? "") === "")
200
+ return undefined;
201
+ return { field: node.field, operator: node.operator, value: [node.value, node.upper] };
202
+ }
203
+ /* Chosen values travel as what they are —a list for «está en», the one for «es»—, by key. */
204
+ if (node.values !== undefined && node.values.length > 0) {
205
+ const keys = node.values.map((one) => one.id);
206
+ return {
207
+ field: node.field,
208
+ operator: node.operator,
209
+ value: node.operator === "in" || node.operator === "not in" ? keys : keys[0],
210
+ };
196
211
  }
212
+ if (node.raw !== undefined) {
213
+ return { field: node.field, operator: node.operator, value: node.raw };
214
+ }
215
+ /* **A rule with no value does not filter.** It used to travel with `value: ""`, and that is not «not
216
+ written anything yet»: against an `=` it is «the field is the empty string», which empties the list
217
+ while somebody is still typing, and against a `like` it is «contains nothing», which leaves it
218
+ the same. To ask for what is empty there is the «está vacío» operator, which the
219
+ model publishes on the fields that admit it — explicit, and not by omission. */
220
+ if (node.value === "")
221
+ return undefined;
222
+ return { field: node.field, operator: node.operator, value: node.value };
197
223
  }
198
224
  function groupToFilter(node) {
199
225
  const kept = node.children
@@ -211,8 +237,9 @@ function groupToFilter(node) {
211
237
  return kept[0];
212
238
  return node.join === "any" ? { any: kept } : { all: kept };
213
239
  }
214
- /** A condition back to an editable row: the value goes back to text, which is the only thing
215
- * an `<input>` knows how to show. A list —an `in`'s value— is written separated by commas. */
240
+ /** A condition back to an editable row: the value goes back to text, which is what an
241
+ * `<input>` shows — and stays as it came (`raw`), so the rule goes back out the same. A list
242
+ * —an `in`'s value— is written separated by commas, and kept as chosen values. */
216
243
  function conditionToTree(condition) {
217
244
  if (WITH_RANGE.has(condition.operator) && Array.isArray(condition.value)) {
218
245
  const [from, to] = condition.value;
@@ -224,15 +251,25 @@ function conditionToTree(condition) {
224
251
  upper: String(to ?? ""),
225
252
  };
226
253
  }
254
+ if (WITHOUT_VALUE.has(condition.operator)) {
255
+ return {
256
+ kind: "condition",
257
+ field: condition.field,
258
+ operator: condition.operator,
259
+ value: "",
260
+ };
261
+ }
262
+ const value = condition.value;
227
263
  return {
228
264
  kind: "condition",
229
265
  field: condition.field,
230
266
  operator: condition.operator,
231
- value: WITHOUT_VALUE.has(condition.operator)
232
- ? ""
233
- : Array.isArray(condition.value)
234
- ? condition.value.join(",")
235
- : String(condition.value ?? ""),
267
+ value: Array.isArray(value) ? value.join(",") : String(value ?? ""),
268
+ ...(Array.isArray(value)
269
+ ? { values: value.map((id) => ({ id: id, name: "" })) }
270
+ : value === undefined
271
+ ? {}
272
+ : { raw: value }),
236
273
  };
237
274
  }
238
275
  /** The filter read back into a tree.
@@ -306,6 +343,191 @@ function readChildren(raws) {
306
343
  }
307
344
  return children;
308
345
  }
346
+ /** The operators a rule about records offers: one record or several, in or out — and, through
347
+ * a column that admits it, «está vacío». A to-many relation is asked by some of its records
348
+ * or none of them. */
349
+ export function recordOps(target) {
350
+ if (target.many)
351
+ return ["in", "not in"];
352
+ const empty = ["is null", "is not null"].filter((op) => target.column !== undefined && target.ops.includes(op));
353
+ return ["=", "!=", "in", "not in", ...empty];
354
+ }
355
+ /** The keys of a list read back, as chosen values not named yet. */
356
+ function unnamed(keys) {
357
+ return keys.map((id) => ({ id, name: "" }));
358
+ }
359
+ /**
360
+ * The rules about RECORDS of a relation, recognised again in a tree read back.
361
+ *
362
+ * A filter carries keys, never which relation they were chosen from: `customer_id in [7, 9]`
363
+ * is, for the tree, a column compared to two numbers. The model says that `customer_id` is
364
+ * how «Cliente» is compared, so the row is drawn as «Cliente es alguno de [Andrés Pérez,
365
+ * Andrés Gutiérrez]» — the names asked of `searchRecords` by key. The same for a to-many
366
+ * crossed to its key: `{through: "tags", selection: {field: "id", operator: "in", …}}` is
367
+ * «Etiquetas es alguno de …».
368
+ *
369
+ * in {field: "customer_id", operator: "in", value: [7, 9]} (customer_id names Cliente)
370
+ * out {field: "customer", target: Cliente, operator: "in", values: [#7, #9]}
371
+ *
372
+ * Only on the record's own fields: a relation of a related record needs its model, and a row
373
+ * that stays a plain condition still filters the same.
374
+ */
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) {
379
+ if (node.kind === "group") {
380
+ return {
381
+ ...node,
382
+ children: node.children.map((child) => liftRecords(child, model, modelAt)),
383
+ };
384
+ }
385
+ if (node.target !== undefined)
386
+ return node;
387
+ const hops = node.through ?? [];
388
+ const at = (path) => path.length === 0 ? model : modelAt?.(path.map((hop) => hop.field));
389
+ const keys = () => node.values !== undefined
390
+ ? node.values.map((one) => one.id)
391
+ : typeof node.raw === "string" || typeof node.raw === "number"
392
+ ? [node.raw]
393
+ : [];
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);
399
+ if (target === undefined || target.many || target.column !== node.field)
400
+ continue;
401
+ if (!recordOps(target).includes(node.operator))
402
+ return node;
403
+ return {
404
+ kind: "condition",
405
+ ...(hops.length === 0 ? {} : { through: hops }),
406
+ field: name,
407
+ operator: node.operator,
408
+ value: "",
409
+ target,
410
+ ...(WITHOUT_VALUE.has(node.operator) ? {} : { values: unnamed(keys()) }),
411
+ };
412
+ }
413
+ }
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")
417
+ return node;
418
+ const before = hops.slice(0, -1);
419
+ const owner = at(before);
420
+ const target = owner === undefined ? undefined : recordTarget(owner, last.field);
421
+ if (target === undefined || !target.many || node.field !== target.key)
422
+ return node;
423
+ if (node.operator !== "in" && node.operator !== "=")
424
+ return node;
425
+ return {
426
+ kind: "condition",
427
+ ...(before.length === 0 ? {} : { through: before }),
428
+ field: last.field,
429
+ operator: last.match === "none" ? "not in" : "in",
430
+ value: "",
431
+ target,
432
+ values: unnamed(keys()),
433
+ };
434
+ }
435
+ /** The names of the records a tree has chosen, by relation and key: what says them in a
436
+ * sentence (`describeFilter`) once the tree is applied. */
437
+ export function namesOf(node) {
438
+ const known = new Map();
439
+ const walk = (one) => {
440
+ if (one.kind === "group")
441
+ return one.children.forEach(walk);
442
+ if (one.target === undefined)
443
+ return;
444
+ for (const value of one.values ?? []) {
445
+ if (value.name !== "")
446
+ known.set(`${one.target.name}\u0000${value.id}`, value.name);
447
+ }
448
+ };
449
+ walk(node);
450
+ return (relation, key) => known.get(`${relation}\u0000${key}`);
451
+ }
452
+ /** The tree with the names that were missing, where they are known. */
453
+ function withNames(node, names) {
454
+ if (node.kind === "group") {
455
+ return { ...node, children: node.children.map((child) => withNames(child, names)) };
456
+ }
457
+ if (node.target === undefined || node.values === undefined)
458
+ return node;
459
+ const target = node.target;
460
+ return {
461
+ ...node,
462
+ values: node.values.map((one) => one.name !== ""
463
+ ? one
464
+ : { ...one, name: names.get(`${target.name}\u0000${one.id}`) ?? `#${one.id}` }),
465
+ };
466
+ }
467
+ /**
468
+ * Names the records a tree read back carries only by key — ONE question per relation, for the
469
+ * whole tree. Per row, five rows answered at five moments and each wrote its answer over a tree
470
+ * that no longer had the others'. Until it answers, a record reads «#7».
471
+ */
472
+ export function useRecordNames(tree, searchRecords, apply) {
473
+ const missing = new Map();
474
+ const walk = (node) => {
475
+ if (node.kind === "group")
476
+ return node.children.forEach(walk);
477
+ if (node.target === undefined)
478
+ return;
479
+ const path = [...(node.through ?? []).map((hop) => hop.field), node.target.name];
480
+ for (const one of node.values ?? []) {
481
+ if (one.name !== "")
482
+ continue;
483
+ const asked = missing.get(node.target.name) ?? { target: node.target, path, keys: [] };
484
+ asked.keys.push(one.id);
485
+ missing.set(node.target.name, asked);
486
+ }
487
+ };
488
+ walk(tree);
489
+ const key = [...missing.values()]
490
+ .map((one) => `${one.target.name}:${one.keys.join(",")}`)
491
+ .join("|");
492
+ useEffect(() => {
493
+ if (searchRecords === undefined || missing.size === 0)
494
+ return;
495
+ const controller = new AbortController();
496
+ void Promise.all([...missing.values()].map(({ target, path, keys }) => searchRecords({
497
+ relation: target.relation,
498
+ path,
499
+ text: "",
500
+ keys,
501
+ signal: controller.signal,
502
+ }).then((found) => found.map((one) => [`${target.name}\u0000${one.id}`, one.name]), () => []))).then((answers) => {
503
+ if (controller.signal.aborted)
504
+ return;
505
+ const names = new Map(answers.flat());
506
+ apply((current) => withNames(current, names));
507
+ });
508
+ return () => controller.abort();
509
+ // Asked once per set of keys without a name.
510
+ // eslint-disable-next-line react-hooks/exhaustive-deps
511
+ }, [key]);
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
+ }
309
531
  function stringifyFilter(filter) {
310
532
  return filter === undefined ? "" : JSON.stringify(filter, null, 2);
311
533
  }
@@ -349,11 +571,36 @@ function describeValue(value, operator) {
349
571
  export function describeFilter(node, model,
350
572
  /** The model at the end of a path of relations, when it already arrived: it names the
351
573
  * fields of a `through`. Without it they keep their raw names. */
352
- modelAt) {
353
- return say(node, model, 0, [], modelAt);
574
+ modelAt,
575
+ /** The names of the records a filter asks for, by relation and key: «Cliente es Andrés
576
+ * Pérez» instead of «customer_id es 7». The builder hands its own (`namesOf`). */
577
+ names) {
578
+ return say(node, model, 0, [], modelAt, names);
579
+ }
580
+ /** A filter that asks for RECORDS of one of the model's relations, said as such: «Cliente es
581
+ * alguno de Andrés Pérez, Andrés Gutiérrez». `null` when it is not one. */
582
+ function sayRecords(node, model, names) {
583
+ if (model === undefined)
584
+ return null;
585
+ for (const name of Object.keys(model.fields)) {
586
+ const target = recordTarget(model, name);
587
+ if (target === undefined)
588
+ continue;
589
+ const asked = recordsOf(target, node);
590
+ if (asked === null)
591
+ continue;
592
+ const one = asked.keys.length === 1 && !target.many;
593
+ const op = asked.negate ? (one ? "!=" : "not in") : one ? "=" : "in";
594
+ const said = asked.keys.map((key) => names?.(name, key) ?? String(key)).join(", ");
595
+ return sayCondition(fieldLabel(model, name, currentCopy().locale), op, said);
596
+ }
597
+ return null;
354
598
  }
355
- function say(node, model, depth, at, modelAt) {
599
+ function say(node, model, depth, at, modelAt, names) {
356
600
  const copy = currentCopy();
601
+ const records = sayRecords(node, model, names);
602
+ if (records !== null)
603
+ return records;
357
604
  const crossed = crossedOf(node);
358
605
  if (crossed !== null) {
359
606
  /* «alguno de Líneas con alguno de Impuestos con Monto mayor que 10». The quantifier
@@ -361,7 +608,7 @@ function say(node, model, depth, at, modelAt) {
361
608
  not its gender or its singular: «algún Impuestos» would be worse than neutral. */
362
609
  const relation = model === undefined ? crossed.through : fieldLabel(model, crossed.through, copy.locale);
363
610
  const next = [...at, crossed.through];
364
- const inner = say(crossed.selection, modelAt?.(next), depth + 1, next, modelAt);
611
+ const inner = say(crossed.selection, modelAt?.(next), depth + 1, next, modelAt, names);
365
612
  const template = reachesOne(model, crossed)
366
613
  ? copy.fieldPath.say.one
367
614
  : copy.fieldPath.say[crossed.match];
@@ -370,7 +617,9 @@ function say(node, model, depth, at, modelAt) {
370
617
  if ("all" in node || "any" in node) {
371
618
  const items = "all" in node ? node.all : node.any;
372
619
  const glue = "all" in node ? copy.search.and : copy.search.or;
373
- const said = items.slice(0, 3).map((child) => say(child, model, depth + 1, at, modelAt));
620
+ const said = items
621
+ .slice(0, 3)
622
+ .map((child) => say(child, model, depth + 1, at, modelAt, names));
374
623
  if (items.length > 3) {
375
624
  said.push(fillCopy(copy.search.andMore, { count: items.length - 3 }));
376
625
  }
@@ -378,7 +627,7 @@ function say(node, model, depth, at, modelAt) {
378
627
  return depth === 0 || said.length === 1 ? joined : `(${joined})`;
379
628
  }
380
629
  if ("negate" in node) {
381
- return `${copy.search.notWord} ${say(node.negate, model, depth + 1, at, modelAt)}`;
630
+ return `${copy.search.notWord} ${say(node.negate, model, depth + 1, at, modelAt, names)}`;
382
631
  }
383
632
  /* Every `through` was said above; anything still not a condition is not a shape of the
384
633
  grammar, and it is shown as it came rather than as a sentence it is not. */
@@ -423,11 +672,16 @@ export function ExpressionView({ node, model, depth = 0, modelAt, at = [], }) {
423
672
  /* ---------------------------------------------------------------------- *
424
673
  * A GROUP, DRAWN — the piece that calls itself to nest.
425
674
  * ---------------------------------------------------------------------- */
426
- export function SelectionTree({ model, group, onChange, depth = 0, focus, loadModel, models: shared, }) {
675
+ export function SelectionTree({ model, group, onChange, depth = 0, focus, loadModel, models: shared, searchRecords: ownSearchRecords, browseRecords: ownBrowseRecords, valueEditor: ownValueEditor, }) {
427
676
  const names = filterableNames(model);
428
677
  const copy = useUiCopy();
429
678
  const surface = useSurface();
430
679
  const models = useModelCache(model, loadModel, shared);
680
+ const extend = useSearchSettings({
681
+ ...(ownSearchRecords === undefined ? {} : { searchRecords: ownSearchRecords }),
682
+ ...(ownBrowseRecords === undefined ? {} : { browseRecords: ownBrowseRecords }),
683
+ ...(ownValueEditor === undefined ? {} : { valueEditor: ownValueEditor }),
684
+ });
431
685
  const box = surface === "chrome"
432
686
  ? "border-chrome-ink/20 bg-chrome text-chrome-ink"
433
687
  : "border-ink/15 bg-surface text-ink";
@@ -460,12 +714,25 @@ export function SelectionTree({ model, group, onChange, depth = 0, focus, loadMo
460
714
  function removeAt(index) {
461
715
  onChange({ ...group, children: group.children.filter((_, at) => at !== index) });
462
716
  }
463
- return (_jsxs("div", { className: `flex min-w-0 flex-col gap-2 rounded-control border p-2 ${box}`, children: [_jsxs("p", { className: "flex flex-wrap items-baseline gap-1 text-meta", children: [copy.search.askJoin, _jsx(JoinWord, { join: group.join, onChange: (join) => onChange({ ...group, join }) })] }), group.children.map((child, index) => child.kind === "group" ? (_jsxs("div", { className: "flex min-w-0 items-start gap-2", children: [_jsx("div", { className: "min-w-0 flex-1", children: _jsx(SelectionTree, { model: model, group: child, onChange: (next) => setChild(index, next), depth: depth + 1, models: models, ...(focus === undefined ? {} : { focus }) }) }), _jsx("button", { type: "button", "aria-label": copy.builder.dropGroup, disabled: group.children.length === 1, onClick: () => removeAt(index), className: "mt-2 text-muted disabled:opacity-30", children: _jsx(Trash2, { className: "size-4" }) })] }, index)) : (_jsx(ConditionRow, { model: model, models: models, child: child, box: box, focused: focus !== undefined && child.field === focus, onChange: (next) => setChild(index, next), actions: _jsxs("span", { className: "ml-auto flex shrink-0 items-center gap-2", children: [_jsx("button", { type: "button", "aria-label": copy.builder.addRule, onClick: () => addConditionAfter(index), className: "text-muted hover:text-ink", children: _jsx(Plus, { className: "size-4" }) }), _jsx("button", { type: "button", "aria-label": copy.builder.addNested, onClick: () => addGroupAfter(index), className: "text-muted hover:text-ink", children: _jsx(FolderTree, { className: "size-4" }) }), _jsx("button", { type: "button", "aria-label": copy.builder.dropRule, disabled: group.children.length === 1, onClick: () => removeAt(index), className: "text-muted disabled:opacity-30", children: _jsx(Trash2, { className: "size-4" }) })] }) }, index)))] }));
717
+ return (_jsxs("div", { className: `flex min-w-0 flex-col gap-2 rounded-control border p-2 ${box}`, children: [_jsxs("p", { className: "flex flex-wrap items-baseline gap-1 text-meta", children: [copy.search.askJoin, _jsx(JoinWord, { join: group.join, onChange: (join) => onChange({ ...group, join }) })] }), group.children.map((child, index) => child.kind === "group" ? (_jsxs("div", { className: "flex min-w-0 items-start gap-2", children: [_jsx("div", { className: "min-w-0 flex-1", children: _jsx(SelectionTree, { model: model, group: child, onChange: (next) => setChild(index, next), depth: depth + 1, models: models, ...extend, ...(focus === undefined ? {} : { focus }) }) }), _jsx("button", { type: "button", "aria-label": copy.builder.dropGroup, disabled: group.children.length === 1, onClick: () => removeAt(index), className: "mt-2 text-muted disabled:opacity-30", children: _jsx(Trash2, { className: "size-4" }) })] }, index)) : (_jsx(ConditionRow, { model: model, models: models, child: child, box: box, focused: focus !== undefined && child.field === focus, onChange: (next) => setChild(index, next), ...extend, actions: _jsxs("span", { className: "ml-auto flex shrink-0 items-center gap-2", children: [_jsx("button", { type: "button", "aria-label": copy.builder.addRule, onClick: () => addConditionAfter(index), className: "text-muted hover:text-ink", children: _jsx(Plus, { className: "size-4" }) }), _jsx("button", { type: "button", "aria-label": copy.builder.addNested, onClick: () => addGroupAfter(index), className: "text-muted hover:text-ink", children: _jsx(FolderTree, { className: "size-4" }) }), _jsx("button", { type: "button", "aria-label": copy.builder.dropRule, disabled: group.children.length === 1, onClick: () => removeAt(index), className: "text-muted disabled:opacity-30", children: _jsx(Trash2, { className: "size-4" }) })] }) }, index)))] }));
464
718
  }
465
719
  /* ---------------------------------------------------------------------- *
466
720
  * A RULE — the path to the field, how many of each relation, the operator and the value.
467
721
  * ---------------------------------------------------------------------- */
468
- function ConditionRow({ model, models, child, box, focused, onChange, actions, }) {
722
+ /** The rule without what was chosen or read for its value: what is left when the field or
723
+ * the way of comparing changes, or something is written in the box. */
724
+ function bare(child) {
725
+ return {
726
+ kind: "condition",
727
+ field: child.field,
728
+ operator: child.operator,
729
+ value: child.value,
730
+ ...(child.through === undefined ? {} : { through: child.through }),
731
+ ...(child.upper === undefined ? {} : { upper: child.upper }),
732
+ ...(child.target === undefined ? {} : { target: child.target }),
733
+ };
734
+ }
735
+ function ConditionRow({ model, models, child, box, focused, onChange, actions, searchRecords, browseRecords, valueEditor, }) {
469
736
  const copy = useUiCopy();
470
737
  const hops = child.through ?? [];
471
738
  const path = child.field === "" ? [] : [...hops.map((hop) => hop.field), child.field];
@@ -474,7 +741,11 @@ function ConditionRow({ model, models, child, box, focused, onChange, actions, }
474
741
  relations, is compared as a number and not as the relation it was reached through. A
475
742
  root rule knows it without waiting for anybody. */
476
743
  const leaf = steps?.at(-1)?.field ?? (hops.length === 0 ? model.fields[child.field] : undefined);
477
- const ops = leaf?.ops ?? [];
744
+ const leafModel = models.peek(hops.map((hop) => hop.field));
745
+ const target = child.target;
746
+ /* A rule about records offers the comparisons that pick them —one, several, in or out—;
747
+ any other, the ones the model publishes for the field. */
748
+ const ops = target !== undefined ? recordOps(target) : (leaf?.ops ?? []);
478
749
  const type = leaf?.type ?? "text";
479
750
  function choosePath(next, found) {
480
751
  const last = found.at(-1);
@@ -485,37 +756,88 @@ function ConditionRow({ model, models, child, box, focused, onChange, actions, }
485
756
  /* Changing the final field does not reset the chip of a relation that remains in the path. */
486
757
  match: hops[at]?.field === step.name ? hops[at].match : "any",
487
758
  }));
759
+ const name = next[next.length - 1] ?? "";
760
+ /* The relation ITSELF was chosen —«Cliente», not «Cliente > Nombre»—: the rule asks
761
+ about its records, picked by name. Only when they can be searched. */
762
+ const parent = models.peek(next.slice(0, -1));
763
+ const nextTarget = searchRecords !== undefined && isRelation(last.field) && parent !== undefined
764
+ ? recordTarget(parent, name)
765
+ : undefined;
766
+ const nextOps = nextTarget !== undefined ? recordOps(nextTarget) : last.field.ops;
488
767
  onChange({
489
- ...child,
490
- through: nextHops.length === 0 ? undefined : nextHops,
491
- field: next[next.length - 1] ?? "",
492
- operator: last.field.ops.includes(child.operator)
493
- ? child.operator
494
- : (last.field.ops[0] ?? "="),
768
+ kind: "condition",
769
+ ...(nextHops.length === 0 ? {} : { through: nextHops }),
770
+ field: name,
771
+ operator: nextOps.includes(child.operator) ? child.operator : (nextOps[0] ?? "="),
772
+ value: nextTarget === undefined && child.target === undefined ? child.value : "",
773
+ ...(nextTarget === undefined ? {} : { target: nextTarget }),
495
774
  });
496
775
  }
776
+ function setOperator(operator) {
777
+ /* From several to one keeps the first: a picker of one cannot show three. */
778
+ const many = operator === "in" || operator === "not in";
779
+ const values = child.values === undefined ? undefined : many ? child.values : child.values.slice(0, 1);
780
+ onChange({ ...child, operator, ...(values === undefined ? {} : { values }) });
781
+ }
497
782
  function setMatch(at, match) {
498
783
  onChange({
499
784
  ...child,
500
785
  through: hops.map((hop, i) => (i === at ? { ...hop, match } : hop)),
501
786
  });
502
787
  }
788
+ const editor = {
789
+ name: child.field,
790
+ field: leaf ?? { type, nullable: true, sortable: false, ops },
791
+ path,
792
+ ...(leafModel === undefined ? {} : { model: leafModel }),
793
+ operator: child.operator,
794
+ value: child.value,
795
+ /* What is written IS the value: what was read or chosen before is dropped. */
796
+ onValue: (value) => onChange({ ...bare(child), value }),
797
+ values: child.values ?? [],
798
+ onValues: (values) => onChange({ ...bare(child), values }),
799
+ raw: child.raw,
800
+ onRaw: (raw) => onChange(raw === undefined
801
+ ? { ...bare(child), value: "" }
802
+ : { ...bare(child), raw, value: String(raw) }),
803
+ label: copy.builder.ruleValue,
804
+ };
503
805
  return (_jsxs("div", {
504
806
  /* The one that was come to see is marked and brought into view. A ring and not
505
807
  a background: the background competes with the `select` that has to be touched. */
506
- ref: focused ? (node) => node?.scrollIntoView({ block: "nearest" }) : undefined, className: `flex min-w-0 flex-wrap items-center gap-2 rounded-control ${focused ? "-m-1 p-1 ring-1 ring-primary/60" : ""}`, children: [_jsx(FieldPath, { model: model, models: models, value: path, label: copy.builder.ruleField, filter: (field) => isFilterable(field), onChange: choosePath }), hops.map((hop, at) => {
808
+ ref: focused ? (node) => node?.scrollIntoView({ block: "nearest" }) : undefined, className: `flex min-w-0 flex-wrap items-center gap-2 rounded-control ${focused ? "-m-1 p-1 ring-1 ring-primary/60" : ""}`, children: [_jsx(FieldPath, { model: model, models: models, value: path, label: copy.builder.ruleField,
809
+ /* A relation can be chosen itself —«Cliente es …»— when its records can be searched;
810
+ otherwise only what compares on its own. */
811
+ filter: (field) => isFilterable(field) || (searchRecords !== undefined && isRelation(field)), onChange: choosePath }), hops.map((hop, at) => {
507
812
  const step = steps?.[at];
508
813
  const many = step !== undefined && isToMany(step.field);
509
814
  return hop.match !== "any" || many ? (_jsxs("label", { className: `flex min-w-0 shrink-0 items-center gap-1 rounded-control border px-2 py-0.5 text-micro ${box}`, children: [_jsx("span", { className: "max-w-32 truncate text-muted", children: step?.label ?? hop.field }), _jsx("select", { "aria-label": fillCopy(copy.fieldPath.match.label, {
510
815
  relation: step?.label ?? hop.field,
511
816
  }), value: hop.match, onChange: (event) => setMatch(at, event.target.value), className: "bg-transparent text-micro font-medium", children: MATCHES.map((match) => (_jsx("option", { value: match, children: copy.fieldPath.match[match] }, match))) })] }, `${hop.field}-${at}`)) : null;
512
- }), _jsx("select", { "aria-label": copy.builder.ruleOperator, value: child.operator, onChange: (event) => onChange({ ...child, operator: event.target.value }), className: `min-w-0 flex-1 basis-36 rounded-control border px-2 py-1 text-meta ${box}`, children: ops.map((operator) => (_jsx("option", { value: operator, children: opLabel(operator) }, operator))) }), WITHOUT_VALUE.has(child.operator) ? (_jsx("span", { className: "flex-1 text-meta text-muted", children: copy.builder.noValue })) : 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({ ...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({ ...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("input", { type: inputType(type), value: child.value, onChange: (event) => onChange({ ...child, value: event.target.value }), placeholder: copy.builder.value, className: `min-w-0 flex-1 basis-40 rounded-control border px-2 py-1 text-meta ${box}` })), actions] }));
817
+ }), _jsx("select", { "aria-label": copy.builder.ruleOperator, value: child.operator, onChange: (event) => setOperator(event.target.value), className: `min-w-0 flex-1 basis-36 rounded-control border px-2 py-1 text-meta ${box}`, children: ops.map((operator) => (_jsx("option", { value: operator, children: opLabel(operator) }, operator))) }), WITHOUT_VALUE.has(child.operator) ? (_jsx("span", { className: "flex-1 text-meta text-muted", children: copy.builder.noValue })) : (
818
+ /* The application's control first, for the fields it draws its own way; the builder's
819
+ for the rest. */
820
+ (valueEditor?.(editor) ??
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] }));
513
822
  }
514
- export function FilterBuilder({ model, initial, onApply, onCancel, loadModel, models: shared, }) {
823
+ export function FilterBuilder({ model, initial, onApply, onCancel, loadModel, models: shared, searchRecords: ownSearchRecords, browseRecords: ownBrowseRecords, valueEditor: ownValueEditor, }) {
515
824
  const names = filterableNames(model);
516
825
  const models = useModelCache(model, loadModel, shared);
826
+ const settings = useSearchSettings({
827
+ ...(ownSearchRecords === undefined ? {} : { searchRecords: ownSearchRecords }),
828
+ ...(ownBrowseRecords === undefined ? {} : { browseRecords: ownBrowseRecords }),
829
+ ...(ownValueEditor === undefined ? {} : { valueEditor: ownValueEditor }),
830
+ });
831
+ /* A filter read back carries keys; with records searchable, the rules about records are
832
+ drawn as such again — by name. */
833
+ const read = (filter) => {
834
+ const node = treeFromFilter(filter);
835
+ return node === null || settings.searchRecords === undefined
836
+ ? node
837
+ : liftRecords(node, model);
838
+ };
517
839
  const copy = useUiCopy();
518
- const decomposed = initial === undefined ? null : treeFromFilter(initial);
840
+ const decomposed = initial === undefined ? null : read(initial);
519
841
  const [tree, setTree] = useState(() => decomposed !== null && decomposed.kind === "group"
520
842
  ? decomposed
521
843
  : decomposed !== null
@@ -524,6 +846,24 @@ export function FilterBuilder({ model, initial, onApply, onCancel, loadModel, mo
524
846
  const [lockedView, setLockedView] = useState(initial !== undefined && decomposed === null ? initial : null);
525
847
  const [rawText, setRawText] = useState(() => stringifyFilter(initial ?? treeToFilter(tree)));
526
848
  const [rawError, setRawError] = useState(null);
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("|")]);
527
867
  /* Touching the tree rewrites the JSON so it shows exactly what the tree now says,
528
868
  and drops any read-only view that may have been left. */
529
869
  function updateTree(next) {
@@ -557,7 +897,7 @@ export function FilterBuilder({ model, initial, onApply, onCancel, loadModel, mo
557
897
  return;
558
898
  }
559
899
  setRawError(null);
560
- const node = treeFromFilter(parsed);
900
+ const node = read(parsed);
561
901
  if (node !== null) {
562
902
  setTree(node.kind === "group" ? node : { kind: "group", join: "all", children: [node] });
563
903
  setLockedView(null);
@@ -566,5 +906,10 @@ export function FilterBuilder({ model, initial, onApply, onCancel, loadModel, mo
566
906
  setLockedView(parsed);
567
907
  }
568
908
  }
569
- return (_jsxs("div", { className: "flex min-w-0 flex-col gap-3 p-3", children: [_jsx("div", { className: "max-h-80 min-w-0 overflow-auto", children: lockedView !== null ? (_jsxs(_Fragment, { children: [_jsx("p", { className: "text-meta text-muted", children: copy.search.unreadable }), _jsx(ExpressionView, { node: lockedView, model: model, modelAt: models.peek })] })) : (_jsx(SelectionTree, { model: model, group: tree, onChange: updateTree, models: models })) }), _jsx(LazyJsonEditor, { value: rawText, onChange: updateRaw, error: rawError, label: copy.builder.jsonFilter }), _jsxs("div", { className: "flex gap-2", children: [_jsx(Button, { role: "primary", disabled: rawError !== null, onClick: () => onApply(rawText.trim() === "" ? undefined : JSON.parse(rawText)), children: copy.builder.add }), onCancel === undefined ? null : (_jsx(Button, { role: "ghost", onClick: onCancel, children: copy.builder.cancel }))] })] }));
909
+ return (_jsxs("div", { className: "flex min-w-0 flex-col gap-3 p-3", children: [_jsx("div", { className: "max-h-80 min-w-0 overflow-auto", children: lockedView !== null ? (_jsxs(_Fragment, { children: [_jsx("p", { className: "text-meta text-muted", children: copy.search.unreadable }), _jsx(ExpressionView, { node: lockedView, model: model, modelAt: models.peek })] })) : (_jsx(SelectionTree, { model: model, group: tree, onChange: updateTree, models: models, ...settings })) }), _jsx(LazyJsonEditor, { value: rawText, onChange: updateRaw, error: rawError, label: copy.builder.jsonFilter }), _jsxs("div", { className: "flex gap-2", children: [_jsx(Button, { role: "primary", disabled: rawError !== null, onClick: () => {
910
+ const selection = rawText.trim() === "" ? undefined : JSON.parse(rawText);
911
+ onApply(selection, selection === undefined
912
+ ? undefined
913
+ : describeFilter(selection, model, models.peek, namesOf(tree)));
914
+ }, children: copy.builder.add }), onCancel === undefined ? null : (_jsx(Button, { role: "ghost", onClick: onCancel, children: copy.builder.cancel }))] })] }));
570
915
  }
@@ -0,0 +1,21 @@
1
+ import type { ValueEditorProps } from "./context.js";
2
+ import type { BrowseRecords, RecordTarget, SearchRecords } from "./records.js";
3
+ /** The comparisons that take several values. */
4
+ export declare function takesMany(operator: string): boolean;
5
+ /**
6
+ * The builder's own value control for a rule — what is drawn when the application's
7
+ * `valueEditor` does not answer for the field.
8
+ */
9
+ export declare function RuleValue({ props, target, searchRecords, browseRecords, relationLabel, box, inputType, }: {
10
+ props: ValueEditorProps;
11
+ /** The rule asks about records of a relation. */
12
+ target?: RecordTarget;
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;
18
+ /** The look of the row's other controls, for the native ones. */
19
+ box: string;
20
+ inputType: string;
21
+ }): import("react").JSX.Element;