@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,17 +1,85 @@
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 { at, criteriaId, filterCriteria, removeAt, replaceAt, } from "./criteria.js";
4
5
  import { CriteriaChips } from "./CriteriaChips.js";
5
- import { describeCondition, opLabel, queryFields, readTyped, suggest, withoutValue, } from "./query.js";
6
+ import { choiceValues, conditionCriteria, fieldKey, opLabel, queryFields, readTyped, suggest, withValue, } from "./query.js";
6
7
  import { fillCopy, useUiCopy } from "../../foundations/copy.js";
7
8
  import { bySurface, useSurface } from "../../foundations/surface.js";
8
9
  import { CheckMark } from "../../primitives/field/Checks.js";
10
+ import { MatchedText } from "../../primitives/picker/MatchedText.js";
9
11
  import { Count } from "../../primitives/tag/Count.js";
10
12
  import { chosenTone } from "../../primitives/tag/Tag.js";
11
13
  import { Tags } from "../../primitives/tag/Tags.js";
12
- import { ChevronRight, CornerDownRight, Layers, ListFilter, Search, SlidersHorizontal, Star, X, } from "lucide-react";
14
+ import { CalendarDays, ChevronRight, CornerDownRight, Hash, Layers, Link2, List, ListFilter, Search, SlidersHorizontal, Star, ToggleLeft, Type, X, } from "lucide-react";
13
15
  import { Fragment, useEffect, useId, useRef, useState } from "react";
14
16
  import { mergeProps, Overlay, useOverlay, useOverlayPosition } from "react-aria";
17
+ /** What kind of field a row asks about, at a glance: its icon. */
18
+ const KIND_ICON = {
19
+ text: Type,
20
+ number: Hash,
21
+ date: CalendarDays,
22
+ boolean: ToggleLeft,
23
+ choice: List,
24
+ relation: Link2,
25
+ };
26
+ /** How long the bar waits for the typing to stop before searching records: every key would
27
+ * be a request, and the answer to «a», «an», «and» is thrown away anyway. */
28
+ const RECORDS_DELAY = 200;
29
+ /** A row the keyboard and the pointer stop on — every one but a status. */
30
+ function selectable(item) {
31
+ return item.kind !== "status";
32
+ }
33
+ /** A row that opens what is under it with → (or its ▸). */
34
+ function unfoldable(item) {
35
+ if (item?.kind !== "suggestion" || item.child === true)
36
+ return false;
37
+ const one = item.suggestion;
38
+ return one.kind === "unfold" || (one.kind === "condition" && one.unfolds === true);
39
+ }
40
+ /**
41
+ * What one row of the dropdown says. The row around it —its role, its mark, what pressing it
42
+ * does— is the bar's; this is only its content, so every kind reads the same way:
43
+ *
44
+ * ▢ Cliente : contiene andres ▸ a question; ▸ opens its records
45
+ * ▢ Etiquetas con «urg» ▸ a field asked only by its values
46
+ * Andrés Pérez 1028457 a value under its row
47
+ * Buscar más…
48
+ * ⚙ Búsqueda avanzada…
49
+ */
50
+ function SuggestionRow({ item, open, onToggle, renderRecord, }) {
51
+ const copy = useUiCopy();
52
+ const indent = "ml-6 border-l border-line pl-2.5";
53
+ if (item.kind === "status") {
54
+ return (_jsx("span", { className: `min-w-0 truncate text-micro text-muted ${item.child === true ? indent : ""}`, children: item.text }));
55
+ }
56
+ if (item.kind === "more") {
57
+ return (_jsxs("span", { className: `flex min-w-0 items-center gap-1.5 font-medium text-primary ${item.child === true ? indent : ""}`, children: [_jsx(Search, { className: "size-(--size-icon-sm) shrink-0", strokeWidth: 2, "aria-hidden": true }), copy.search.moreRecords] }));
58
+ }
59
+ if (item.kind === "advanced") {
60
+ return (_jsxs("span", { className: "-mx-2 -my-1.5 flex w-full min-w-0 items-center gap-2 border-t border-line px-2 pt-2 pb-1.5 font-medium text-primary", children: [_jsx(SlidersHorizontal, { className: "size-(--size-icon-sm) shrink-0", strokeWidth: 2, "aria-hidden": true }), copy.search.advanced] }));
61
+ }
62
+ const one = item.suggestion;
63
+ /* A VALUE under its row: the record's name with what was typed marked —it says why it is
64
+ listed—, and what tells two of the same name apart on the right. */
65
+ if (one.kind === "value" && item.child === true) {
66
+ const query = item.query ?? "";
67
+ return (_jsx("span", { className: `flex min-w-0 flex-1 items-baseline gap-2 ${indent}`, children: renderRecord !== undefined ? (renderRecord(one.option, { field: one.field, query })) : (_jsxs(_Fragment, { children: [_jsx("span", { className: "min-w-0 flex-1 truncate text-ink", children: _jsx(MatchedText, { text: one.option.name, query: query }) }), one.option.meta === undefined ? null : (_jsx("span", { className: "shrink-0 text-micro text-muted tabular-nums", children: one.option.meta }))] })) }));
68
+ }
69
+ const Icon = one.kind === "literal"
70
+ ? Search
71
+ : one.kind === "condition" ||
72
+ one.kind === "unfold" ||
73
+ one.kind === "value" ||
74
+ one.kind === "field"
75
+ ? KIND_ICON[one.field.kind]
76
+ : undefined;
77
+ const opens = one.kind === "unfold" || (one.kind === "condition" && one.unfolds === true);
78
+ return (_jsxs(_Fragment, { children: [Icon === undefined ? null : (_jsx(Icon, { className: "size-(--size-icon-sm) shrink-0 text-muted", strokeWidth: 2, "aria-hidden": true })), _jsxs("span", { className: "flex min-w-0 flex-1 items-baseline gap-1.5", children: [_jsx("span", { className: "shrink-0 font-medium text-ink", children: one.label }), one.kind === "condition" || one.kind === "literal" || one.kind === "value" ? (one.hint === "" ? null : (_jsxs(_Fragment, { children: [_jsx("span", { className: "shrink-0 text-muted", children: ":" }), _jsx("span", { className: "min-w-0 truncate font-mono text-micro text-ink", children: one.hint })] }))) : one.kind === "unfold" ? (_jsx("span", { className: "min-w-0 truncate text-micro text-muted", children: fillCopy(copy.search.unfoldHint, { text: one.hint }) })) : one.kind === "field" && one.hint !== undefined ? (_jsx("span", { className: "inline-flex shrink-0 items-center rounded-pill border border-line-strong bg-ink/5 px-2 py-0.5 text-micro text-muted", children: one.hint })) : null] }), !opens ? null : (_jsx("span", { "aria-hidden": true, title: open ? copy.search.fold : copy.search.unfold, onClick: (event) => {
79
+ event.stopPropagation();
80
+ onToggle();
81
+ }, className: "-my-1 -mr-1 inline-flex shrink-0 items-center rounded-control p-1 text-muted hover:bg-ink/6 hover:text-ink", children: _jsx(ChevronRight, { className: `size-(--size-icon-sm) transition-transform duration-(--duration-instant) ${open ? "rotate-90" : ""}`, strokeWidth: 2 }) })), !opens ? null : (_jsx("span", { className: "sr-only", children: open ? copy.search.fold : copy.search.unfold }))] }));
82
+ }
15
83
  function Option({ o, checks, onSelect, }) {
16
84
  const Icon = o.icon;
17
85
  const toggles = checks || o.checked !== undefined;
@@ -33,9 +101,11 @@ function Group({ group, first, checks, onSelect, }) {
33
101
  ? "flex flex-col gap-0.5 pl-(--spacing-indent)"
34
102
  : "flex flex-col gap-0.5", children: options }))] }));
