@sincpro/web-ui 2.6.0 → 2.7.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 };
184
+ return node.target.column === undefined
185
+ ? undefined
186
+ : { field: node.target.column, operator: node.operator, value: true };
180
187
  }
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] };
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)
190
+ return undefined;
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 ?? "") === "")
194
200
  return undefined;
195
- return { field: node.field, operator: node.operator, value: node.value };
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
+ };
211
+ }
212
+ if (node.raw !== undefined) {
213
+ return { field: node.field, operator: node.operator, value: node.raw };
196
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,157 @@ 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
+ if (node.kind === "group") {
377
+ return { ...node, children: node.children.map((child) => liftRecords(child, model)) };
378
+ }
379
+ const hops = node.through ?? [];
380
+ const keys = () => node.values !== undefined
381
+ ? node.values.map((one) => one.id)
382
+ : typeof node.raw === "string" || typeof node.raw === "number"
383
+ ? [node.raw]
384
+ : [];
385
+ if (hops.length === 0) {
386
+ for (const name of Object.keys(model.fields)) {
387
+ const target = recordTarget(model, name);
388
+ if (target === undefined || target.many || target.column !== node.field)
389
+ continue;
390
+ if (!recordOps(target).includes(node.operator))
391
+ return node;
392
+ return {
393
+ kind: "condition",
394
+ field: name,
395
+ operator: node.operator,
396
+ value: "",
397
+ target,
398
+ ...(WITHOUT_VALUE.has(node.operator) ? {} : { values: unnamed(keys()) }),
399
+ };
400
+ }
401
+ return node;
402
+ }
403
+ const [hop] = hops;
404
+ if (hops.length !== 1 || hop === undefined || hop.match === "all")
405
+ return node;
406
+ const target = recordTarget(model, hop.field);
407
+ if (target === undefined || !target.many || node.field !== target.key)
408
+ return node;
409
+ if (node.operator !== "in" && node.operator !== "=")
410
+ return node;
411
+ return {
412
+ kind: "condition",
413
+ field: hop.field,
414
+ operator: hop.match === "none" ? "not in" : "in",
415
+ value: "",
416
+ target,
417
+ values: unnamed(keys()),
418
+ };
419
+ }
420
+ /** The names of the records a tree has chosen, by relation and key: what says them in a
421
+ * sentence (`describeFilter`) once the tree is applied. */
422
+ export function namesOf(node) {
423
+ const known = new Map();
424
+ const walk = (one) => {
425
+ if (one.kind === "group")
426
+ return one.children.forEach(walk);
427
+ if (one.target === undefined)
428
+ return;
429
+ for (const value of one.values ?? []) {
430
+ if (value.name !== "")
431
+ known.set(`${one.target.name}\u0000${value.id}`, value.name);
432
+ }
433
+ };
434
+ walk(node);
435
+ return (relation, key) => known.get(`${relation}\u0000${key}`);
436
+ }
437
+ /** The tree with the names that were missing, where they are known. */
438
+ function withNames(node, names) {
439
+ if (node.kind === "group") {
440
+ return { ...node, children: node.children.map((child) => withNames(child, names)) };
441
+ }
442
+ if (node.target === undefined || node.values === undefined)
443
+ return node;
444
+ const target = node.target;
445
+ return {
446
+ ...node,
447
+ values: node.values.map((one) => one.name !== ""
448
+ ? one
449
+ : { ...one, name: names.get(`${target.name}\u0000${one.id}`) ?? `#${one.id}` }),
450
+ };
451
+ }
452
+ /**
453
+ * Names the records a tree read back carries only by key — ONE question per relation, for the
454
+ * whole tree. Per row, five rows answered at five moments and each wrote its answer over a tree
455
+ * that no longer had the others'. Until it answers, a record reads «#7».
456
+ */
457
+ export function useRecordNames(tree, searchRecords, apply) {
458
+ const missing = new Map();
459
+ const walk = (node) => {
460
+ if (node.kind === "group")
461
+ return node.children.forEach(walk);
462
+ if (node.target === undefined)
463
+ return;
464
+ for (const one of node.values ?? []) {
465
+ if (one.name !== "")
466
+ continue;
467
+ const asked = missing.get(node.target.name) ?? { target: node.target, keys: [] };
468
+ asked.keys.push(one.id);
469
+ missing.set(node.target.name, asked);
470
+ }
471
+ };
472
+ walk(tree);
473
+ const key = [...missing.values()]
474
+ .map((one) => `${one.target.name}:${one.keys.join(",")}`)
475
+ .join("|");
476
+ useEffect(() => {
477
+ if (searchRecords === undefined || missing.size === 0)
478
+ return;
479
+ const controller = new AbortController();
480
+ void Promise.all([...missing.values()].map(({ target, keys }) => searchRecords({
481
+ relation: target.relation,
482
+ path: [target.name],
483
+ text: "",
484
+ keys,
485
+ signal: controller.signal,
486
+ }).then((found) => found.map((one) => [`${target.name}\u0000${one.id}`, one.name]), () => []))).then((answers) => {
487
+ if (controller.signal.aborted)
488
+ return;
489
+ const names = new Map(answers.flat());
490
+ apply((current) => withNames(current, names));
491
+ });
492
+ return () => controller.abort();
493
+ // Asked once per set of keys without a name.
494
+ // eslint-disable-next-line react-hooks/exhaustive-deps
495
+ }, [key]);
496
+ }
309
497
  function stringifyFilter(filter) {
310
498
  return filter === undefined ? "" : JSON.stringify(filter, null, 2);
311
499
  }