35
103
  }
36
- export function SearchBar({ facets, model, criteria, onCriteriaChange, placeholder, filters, grouping, onOpenGroup, favorites, onFilterSelect, onFavoriteSelect, onOpenBuilder, literal, trailing, collapseAfter, surface, }) {
104
+ export function SearchBar({ facets, model, criteria, onCriteriaChange, placeholder, filters, grouping, onOpenGroup, favorites, onFilterSelect, onFavoriteSelect, onOpenBuilder, literal, searchRecords: ownSearchRecords, onBrowseRecords, renderRecord, trailing, collapseAfter, surface, }) {
37
105
  const copy = useUiCopy();
38
106
  const sup = useSurface(surface);
107
+ /* Its own, or the application's (`SearchProvider`): wired once for every bar. */
108
+ const { searchRecords } = useSearchSettings(ownSearchRecords === undefined ? {} : { searchRecords: ownSearchRecords });
39
109
  const [text, setText] = useState("");
40
110
  const [panel, setPanel] = useState(false);
41
111
  /* Which edge of the field the panel hangs from. It is wider than the field when the
@@ -45,9 +115,14 @@ export function SearchBar({ facets, model, criteria, onCriteriaChange, placehold
45
115
  /** The step the question being written is at: no field, with a field, or
46
116
  * with a field and operator. */
47
117
  const [step, setStep] = useState({});
48
- /** Which of the offered is marked. It starts on the first, which is the one
49
- * Enter takes without going down even once. */
50
- const [active, setActive] = useState(0);
118
+ /** Which of the offered is marked, by its id: `null` is the first, which is the one Enter
119
+ * takes without going down even once. By id and not by place, because records arriving
120
+ * under an unfolded row push the rows below them down. */
121
+ const [activeId, setActiveId] = useState(null);
122
+ /** The row unfolded into its values — a relation's records, an enum's values. One at a time:
123
+ * two lists open are two places to look for the same thing. */
124
+ const [unfolded, setUnfolded] = useState(null);
125
+ const [found, setFound] = useState(null);
51
126
  /**
52
127
  * The OPEN group: where the next thing written lands.
53
128
  *
@@ -111,27 +186,179 @@ export function SearchBar({ facets, model, criteria, onCriteriaChange, placehold
111
186
  ops: ["like", "=", "!="],
112
187
  }))
113
188
  : queryFields(model, copy.locale);
114
- /* What is marked goes back to the first when what is offered changes: leaving the mark on the
115
- fourth row while you keep writing makes Enter take something that is no
116
- longer what the screen says. */
189
+ const records = searchRecords !== undefined;
117
190
  const suggestions = suggest({
118
191
  ...(step.field === undefined ? {} : { field: step.field }),
119
192
  ...(step.op === undefined ? {} : { op: step.op }),
120
193
  text,
121
- }, fields, { literal: literal !== undefined });
194
+ }, fields, { literal: literal !== undefined, records });
122
195
  /* What was typed, already read: needed here to know whether an
123
196
  ATTRIBUTE is being chosen —what starts with `#`— and to draw chips instead of rows. */
124
197
  const asked = readTyped(text);
125
- /* It opens when there is something to offer AND somebody has started: typing, or
126
- choosing a field, which is already having started. */
127
- const open = suggestions.length > 0 && (text.trim() !== "" || step.field !== undefined);
128
198
  /* CHIPS are chosen when what is chosen is an attribute or a comparison, and
129
199
  rows when what is chosen is a whole question. */
130
200
  const asTags = asked.attribute === true || (step.field !== undefined && step.op === undefined);
201
+ /* The unfolded row, while it is still offered: typing more keeps it open —«andr», «andres»
202
+ narrow the same records— and a row that left the list takes its values with it. */
203
+ const unfoldedRow = suggestions.find((one) => one.id === unfolded &&
204
+ (one.kind === "unfold" || (one.kind === "condition" && one.unfolds === true)));
205
+ /* Whose records are searched, and for what: the relation chosen with `#` (its records ARE
206
+ the value step), or the relation row unfolded. */
207
+ const searching = !records
208
+ ? undefined
209
+ : step.field?.relation !== undefined && step.op !== undefined
210
+ ? { field: step.field, text: text.trim() }
211
+ : unfoldedRow !== undefined && unfoldedRow.field.relation !== undefined
212
+ ? {
213
+ field: unfoldedRow.field,
214
+ text: unfoldedRow.kind === "unfold" ? unfoldedRow.text : asked.value,
215
+ under: unfoldedRow.id,
216
+ }
217
+ : undefined;
218
+ const searchKey = searching === undefined ? "" : `${fieldKey(searching.field)}\u0000${searching.text}`;
219
+ /* The records are ASKED, never filtered here: the application searches thousands where the
220
+ bar would hold ten. A newer question cancels the one on its way (`signal`), and the
221
+ records already shown stay while the next ones come — a list that empties on every key
222
+ jumps under the hand. */
223
+ useEffect(() => {
224
+ if (searching === undefined || searchRecords === undefined)
225
+ return;
226
+ const relation = searching.field.relation;
227
+ if (relation === undefined)
228
+ return;
229
+ const key = searchKey;
230
+ const which = fieldKey(searching.field);
231
+ const asking = searching.text;
232
+ const controller = new AbortController();
233
+ setFound((before) => ({
234
+ key,
235
+ field: which,
236
+ status: "loading",
237
+ options: before?.field === which ? before.options : [],
238
+ }));
239
+ const timer = window.setTimeout(() => {
240
+ searchRecords({
241
+ relation: relation.relation,
242
+ path: [relation.name],
243
+ text: asking,
244
+ signal: controller.signal,
245
+ }).then((options) => {
246
+ if (!controller.signal.aborted)
247
+ setFound({ key, field: which, status: "ready", options: [...options] });
248
+ }, () => {
249
+ if (!controller.signal.aborted)
250
+ setFound({ key, field: which, status: "failed", options: [] });
251
+ });
252
+ }, RECORDS_DELAY);
253
+ return () => {
254
+ window.clearTimeout(timer);
255
+ controller.abort();
256
+ };
257
+ // Asked again only when WHAT is searched changes, not on every render.
258
+ // eslint-disable-next-line react-hooks/exhaustive-deps
259
+ }, [searchKey]);
260
+ /** The records of the relation being searched, as rows: each one a value, then what the
261
+ * search says when there is nothing to list, then «Buscar más…». */
262
+ function recordRows(field, query, under) {
263
+ const which = fieldKey(field);
264
+ const answer = found !== null && found.field === which ? found : null;
265
+ const settled = answer !== null && answer.key === searchKey ? answer.status : "loading";
266
+ const rows = (answer?.options ?? []).map((option) => ({
267
+ kind: "suggestion",
268
+ id: `r:${which}:${option.id}`,
269
+ suggestion: {
270
+ kind: "value",
271
+ id: `r:${which}:${option.id}`,
272
+ label: option.name,
273
+ hint: option.meta ?? "",
274
+ field,
275
+ option,
276
+ ...(under === undefined ? {} : { under }),
277
+ },
278
+ ...(under === undefined ? {} : { child: true }),
279
+ query,
280
+ }));
281
+ const nested = under === undefined ? {} : { child: true };
282
+ const status = settled === "loading"
283
+ ? copy.search.searchingRecords
284
+ : settled === "failed"
285
+ ? copy.search.recordsFailed
286
+ : rows.length === 0
287
+ ? copy.search.noRecords
288
+ : undefined;
289
+ if (status !== undefined)
290
+ rows.push({ kind: "status", id: `s:${which}`, text: status, ...nested });
291
+ if (onBrowseRecords !== undefined) {
292
+ rows.push({ kind: "more", id: `m:${which}`, field, text: query, ...nested });
293
+ }
294
+ return rows;
295
+ }
296
+ /** What an unfolded row opens into: a relation's records, or an enum's values. */
297
+ function unfoldedRows(row) {
298
+ if (row.kind !== "unfold" && row.kind !== "condition")
299
+ return [];
300
+ const query = row.kind === "unfold" ? row.text : asked.value;
301
+ if (row.field.relation !== undefined)
302
+ return recordRows(row.field, query, row.id);
303
+ return choiceValues(row.field, query).map((option) => ({
304
+ kind: "suggestion",
305
+ id: `v:${fieldKey(row.field)}:${option.id}`,
306
+ suggestion: {
307
+ kind: "value",
308
+ id: `v:${fieldKey(row.field)}:${option.id}`,
309
+ label: option.name,
310
+ hint: "",
311
+ field: row.field,
312
+ option,
313
+ under: row.id,
314
+ },
315
+ child: true,
316
+ query,
317
+ }));
318
+ }
319
+ const items = [];
320
+ for (const one of suggestions) {
321
+ items.push({ kind: "suggestion", id: one.id, suggestion: one });
322
+ if (one.id === unfoldedRow?.id)
323
+ items.push(...unfoldedRows(one));
324
+ }
325
+ if (searching !== undefined && searching.under === undefined) {
326
+ items.push(...recordRows(searching.field, searching.text));
327
+ }
328
+ /* It opens when there is something to offer AND somebody has started: typing, or
329
+ choosing a field, which is already having started. */
330
+ const open = items.some(selectable) && (text.trim() !== "" || step.field !== undefined);
331
+ /* THE WAY INTO THE BUILDER, under what is offered: whoever typed a question the bar cannot
332
+ write —a range, a group of three, «ninguna línea con…»— is looking at this list when they
333
+ find out. It was only at the foot of the panel, behind another button. */
334
+ if (open && onOpenBuilder !== undefined && !asTags && step.field === undefined) {
335
+ items.push({ kind: "advanced", id: "a:advanced" });
336
+ }
337
+ const firstSelectable = items.findIndex(selectable);
338
+ const marked = items.findIndex((one) => one.id === activeId && selectable(one));
339
+ const active = marked >= 0 ? marked : firstSelectable;
340
+ const activeItem = items[active];
341
+ /* What is marked goes back to the first when what is offered changes: leaving the mark on the
342
+ fourth row while you keep writing makes Enter take something that is no
343
+ longer what the screen says. Only what `suggest` offers counts — records arriving under an
344
+ unfolded row do not move the mark. */
131
345
  const shown = suggestions.map((one) => one.id).join("\u0000");