@@ -349,11 +537,36 @@ function describeValue(value, operator) {
349
537
  export function describeFilter(node, model,
350
538
  /** The model at the end of a path of relations, when it already arrived: it names the
351
539
  * fields of a `through`. Without it they keep their raw names. */
352
- modelAt) {
353
- return say(node, model, 0, [], modelAt);
540
+ modelAt,
541
+ /** The names of the records a filter asks for, by relation and key: «Cliente es Andrés
542
+ * Pérez» instead of «customer_id es 7». The builder hands its own (`namesOf`). */
543
+ names) {
544
+ return say(node, model, 0, [], modelAt, names);
545
+ }
546
+ /** A filter that asks for RECORDS of one of the model's relations, said as such: «Cliente es
547
+ * alguno de Andrés Pérez, Andrés Gutiérrez». `null` when it is not one. */
548
+ function sayRecords(node, model, names) {
549
+ if (model === undefined)
550
+ return null;
551
+ for (const name of Object.keys(model.fields)) {
552
+ const target = recordTarget(model, name);
553
+ if (target === undefined)
554
+ continue;
555
+ const asked = recordsOf(target, node);
556
+ if (asked === null)
557
+ continue;
558
+ const one = asked.keys.length === 1 && !target.many;
559
+ const op = asked.negate ? (one ? "!=" : "not in") : one ? "=" : "in";
560
+ const said = asked.keys.map((key) => names?.(name, key) ?? String(key)).join(", ");
561
+ return sayCondition(fieldLabel(model, name, currentCopy().locale), op, said);
562
+ }
563
+ return null;
354
564
  }
355
- function say(node, model, depth, at, modelAt) {
565
+ function say(node, model, depth, at, modelAt, names) {
356
566
  const copy = currentCopy();
567
+ const records = sayRecords(node, model, names);
568
+ if (records !== null)
569
+ return records;
357
570
  const crossed = crossedOf(node);
358
571
  if (crossed !== null) {
359
572
  /* «alguno de Líneas con alguno de Impuestos con Monto mayor que 10». The quantifier
@@ -361,7 +574,7 @@ function say(node, model, depth, at, modelAt) {
361
574
  not its gender or its singular: «algún Impuestos» would be worse than neutral. */
362
575
  const relation = model === undefined ? crossed.through : fieldLabel(model, crossed.through, copy.locale);
363
576
  const next = [...at, crossed.through];
364
- const inner = say(crossed.selection, modelAt?.(next), depth + 1, next, modelAt);
577
+ const inner = say(crossed.selection, modelAt?.(next), depth + 1, next, modelAt, names);
365
578
  const template = reachesOne(model, crossed)
366
579
  ? copy.fieldPath.say.one
367
580
  : copy.fieldPath.say[crossed.match];
@@ -370,7 +583,9 @@ function say(node, model, depth, at, modelAt) {
370
583
  if ("all" in node || "any" in node) {
371
584
  const items = "all" in node ? node.all : node.any;
372
585
  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));
586
+ const said = items
587
+ .slice(0, 3)
588
+ .map((child) => say(child, model, depth + 1, at, modelAt, names));
374
589
  if (items.length > 3) {
375
590
  said.push(fillCopy(copy.search.andMore, { count: items.length - 3 }));
376
591
  }
@@ -378,7 +593,7 @@ function say(node, model, depth, at, modelAt) {
378
593
  return depth === 0 || said.length === 1 ? joined : `(${joined})`;
379
594
  }
380
595
  if ("negate" in node) {
381
- return `${copy.search.notWord} ${say(node.negate, model, depth + 1, at, modelAt)}`;
596
+ return `${copy.search.notWord} ${say(node.negate, model, depth + 1, at, modelAt, names)}`;
382
597
  }
383
598
  /* Every `through` was said above; anything still not a condition is not a shape of the
384
599
  grammar, and it is shown as it came rather than as a sentence it is not. */
@@ -423,11 +638,19 @@ export function ExpressionView({ node, model, depth = 0, modelAt, at = [], }) {
423
638
  /* ---------------------------------------------------------------------- *
424
639
  * A GROUP, DRAWN — the piece that calls itself to nest.
425
640
  * ---------------------------------------------------------------------- */
426
- export function SelectionTree({ model, group, onChange, depth = 0, focus, loadModel, models: shared, }) {
641
+ export function SelectionTree({ model, group, onChange, depth = 0, focus, loadModel, models: shared, searchRecords: ownSearchRecords, valueEditor: ownValueEditor, }) {
427
642
  const names = filterableNames(model);
428
643
  const copy = useUiCopy();
429
644
  const surface = useSurface();
430
645
  const models = useModelCache(model, loadModel, shared);
646
+ const { searchRecords, valueEditor } = useSearchSettings({
647
+ ...(ownSearchRecords === undefined ? {} : { searchRecords: ownSearchRecords }),
648
+ ...(ownValueEditor === undefined ? {} : { valueEditor: ownValueEditor }),
649
+ });
650
+ const extend = {
651
+ ...(searchRecords === undefined ? {} : { searchRecords }),
652
+ ...(valueEditor === undefined ? {} : { valueEditor }),
653
+ };
431
654
  const box = surface === "chrome"
432
655
  ? "border-chrome-ink/20 bg-chrome text-chrome-ink"
433
656
  : "border-ink/15 bg-surface text-ink";
@@ -460,12 +683,25 @@ export function SelectionTree({ model, group, onChange, depth = 0, focus, loadMo
460
683
  function removeAt(index) {
461
684
  onChange({ ...group, children: group.children.filter((_, at) => at !== index) });
462
685
  }
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)))] }));
686
+ 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
687
  }
465
688
  /* ---------------------------------------------------------------------- *
466
689
  * A RULE — the path to the field, how many of each relation, the operator and the value.
467
690
  * ---------------------------------------------------------------------- */
468
- function ConditionRow({ model, models, child, box, focused, onChange, actions, }) {
691
+ /** The rule without what was chosen or read for its value: what is left when the field or
692
+ * the way of comparing changes, or something is written in the box. */
693
+ function bare(child) {
694
+ return {
695
+ kind: "condition",
696
+ field: child.field,
697
+ operator: child.operator,
698
+ value: child.value,
699
+ ...(child.through === undefined ? {} : { through: child.through }),
700
+ ...(child.upper === undefined ? {} : { upper: child.upper }),
701
+ ...(child.target === undefined ? {} : { target: child.target }),
702
+ };
703
+ }
704
+ function ConditionRow({ model, models, child, box, focused, onChange, actions, searchRecords, valueEditor, }) {
469
705
  const copy = useUiCopy();
470
706
  const hops = child.through ?? [];
471
707
  const path = child.field === "" ? [] : [...hops.map((hop) => hop.field), child.field];
@@ -474,7 +710,11 @@ function ConditionRow({ model, models, child, box, focused, onChange, actions, }
474
710
  relations, is compared as a number and not as the relation it was reached through. A
475
711
  root rule knows it without waiting for anybody. */
476
712
  const leaf = steps?.at(-1)?.field ?? (hops.length === 0 ? model.fields[child.field] : undefined);
477
- const ops = leaf?.ops ?? [];
713
+ const leafModel = models.peek(hops.map((hop) => hop.field));
714
+ const target = child.target;
715
+ /* A rule about records offers the comparisons that pick them —one, several, in or out—;
716
+ any other, the ones the model publishes for the field. */
717
+ const ops = target !== undefined ? recordOps(target) : (leaf?.ops ?? []);
478
718
  const type = leaf?.type ?? "text";
479
719
  function choosePath(next, found) {
480
720
  const last = found.at(-1);
@@ -485,37 +725,87 @@ function ConditionRow({ model, models, child, box, focused, onChange, actions, }
485
725
  /* Changing the final field does not reset the chip of a relation that remains in the path. */
486
726
  match: hops[at]?.field === step.name ? hops[at].match : "any",
487
727
  }));
728
+ const name = next[next.length - 1] ?? "";
729
+ /* The relation ITSELF was chosen —«Cliente», not «Cliente > Nombre»—: the rule asks
730
+ about its records, picked by name. Only when they can be searched. */
731
+ const parent = models.peek(next.slice(0, -1));
732
+ const nextTarget = searchRecords !== undefined && isRelation(last.field) && parent !== undefined
733
+ ? recordTarget(parent, name)
734
+ : undefined;
735
+ const nextOps = nextTarget !== undefined ? recordOps(nextTarget) : last.field.ops;
488
736
  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] ?? "="),
737
+ kind: "condition",
738
+ ...(nextHops.length === 0 ? {} : { through: nextHops }),
739
+ field: name,
740
+ operator: nextOps.includes(child.operator) ? child.operator : (nextOps[0] ?? "="),
741
+ value: nextTarget === undefined && child.target === undefined ? child.value : "",
742
+ ...(nextTarget === undefined ? {} : { target: nextTarget }),
495
743
  });