132
346
  useEffect(() => {
133
- setActive(0);
347
+ setActiveId(null);
134
348
  }, [shown]);
349
+ /** Marks the row `by` places away, skipping what cannot be chosen; it wraps around. */
350
+ function move(by) {
351
+ const count = items.length;
352
+ if (count === 0)
353
+ return;
354
+ for (let step = 1; step <= count; step++) {
355
+ const next = items[(active + by * step + count * step) % count];
356
+ if (next !== undefined && selectable(next)) {
357
+ setActiveId(next.id);
358
+ return;
359
+ }
360
+ }
361
+ }
135
362
  /** A column with no options is not a column: the trigger would appear and the
136
363
  * panel would open blank. Passing `[]` is what whoever has a list that
137
364
  * declares no cut does, and it has to read the same as passing nothing. */
@@ -225,24 +452,53 @@ export function SearchBar({ facets, model, criteria, onCriteriaChange, placehold
225
452
  : replaceAt(criteria, openGroup, addTo(at(criteria, openGroup), one)));
226
453
  setText("");
227
454
  setStep({});
455
+ setUnfolded(null);
228
456
  input.current?.focus();
229
457
  }
230
458
  function commit(field, op, value) {
231
- const one = filterCriteria(
232
- /* The one that takes no value travels with `true`, which is what the engine expects of
233
- «está vacío»: sending it the empty string would be asking for the field that
234
- is "". */
235
- { field: field.field, operator: op, value: withoutValue(op) ? true : value }, describeCondition(field, op, value));
236
- put(one);
459
+ put(conditionCriteria(field, op, value));
460
+ }
461
+ /**
462
+ * A VALUE of a field —a record, an enum's word— where things land: into the chip that
463
+ * already asks about that field, or as a new one (`withValue`). Inside the open group, the
464
+ * same: «Cliente: A o B» is still one chip there.
465
+ */
466
+ function putValue(field, option) {
467
+ const node = openGroup === null ? undefined : at(criteria, openGroup);
468
+ if (openGroup !== null && node?.kind === "join") {
469
+ onCriteriaChange(replaceAt(criteria, openGroup, { ...node, of: withValue(node.of, field, option) }));
470
+ }
471
+ else {
472
+ onCriteriaChange(withValue(criteria, field, option));
473
+ }
474
+ setText("");
475
+ setStep({});
476
+ setUnfolded(null);
477
+ input.current?.focus();
237
478
  }
238
479
  /** What was chosen in the dropdown, depending on what kind it is. */
239
480
  function pick(suggestion) {
240
481
  if (suggestion.kind === "field") {
241
- setStep({ field: suggestion.field });
482
+ /* A relation whose records can be searched skips the comparison: what is typed next
483
+ searches its records, and choosing one is «es». «No es» and the rest are the
484
+ builder's. */
485
+ setStep(records && suggestion.field.relation !== undefined
486
+ ? { field: suggestion.field, op: "=" }
487
+ : { field: suggestion.field });
242
488
  setText("");
489
+ setUnfolded(null);
243
490
  input.current?.focus();
244
491
  return;
245
492
  }
493
+ if (suggestion.kind === "unfold") {
494
+ setUnfolded(suggestion.id);
495
+ input.current?.focus();
496
+ return;
497
+ }
498
+ if (suggestion.kind === "value") {
499
+ putValue(suggestion.field, suggestion.option);
500
+ return;
501
+ }
246
502
  if (suggestion.kind === "op") {
247
503
  setStep((current) => ({ ...current, op: suggestion.op }));
248
504
  input.current?.focus();
@@ -274,6 +530,30 @@ export function SearchBar({ facets, model, criteria, onCriteriaChange, placehold
274
530
  }
275
531
  commit(suggestion.field, suggestion.op, suggestion.value);
276
532
  }
533
+ /** A row chosen — with Enter or the pointer. */
534
+ function choose(item) {
535
+ if (item === undefined)
536
+ return;
537
+ if (item.kind === "suggestion")
538
+ pick(item.suggestion);
539
+ else if (item.kind === "more")
540
+ onBrowseRecords?.(item.field, item.text);
541
+ else if (item.kind === "advanced") {
542
+ /* What was typed was not a question the bar could write — that is why the builder was
543
+ chosen —: it goes, and the dropdown with it, instead of staying open behind the
544
+ builder. */
545
+ setText("");
546
+ setStep({});
547
+ setUnfolded(null);
548
+ onOpenBuilder?.();
549
+ }
550
+ }
551
+ /** Opens or closes what is under a row; the mark stays on the row. */
552
+ function toggle(id) {
553
+ setUnfolded((current) => (current === id ? null : id));
554
+ setActiveId(id);
555
+ input.current?.focus();
556
+ }
277
557
  /** The node with one more instance inside. */
278
558
  function addTo(node, one) {
279
559
  return node === undefined || node.kind !== "join"
@@ -353,7 +633,7 @@ export function SearchBar({ facets, model, criteria, onCriteriaChange, placehold
353
633
  removeLabel: copy.search.dropOp,
354
634
  },
355
635
  ]),
356
- ] }), _jsx("input", { ref: input, "aria-label": copy.choice.search, role: "combobox", "aria-autocomplete": "list", "aria-expanded": open, ...(open ? { "aria-controls": listId } : {}), ...(open && !asTags && suggestions[active] !== undefined
636
+ ] }), _jsx("input", { ref: input, "aria-label": copy.choice.search, role: "combobox", "aria-autocomplete": "list", "aria-expanded": open, ...(open ? { "aria-controls": listId } : {}), ...(open && !asTags && activeItem !== undefined
357
637
  ? { "aria-activedescendant": optionId(active) }
358
638
  : {}), value: text, onChange: (e) => setText(e.target.value), onKeyDown: (e) => {
359
639
  /* Backspace with the field empty removes the LAST instance: the gesture
@@ -372,15 +652,37 @@ export function SearchBar({ facets, model, criteria, onCriteriaChange, placehold
372
652
  list was seen and could not be touched without the mouse, which is
373
653
  precisely what a search bar cannot ask for. */
374
654
  if (e.key === "ArrowDown" || e.key === "ArrowUp") {
375
- if (suggestions.length === 0)
655
+ if (!items.some(selectable))
376
656
  return;
377
657
  e.preventDefault();
378
- setActive((current) => {
379
- const next = e.key === "ArrowDown" ? current + 1 : current - 1;
380
- /* It wraps around: with five fields, going down six times returns to the
381
- first instead of getting stuck on the last. */
382
- return (next + suggestions.length) % suggestions.length;
383
- });
658
+ move(e.key === "ArrowDown" ? 1 : -1);
659
+ return;
660
+ }
661
+ /* → OPENS what is under the marked row —a relation's records, an enum's values—
662
+ and ← closes it and goes back to the row, the way a tree and Odoo's bar do.
663
+ Only with the caret at the end: in the middle of the text the arrows are still
664
+ the text's. */
665
+ const atEnd = e.currentTarget.selectionStart === text.length;
666
+ if (e.key === "ArrowRight" && atEnd && open && unfoldable(activeItem)) {
667
+ if (activeItem !== undefined && activeItem.id !== unfolded) {
668
+ e.preventDefault();
669
+ toggle(activeItem.id);
670
+ }
671
+ return;
672
+ }
673
+ if (e.key === "ArrowLeft" && atEnd && open && unfolded !== null) {
674
+ const parent = activeItem?.kind === "suggestion" && activeItem.suggestion.kind === "value"
675
+ ? activeItem.suggestion.under
676
+ : activeItem?.kind === "status" || activeItem?.kind === "more"
677
+ ? unfolded
678
+ : activeItem?.id === unfolded
679
+ ? unfolded
680
+ : undefined;
681
+ if (parent !== undefined) {
682
+ e.preventDefault();
683
+ setUnfolded(null);
684
+ setActiveId(parent);
685
+ }
384
686
  return;
385
687
  }
386
688
  /* Enter takes what is MARKED, which starts out being the first — and the
@@ -388,18 +690,23 @@ export function SearchBar({ facets, model, criteria, onCriteriaChange, placehold
388
690
  with «<= 100» the only one that can answer it. */
389
691
  if (e.key === "Enter") {
390
692
  e.preventDefault();
391
- const chosen = suggestions[active] ?? suggestions[0];
392
- if (chosen !== undefined)
393
- pick(chosen);
693
+ choose(activeItem);
394
694
  }
395
695
  /* Escape UNDOES, one step at a time and always the last: first what is
396
- written, then the comparison, then the field. Whoever
696
+ unfolded, then what is written, then the comparison, then the field. Whoever
397
697
  got the field wrong wants to change it, not start over — and
398
698
  whoever is not building anything does not expect anything to happen.
399
699
 
400
700
  Before, it only dismantled the step when a field had already been chosen,
401
701
  so with «vent» half-written it did nothing: the key that
402
702
  everybody presses to undo did not undo. */
703
+ if (e.key === "Escape" && unfolded !== null && open) {
704
+ e.preventDefault();
705
+ e.stopPropagation();
706
+ setActiveId(unfolded);
707
+ setUnfolded(null);
708
+ return;
709
+ }
403
710
  if (e.key === "Escape") {
404
711
  if (text !== "") {
405
712
  e.preventDefault();
@@ -410,7 +717,11 @@ export function SearchBar({ facets, model, criteria, onCriteriaChange, placehold
410
717
  if (step.op !== undefined) {
411
718
  e.preventDefault();
412
719
  e.stopPropagation();
413
- setStep({ field: step.field });
720
+ /* A relation searched by its records skipped the comparison: undoing goes
721
+ back to choosing the field, not to a step it never showed. */
722
+ setStep(records && step.field?.relation !== undefined
723
+ ? {}
724
+ : { field: step.field });
414
725
  return;
415
726
  }
416
727
  if (step.field !== undefined) {
@@ -476,11 +787,21 @@ export function SearchBar({ facets, model, criteria, onCriteriaChange, placehold
476
787
  : {}),
477
788
  active: at === active,
478
789
  onSelect: () => pick(one),
479
- })) }) })) : (_jsx("div", { id: listId, role: "listbox", "aria-label": copy.search.suggestions, className: "p-1", children: suggestions.map((one, at) => (_jsxs("div", { id: optionId(at), role: "option", "aria-selected": at === active,
480
- /* The input keeps the focus: pressing an option must not take it. */
481
- onMouseDown: (event) => event.preventDefault(), onClick: () => pick(one), onMouseEnter: () => setActive(at), className: `flex w-full cursor-pointer items-baseline gap-1.5 rounded-ui-option px-2 py-1.5 text-left text-meta transition-colors duration-(--duration-instant) ${at === active ? "bg-ui-option-active" : "hover:bg-ink/4"}`, children: [_jsx("span", { className: "shrink-0 font-medium text-ink", children: one.label }), one.kind === "condition" || one.kind === "literal" ? (_jsxs(_Fragment, { children: [_jsx("span", { className: "shrink-0 text-muted", children: ":" }), _jsx("span", { className: "min-w-0 truncate font-mono text-micro text-ink", children: one.hint })] })) : one.kind === "field" && one.hint !== undefined ? (_jsx("span", { className: "inline-flex shrink-0 items-center rounded-pill border border-line-strong bg-ink/5 px-2 py-0.5 text-micro text-muted", children: one.hint })) : null] }, one.id))) }))] })) : null, panel && (columns.length > 0 || onOpenBuilder !== undefined) ? (_jsx(Overlay, { children: _jsxs("div", { ...mergeProps(overlayProps, positionProps), ref: panelBox, id: id, "data-react-aria-top-layer": "", "data-ui": "search.panel", className: "z-30 flex w-max max-w-(--container-cuts) flex-wrap overflow-hidden rounded-ui-popover border border-ui-popover-border bg-ui-popover shadow-ui-popover", children: [columns.map((c, i) => (_jsxs("div", { className: `flex min-w-48 flex-1 flex-col ${i === 0 ? "" : "border-t border-line sm:border-t-0 sm:border-l"}`, children: [_jsxs("div", { className: "flex items-center gap-2 px-2.5 pt-2.5 pb-1 text-meta font-semibold text-ink", children: [_jsx(c.icon, { className: "size-(--size-icon-sm) shrink-0 text-muted", strokeWidth: 2, "aria-hidden": true }), c.title] }), _jsx("div", { className: "flex max-h-96 flex-col gap-0.5 overflow-y-auto p-1", children: c.content ??
482
- c.groups?.map((g, gi) => (_jsx(Group, { group: g, first: gi === 0, checks: c.checks === true, onSelect: c.onSelect }, g.label ?? gi))) })] }, c.title))), onOpenBuilder === undefined ? null : (_jsx("div", { className: "w-full border-t border-line p-1", children: _jsxs("button", { type: "button", onClick: () => {
790
+ })) }) })) : (_jsxs(_Fragment, { children: [_jsx("div", { id: listId, role: "listbox", "aria-label": copy.search.suggestions, className: "max-h-96 overflow-y-auto p-1", children: items.map((item, at) => (_jsx("div", { id: optionId(at), role: "option", "aria-selected": at === active, ...(item.kind === "status" ? { "aria-disabled": true } : {}), "data-ui": item.kind === "advanced"
791
+ ? "search.advanced"
792
+ : item.kind === "suggestion" && item.child !== true
793
+ ? "search.suggestion"
794
+ : "search.record",
795
+ /* The input keeps the focus: pressing an option must not take it. */
796
+ onMouseDown: (event) => event.preventDefault(), onClick: () => {
797
+ if (item.kind === "suggestion" && item.suggestion.kind === "unfold") {
798
+ toggle(item.id);
799
+ }
800
+ else
801
+ choose(item);
802
+ }, onMouseEnter: selectable(item) ? () => setActiveId(item.id) : undefined, className: `flex w-full items-center gap-2 rounded-ui-option px-2 py-1.5 text-left text-meta transition-colors duration-(--duration-instant) ${item.kind === "status" ? "cursor-default" : "cursor-pointer"} ${item.kind === "advanced" ? "mt-1" : ""} ${at === active ? "bg-ui-option-active" : selectable(item) ? "hover:bg-ink/4" : ""}`, children: _jsx(SuggestionRow, { item: item, open: item.id === unfoldedRow?.id, onToggle: () => toggle(item.id), ...(renderRecord === undefined ? {} : { renderRecord }) }) }, item.id))) }), _jsx("p", { "data-ui": "search.keys", className: "hidden border-t border-line px-3 py-1 text-micro text-muted sm:block", children: copy.search.keysHint })] }))] })) : null, panel && (columns.length > 0 || onOpenBuilder !== undefined) ? (_jsx(Overlay, { children: _jsxs("div", { ...mergeProps(overlayProps, positionProps), ref: panelBox, id: id, "data-react-aria-top-layer": "", "data-ui": "search.panel", className: "z-30 flex w-max max-w-(--container-cuts) flex-wrap overflow-hidden rounded-ui-popover border border-ui-popover-border bg-ui-popover shadow-ui-popover", children: [columns.map((c, i) => (_jsxs("div", { className: `flex min-w-48 flex-1 flex-col ${i === 0 ? "" : "border-t border-line sm:border-t-0 sm:border-l"}`, children: [_jsxs("div", { className: "flex items-center gap-2 px-2.5 pt-2.5 pb-1 text-meta font-semibold text-ink", children: [_jsx(c.icon, { className: "size-(--size-icon-sm) shrink-0 text-muted", strokeWidth: 2, "aria-hidden": true }), c.title] }), _jsx("div", { className: "flex max-h-96 flex-col gap-0.5 overflow-y-auto p-1", children: c.content ??
803
+ c.groups?.map((g, gi) => (_jsx(Group, { group: g, first: gi === 0, checks: c.checks === true, onSelect: c.onSelect }, g.label ?? gi))) })] }, c.title))), onOpenBuilder === undefined ? null : (_jsx("div", { className: "w-full border-t border-line p-1.5", children: _jsxs("button", { type: "button", "data-ui": "search.advanced", title: copy.search.openBuilder, onClick: () => {
483
804
  onOpenBuilder();
484
805
  setPanel(false);
485
- }, className: "flex w-full items-center gap-2 rounded-ui-option px-1.5 py-1 text-left text-meta text-ink transition-colors duration-(--duration-instant) hover:bg-ui-option-active focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-primary", children: [_jsx(SlidersHorizontal, { className: "size-(--size-icon-sm)", strokeWidth: 2 }), copy.search.openBuilder] }) }))] }) })) : null] }));
806
+ }, className: "flex w-full items-center gap-2 rounded-ui-option px-2 py-1.5 text-left text-meta font-medium text-primary transition-colors duration-(--duration-instant) hover:bg-primary/8 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-primary", children: [_jsx(SlidersHorizontal, { className: "size-(--size-icon-sm)", strokeWidth: 2, "aria-hidden": true }), copy.search.advanced] }) }))] }) })) : null] }));
486
807
  }