496
744
  }
745
+ function setOperator(operator) {
746
+ /* From several to one keeps the first: a picker of one cannot show three. */
747
+ const many = operator === "in" || operator === "not in";
748
+ const values = child.values === undefined ? undefined : many ? child.values : child.values.slice(0, 1);
749
+ onChange({ ...child, operator, ...(values === undefined ? {} : { values }) });
750
+ }
497
751
  function setMatch(at, match) {
498
752
  onChange({
499
753
  ...child,
500
754
  through: hops.map((hop, i) => (i === at ? { ...hop, match } : hop)),
501
755
  });
502
756
  }
757
+ const editor = {
758
+ name: child.field,
759
+ field: leaf ?? { type, nullable: true, sortable: false, ops },
760
+ path,
761
+ ...(leafModel === undefined ? {} : { model: leafModel }),
762
+ operator: child.operator,
763
+ value: child.value,
764
+ /* What is written IS the value: what was read or chosen before is dropped. */
765
+ onValue: (value) => onChange({ ...bare(child), value }),
766
+ values: child.values ?? [],
767
+ onValues: (values) => onChange({ ...bare(child), values }),
768
+ raw: child.raw,
769
+ onRaw: (raw) => onChange(raw === undefined
770
+ ? { ...bare(child), value: "" }
771
+ : { ...bare(child), raw, value: String(raw) }),
772
+ label: copy.builder.ruleValue,
773
+ };
503
774
  return (_jsxs("div", {
504
775
  /* The one that was come to see is marked and brought into view. A ring and not
505
776
  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) => {
777
+ 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,
778
+ /* A relation can be chosen itself —«Cliente es …»— when its records can be searched;
779
+ otherwise only what compares on its own. */
780
+ filter: (field) => isFilterable(field) || (searchRecords !== undefined && isRelation(field)), onChange: choosePath }), hops.map((hop, at) => {
507
781
  const step = steps?.[at];
508
782
  const many = step !== undefined && isToMany(step.field);
509
783
  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
784
  relation: step?.label ?? hop.field,
511
785
  }), 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] }));