@@ -0,0 +1,45 @@
1
+ import type { FieldDefinition, ModelDefinition } from "./model.js";
2
+ import type { RecordOption, SearchRecords } from "./records.js";
3
+ import { type ReactNode } from "react";
4
+ /** What a value control of the builder is handed: the field the rule compares, the
5
+ * comparison, and the value — written (`value`) or chosen (`values`, with their names). */
6
+ export interface ValueEditorProps {
7
+ /** The field compared — the LAST one of the path — and its definition. */
8
+ name: string;
9
+ field: FieldDefinition;
10
+ /** The relations crossed and the field, from the root: `["lines", "product_id"]`. */
11
+ path: readonly string[];
12
+ /** The model the field belongs to, when it already arrived. */
13
+ model?: ModelDefinition;
14
+ operator: string;
15
+ /** What is written, for a value that is typed. */
16
+ value: string;
17
+ onValue: (value: string) => void;
18
+ /** What is chosen, for a value that is picked — records of a relation, words of an enum —
19
+ * with their names: what travels is their `id`. */
20
+ values: readonly RecordOption[];
21
+ onValues: (values: RecordOption[]) => void;
22
+ /** The value as it travels, when it is not a text: `true`, a number, a range `[a, b]` of a
23
+ * control of the application's. `undefined` = nothing set. */
24
+ raw: unknown;
25
+ onRaw: (raw: unknown) => void;
26
+ /** The control's accessible name. */
27
+ label: string;
28
+ }
29
+ /**
30
+ * A value control of the application's own, for the fields it wants drawn its way — a date
31
+ * range, a many2one with photos, a color. It answers `undefined` for the rest, which keep
32
+ * the builder's control.
33
+ */
34
+ export type ValueEditor = (props: ValueEditorProps) => ReactNode | undefined;
35
+ export interface SearchSettings {
36
+ /** The application's search over the records of a relation (see `records.ts`). */
37
+ searchRecords?: SearchRecords;
38
+ /** The application's own value controls in the builder. */
39
+ valueEditor?: ValueEditor;
40
+ }
41
+ export declare function SearchProvider({ searchRecords, valueEditor, children, }: SearchSettings & {
42
+ children: ReactNode;
43
+ }): import("react").JSX.Element;
44
+ /** What is in force for a piece: its own props first, then the provider's. */
45
+ export declare function useSearchSettings(own?: SearchSettings): SearchSettings;
@@ -0,0 +1,25 @@
1
+ "use client";
2
+ import { jsx as _jsx } from "react/jsx-runtime";
3
+ import { createContext, useContext, useMemo } from "react";
4
+ const SearchContext = createContext({});
5
+ export function SearchProvider({ searchRecords, valueEditor, children, }) {
6
+ /* A provider nested inside another keeps what it does not say: a screen can swap the
7
+ value controls and still search records the way the app does. */
8
+ const outer = useContext(SearchContext);
9
+ const value = useMemo(() => ({
10
+ ...outer,
11
+ ...(searchRecords === undefined ? {} : { searchRecords }),
12
+ ...(valueEditor === undefined ? {} : { valueEditor }),
13
+ }), [outer, searchRecords, valueEditor]);
14
+ return _jsx(SearchContext.Provider, { value: value, children: children });
15
+ }
16
+ /** What is in force for a piece: its own props first, then the provider's. */
17
+ export function useSearchSettings(own = {}) {
18
+ const inherited = useContext(SearchContext);
19
+ const searchRecords = own.searchRecords ?? inherited.searchRecords;
20
+ const valueEditor = own.valueEditor ?? inherited.valueEditor;
21
+ return {
22
+ ...(searchRecords === undefined ? {} : { searchRecords }),
23
+ ...(valueEditor === undefined ? {} : { valueEditor }),
24
+ };
25
+ }
@@ -16,6 +16,20 @@ export type BuiltFilter = BuiltCondition | {
16
16
  } | {
17
17
  negate: BuiltFilter;
18
18
  } | BuiltThrough;
19
+ /** The key of a record: what the relation's identifying column holds for it. */
20
+ export type RecordKey = string | number;
21
+ /** A record of a relation —or a value of an enum— as a search answers it: what travels and
22
+ * what is read. See `records.ts`. */
23
+ export interface RecordOption {
24
+ /** What travels: for a many2one, what its identifying column holds (its foreign key); for a
25
+ * to-many relation, the key of the record on the other side (`relationKey`, `id`); for an
26
+ * enum, the value. */
27
+ id: RecordKey;
28
+ /** What is read: the record's display name, the enum's word. */
29
+ name: string;
30
+ /** What tells two of the same name apart, already written: a NIT, an email. */
31
+ meta?: string;
32
+ }
19
33
  /** How many of the records reached through a to-many relation have to match: «alguno»,
20
34
  * «ninguno», «todos». It is the TREE's word, not a key that travels: criteria's
21
35
  * `{through, selection}` says «some», and the other two are written with `negate` around it
@@ -81,6 +95,12 @@ export type SearchCriteria = {
81
95
  * of anything: it was drawn in the menu and ticking it did nothing.
82
96
  */
83
97
  selection?: BuiltCondition | BuiltFilter;
98
+ /**
99
+ * The values it asks for, when it asks for values of ONE field — records of a relation,
100
+ * values of an enum —, with the names it reads by. A second value of the same field
101
+ * lands here (`withValue`), and the chip says «Cliente: Andrés Pérez o Andrés Gutiérrez».
102
+ */
103
+ values?: readonly RecordOption[];
84
104
  } | {
85
105
  id: string;
86
106
  kind: "join";