786
+ }), _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 })) : (
787
+ /* The application's control first, for the fields it draws its own way; the builder's
788
+ for the rest. */
789
+ (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] }));
513
791
  }
514
- export function FilterBuilder({ model, initial, onApply, onCancel, loadModel, models: shared, }) {
792
+ export function FilterBuilder({ model, initial, onApply, onCancel, loadModel, models: shared, searchRecords: ownSearchRecords, valueEditor: ownValueEditor, }) {
515
793
  const names = filterableNames(model);
516
794
  const models = useModelCache(model, loadModel, shared);
795
+ const settings = useSearchSettings({
796
+ ...(ownSearchRecords === undefined ? {} : { searchRecords: ownSearchRecords }),
797
+ ...(ownValueEditor === undefined ? {} : { valueEditor: ownValueEditor }),
798
+ });
799
+ /* A filter read back carries keys; with records searchable, the rules about records are
800
+ drawn as such again — by name. */
801
+ const read = (filter) => {
802
+ const node = treeFromFilter(filter);
803
+ return node === null || settings.searchRecords === undefined
804
+ ? node
805
+ : liftRecords(node, model);
806
+ };
517
807
  const copy = useUiCopy();
518
- const decomposed = initial === undefined ? null : treeFromFilter(initial);
808
+ const decomposed = initial === undefined ? null : read(initial);
519
809
  const [tree, setTree] = useState(() => decomposed !== null && decomposed.kind === "group"
520
810
  ? decomposed
521
811
  : decomposed !== null
@@ -524,6 +814,7 @@ export function FilterBuilder({ model, initial, onApply, onCancel, loadModel, mo
524
814
  const [lockedView, setLockedView] = useState(initial !== undefined && decomposed === null ? initial : null);
525
815
  const [rawText, setRawText] = useState(() => stringifyFilter(initial ?? treeToFilter(tree)));
526
816
  const [rawError, setRawError] = useState(null);
817
+ useRecordNames(tree, settings.searchRecords, (named) => setTree((current) => named(current)));
527
818
  /* Touching the tree rewrites the JSON so it shows exactly what the tree now says,
528
819
  and drops any read-only view that may have been left. */
529
820
  function updateTree(next) {
@@ -557,7 +848,7 @@ export function FilterBuilder({ model, initial, onApply, onCancel, loadModel, mo
557
848
  return;
558
849
  }
559
850
  setRawError(null);
560
- const node = treeFromFilter(parsed);
851
+ const node = read(parsed);
561
852
  if (node !== null) {
562
853
  setTree(node.kind === "group" ? node : { kind: "group", join: "all", children: [node] });
563
854
  setLockedView(null);
@@ -566,5 +857,10 @@ export function FilterBuilder({ model, initial, onApply, onCancel, loadModel, mo
566
857
  setLockedView(parsed);
567
858
  }
568
859
  }
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 }))] })] }));
860
+ 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: () => {
861
+ const selection = rawText.trim() === "" ? undefined : JSON.parse(rawText);
862
+ onApply(selection, selection === undefined
863
+ ? undefined
864
+ : describeFilter(selection, model, models.peek, namesOf(tree)));
865
+ }, children: copy.builder.add }), onCancel === undefined ? null : (_jsx(Button, { role: "ghost", onClick: onCancel, children: copy.builder.cancel }))] })] }));
570
866
  }
@@ -0,0 +1,17 @@
1
+ import type { ValueEditorProps } from "./context.js";
2
+ import type { 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, box, inputType, }: {
10
+ props: ValueEditorProps;
11
+ /** The rule asks about records of a relation. */
12
+ target?: RecordTarget;
13
+ searchRecords?: SearchRecords;
14
+ /** The look of the row's other controls, for the native ones. */
15
+ box: string;
16
+ inputType: string;
17
+ }): import("react").JSX.Element;