@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,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,14 @@ 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, browseRecords: ownBrowseRecords, 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, browseRecords } = useSearchSettings({
109
+ ...(ownSearchRecords === undefined ? {} : { searchRecords: ownSearchRecords }),
110
+ ...(ownBrowseRecords === undefined ? {} : { browseRecords: ownBrowseRecords }),
111
+ });
39
112
  const [text, setText] = useState("");
40
113
  const [panel, setPanel] = useState(false);
41
114
  /* Which edge of the field the panel hangs from. It is wider than the field when the
@@ -45,9 +118,14 @@ export function SearchBar({ facets, model, criteria, onCriteriaChange, placehold
45
118
  /** The step the question being written is at: no field, with a field, or
46
119
  * with a field and operator. */
47
120
  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);
121
+ /** Which of the offered is marked, by its id: `null` is the first, which is the one Enter
122
+ * takes without going down even once. By id and not by place, because records arriving
123
+ * under an unfolded row push the rows below them down. */
124
+ const [activeId, setActiveId] = useState(null);
125
+ /** The row unfolded into its values — a relation's records, an enum's values. One at a time:
126
+ * two lists open are two places to look for the same thing. */
127
+ const [unfolded, setUnfolded] = useState(null);
128
+ const [found, setFound] = useState(null);
51
129
  /**
52
130
  * The OPEN group: where the next thing written lands.
53
131
  *
@@ -111,27 +189,179 @@ export function SearchBar({ facets, model, criteria, onCriteriaChange, placehold
111
189
  ops: ["like", "=", "!="],
112
190
  }))
113
191
  : 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. */
192
+ const records = searchRecords !== undefined;
117
193
  const suggestions = suggest({
118
194
  ...(step.field === undefined ? {} : { field: step.field }),
119
195
  ...(step.op === undefined ? {} : { op: step.op }),
120
196
  text,
121
- }, fields, { literal: literal !== undefined });
197
+ }, fields, { literal: literal !== undefined, records });
122
198
  /* What was typed, already read: needed here to know whether an
123
199
  ATTRIBUTE is being chosen —what starts with `#`— and to draw chips instead of rows. */
124
200
  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
201
  /* CHIPS are chosen when what is chosen is an attribute or a comparison, and
129
202
  rows when what is chosen is a whole question. */
130
203
  const asTags = asked.attribute === true || (step.field !== undefined && step.op === undefined);
204
+ /* The unfolded row, while it is still offered: typing more keeps it open —«andr», «andres»
205
+ narrow the same records— and a row that left the list takes its values with it. */
206
+ const unfoldedRow = suggestions.find((one) => one.id === unfolded &&
207
+ (one.kind === "unfold" || (one.kind === "condition" && one.unfolds === true)));
208
+ /* Whose records are searched, and for what: the relation chosen with `#` (its records ARE
209
+ the value step), or the relation row unfolded. */
210
+ const searching = !records
211
+ ? undefined
212
+ : step.field?.relation !== undefined && step.op !== undefined
213
+ ? { field: step.field, text: text.trim() }
214
+ : unfoldedRow !== undefined && unfoldedRow.field.relation !== undefined
215
+ ? {
216
+ field: unfoldedRow.field,
217
+ text: unfoldedRow.kind === "unfold" ? unfoldedRow.text : asked.value,
218
+ under: unfoldedRow.id,
219
+ }
220
+ : undefined;
221
+ const searchKey = searching === undefined ? "" : `${fieldKey(searching.field)}\u0000${searching.text}`;
222
+ /* The records are ASKED, never filtered here: the application searches thousands where the
223
+ bar would hold ten. A newer question cancels the one on its way (`signal`), and the
224
+ records already shown stay while the next ones come — a list that empties on every key
225
+ jumps under the hand. */
226
+ useEffect(() => {
227
+ if (searching === undefined || searchRecords === undefined)
228
+ return;
229
+ const relation = searching.field.relation;
230
+ if (relation === undefined)
231
+ return;
232
+ const key = searchKey;
233
+ const which = fieldKey(searching.field);
234
+ const asking = searching.text;
235
+ const controller = new AbortController();
236
+ setFound((before) => ({
237
+ key,
238
+ field: which,
239
+ status: "loading",
240
+ options: before?.field === which ? before.options : [],
241
+ }));
242
+ const timer = window.setTimeout(() => {
243
+ searchRecords({
244
+ relation: relation.relation,
245
+ path: [relation.name],
246
+ text: asking,
247
+ signal: controller.signal,
248
+ }).then((options) => {
249
+ if (!controller.signal.aborted)
250
+ setFound({ key, field: which, status: "ready", options: [...options] });
251
+ }, () => {
252
+ if (!controller.signal.aborted)
253
+ setFound({ key, field: which, status: "failed", options: [] });
254
+ });
255
+ }, RECORDS_DELAY);
256
+ return () => {
257
+ window.clearTimeout(timer);
258
+ controller.abort();
259
+ };
260
+ // Asked again only when WHAT is searched changes, not on every render.
261
+ // eslint-disable-next-line react-hooks/exhaustive-deps
262
+ }, [searchKey]);
263
+ /** The records of the relation being searched, as rows: each one a value, then what the
264
+ * search says when there is nothing to list, then «Buscar más…». */
265
+ function recordRows(field, query, under) {
266
+ const which = fieldKey(field);
267
+ const answer = found !== null && found.field === which ? found : null;
268
+ const settled = answer !== null && answer.key === searchKey ? answer.status : "loading";
269
+ const rows = (answer?.options ?? []).map((option) => ({
270
+ kind: "suggestion",
271
+ id: `r:${which}:${option.id}`,
272
+ suggestion: {
273
+ kind: "value",
274
+ id: `r:${which}:${option.id}`,
275
+ label: option.name,
276
+ hint: option.meta ?? "",
277
+ field,
278
+ option,
279
+ ...(under === undefined ? {} : { under }),
280
+ },
281
+ ...(under === undefined ? {} : { child: true }),
282
+ query,
283
+ }));
284
+ const nested = under === undefined ? {} : { child: true };
285
+ const status = settled === "loading"
286
+ ? copy.search.searchingRecords
287
+ : settled === "failed"
288
+ ? copy.search.recordsFailed
289
+ : rows.length === 0
290
+ ? copy.search.noRecords
291
+ : undefined;
292
+ if (status !== undefined)
293
+ rows.push({ kind: "status", id: `s:${which}`, text: status, ...nested });
294
+ if (browseRecords !== undefined) {
295
+ rows.push({ kind: "more", id: `m:${which}`, field, text: query, ...nested });
296
+ }
297
+ return rows;
298
+ }
299
+ /** What an unfolded row opens into: a relation's records, or an enum's values. */
300
+ function unfoldedRows(row) {
301
+ if (row.kind !== "unfold" && row.kind !== "condition")
302
+ return [];
303
+ const query = row.kind === "unfold" ? row.text : asked.value;
304
+ if (row.field.relation !== undefined)
305
+ return recordRows(row.field, query, row.id);
306
+ return choiceValues(row.field, query).map((option) => ({
307
+ kind: "suggestion",
308
+ id: `v:${fieldKey(row.field)}:${option.id}`,
309
+ suggestion: {
310
+ kind: "value",
311
+ id: `v:${fieldKey(row.field)}:${option.id}`,
312
+ label: option.name,
313
+ hint: "",
314
+ field: row.field,
315
+ option,
316
+ under: row.id,
317
+ },
318
+ child: true,
319
+ query,
320
+ }));
321
+ }
322
+ const items = [];
323
+ for (const one of suggestions) {
324
+ items.push({ kind: "suggestion", id: one.id, suggestion: one });
325
+ if (one.id === unfoldedRow?.id)
326
+ items.push(...unfoldedRows(one));
327
+ }
328
+ if (searching !== undefined && searching.under === undefined) {
329
+ items.push(...recordRows(searching.field, searching.text));
330
+ }
331
+ /* It opens when there is something to offer AND somebody has started: typing, or
332
+ choosing a field, which is already having started. */
333
+ const open = items.some(selectable) && (text.trim() !== "" || step.field !== undefined);
334
+ /* THE WAY INTO THE BUILDER, under what is offered: whoever typed a question the bar cannot
335
+ write —a range, a group of three, «ninguna línea con…»— is looking at this list when they
336
+ find out. It was only at the foot of the panel, behind another button. */
337
+ if (open && onOpenBuilder !== undefined && !asTags && step.field === undefined) {
338
+ items.push({ kind: "advanced", id: "a:advanced" });
339
+ }
340
+ const firstSelectable = items.findIndex(selectable);
341
+ const marked = items.findIndex((one) => one.id === activeId && selectable(one));
342
+ const active = marked >= 0 ? marked : firstSelectable;
343
+ const activeItem = items[active];
344
+ /* What is marked goes back to the first when what is offered changes: leaving the mark on the
345
+ fourth row while you keep writing makes Enter take something that is no
346
+ longer what the screen says. Only what `suggest` offers counts — records arriving under an
347
+ unfolded row do not move the mark. */
131
348
  const shown = suggestions.map((one) => one.id).join("\u0000");
132
349
  useEffect(() => {
133
- setActive(0);
350
+ setActiveId(null);
134
351
  }, [shown]);
352
+ /** Marks the row `by` places away, skipping what cannot be chosen; it wraps around. */
353
+ function move(by) {
354
+ const count = items.length;
355
+ if (count === 0)
356
+ return;
357
+ for (let step = 1; step <= count; step++) {
358
+ const next = items[(active + by * step + count * step) % count];
359
+ if (next !== undefined && selectable(next)) {
360
+ setActiveId(next.id);
361
+ return;
362
+ }
363
+ }
364
+ }
135
365
  /** A column with no options is not a column: the trigger would appear and the
136
366
  * panel would open blank. Passing `[]` is what whoever has a list that
137
367
  * declares no cut does, and it has to read the same as passing nothing. */
@@ -225,24 +455,87 @@ export function SearchBar({ facets, model, criteria, onCriteriaChange, placehold
225
455
  : replaceAt(criteria, openGroup, addTo(at(criteria, openGroup), one)));
226
456
  setText("");
227
457
  setStep({});
458
+ setUnfolded(null);
228
459
  input.current?.focus();
229
460
  }
230
461
  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);
462
+ put(conditionCriteria(field, op, value));
463
+ }
464
+ /**
465
+ * A VALUE of a field —a record, an enum's word— where things land: into the chip that
466
+ * already asks about that field, or as a new one (`withValue`). Inside the open group, the
467
+ * same: «Cliente: A o B» is still one chip there.
468
+ */
469
+ function putValue(field, option) {
470
+ const node = openGroup === null ? undefined : at(criteria, openGroup);
471
+ if (openGroup !== null && node?.kind === "join") {
472
+ onCriteriaChange(replaceAt(criteria, openGroup, { ...node, of: withValue(node.of, field, option) }));
473
+ }
474
+ else {
475
+ onCriteriaChange(withValue(criteria, field, option));
476
+ }
477
+ setText("");
478
+ setStep({});
479
+ setUnfolded(null);
480
+ input.current?.focus();
481
+ }
482
+ /** Several values of a field at once —what a chooser answers—, into the same chip. */
483
+ function putValues(field, options) {
484
+ if (options.length === 0)
485
+ return;
486
+ const node = openGroup === null ? undefined : at(criteria, openGroup);
487
+ const into = (list) => options.reduce((all, one) => withValue(all, field, one), [...list]);
488
+ if (openGroup !== null && node?.kind === "join") {
489
+ onCriteriaChange(replaceAt(criteria, openGroup, { ...node, of: into(node.of) }));
490
+ }
491
+ else {
492
+ onCriteriaChange(into(criteria));
493
+ }
494
+ setText("");
495
+ setStep({});
496
+ setUnfolded(null);
497
+ input.current?.focus();
498
+ }
499
+ /** «Buscar más…»: the application's chooser over the relation, on what was typed. What is
500
+ * already in the relation's chip is said, so a chooser of many leaves it out. */
501
+ function browse(field, query) {
502
+ const relation = field.relation;
503
+ if (browseRecords === undefined || relation === undefined)
504
+ return;
505
+ const held = criteria.find((one) => one.id === `v:${fieldKey(field)}`);
506
+ browseRecords({
507
+ relation: relation.relation,
508
+ path: [relation.name],
509
+ label: field.label,
510
+ text: query,
511
+ many: true,
512
+ chosen: held?.kind === "filter" ? (held.values ?? []) : [],
513
+ choose: (records) => putValues(field, records),
514
+ });
237
515
  }
238
516
  /** What was chosen in the dropdown, depending on what kind it is. */
239
517
  function pick(suggestion) {
240
518
  if (suggestion.kind === "field") {
241
- setStep({ field: suggestion.field });
519
+ /* A relation whose records can be searched skips the comparison: what is typed next
520
+ searches its records, and choosing one is «es». «No es» and the rest are the
521
+ builder's. */
522
+ setStep(records && suggestion.field.relation !== undefined
523
+ ? { field: suggestion.field, op: "=" }
524
+ : { field: suggestion.field });
242
525
  setText("");
526
+ setUnfolded(null);
527
+ input.current?.focus();
528
+ return;
529
+ }
530
+ if (suggestion.kind === "unfold") {
531
+ setUnfolded(suggestion.id);
243
532
  input.current?.focus();
244
533
  return;
245
534
  }
535
+ if (suggestion.kind === "value") {
536
+ putValue(suggestion.field, suggestion.option);
537
+ return;
538
+ }
246
539
  if (suggestion.kind === "op") {
247
540
  setStep((current) => ({ ...current, op: suggestion.op }));
248
541
  input.current?.focus();
@@ -274,6 +567,30 @@ export function SearchBar({ facets, model, criteria, onCriteriaChange, placehold
274
567
  }
275
568
  commit(suggestion.field, suggestion.op, suggestion.value);
276
569
  }
570
+ /** A row chosen — with Enter or the pointer. */
571
+ function choose(item) {
572
+ if (item === undefined)
573
+ return;
574
+ if (item.kind === "suggestion")
575
+ pick(item.suggestion);
576
+ else if (item.kind === "more")
577
+ browse(item.field, item.text);
578
+ else if (item.kind === "advanced") {
579
+ /* What was typed was not a question the bar could write — that is why the builder was
580
+ chosen —: it goes, and the dropdown with it, instead of staying open behind the
581
+ builder. */
582
+ setText("");
583
+ setStep({});
584
+ setUnfolded(null);
585
+ onOpenBuilder?.();
586
+ }
587
+ }
588
+ /** Opens or closes what is under a row; the mark stays on the row. */
589
+ function toggle(id) {
590
+ setUnfolded((current) => (current === id ? null : id));
591
+ setActiveId(id);
592
+ input.current?.focus();
593
+ }
277
594
  /** The node with one more instance inside. */
278
595
  function addTo(node, one) {
279
596
  return node === undefined || node.kind !== "join"
@@ -353,7 +670,7 @@ export function SearchBar({ facets, model, criteria, onCriteriaChange, placehold
353
670
  removeLabel: copy.search.dropOp,
354
671
  },
355
672
  ]),
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
673
+ ] }), _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
674
  ? { "aria-activedescendant": optionId(active) }
358
675
  : {}), value: text, onChange: (e) => setText(e.target.value), onKeyDown: (e) => {
359
676
  /* Backspace with the field empty removes the LAST instance: the gesture
@@ -372,15 +689,37 @@ export function SearchBar({ facets, model, criteria, onCriteriaChange, placehold
372
689
  list was seen and could not be touched without the mouse, which is
373
690
  precisely what a search bar cannot ask for. */
374
691
  if (e.key === "ArrowDown" || e.key === "ArrowUp") {
375
- if (suggestions.length === 0)
692
+ if (!items.some(selectable))
376
693
  return;
377
694
  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
- });
695
+ move(e.key === "ArrowDown" ? 1 : -1);
696
+ return;
697
+ }
698
+ /* → OPENS what is under the marked row —a relation's records, an enum's values—
699
+ and ← closes it and goes back to the row, the way a tree and Odoo's bar do.
700
+ Only with the caret at the end: in the middle of the text the arrows are still
701
+ the text's. */
702
+ const atEnd = e.currentTarget.selectionStart === text.length;
703
+ if (e.key === "ArrowRight" && atEnd && open && unfoldable(activeItem)) {
704
+ if (activeItem !== undefined && activeItem.id !== unfolded) {
705
+ e.preventDefault();
706
+ toggle(activeItem.id);
707
+ }
708
+ return;
709
+ }
710
+ if (e.key === "ArrowLeft" && atEnd && open && unfolded !== null) {
711
+ const parent = activeItem?.kind === "suggestion" && activeItem.suggestion.kind === "value"
712
+ ? activeItem.suggestion.under
713
+ : activeItem?.kind === "status" || activeItem?.kind === "more"
714
+ ? unfolded
715
+ : activeItem?.id === unfolded
716
+ ? unfolded
717
+ : undefined;
718
+ if (parent !== undefined) {
719
+ e.preventDefault();
720
+ setUnfolded(null);
721
+ setActiveId(parent);
722
+ }
384
723
  return;
385
724
  }
386
725
  /* Enter takes what is MARKED, which starts out being the first — and the
@@ -388,18 +727,23 @@ export function SearchBar({ facets, model, criteria, onCriteriaChange, placehold
388
727
  with «<= 100» the only one that can answer it. */
389
728
  if (e.key === "Enter") {
390
729
  e.preventDefault();
391
- const chosen = suggestions[active] ?? suggestions[0];
392
- if (chosen !== undefined)
393
- pick(chosen);
730
+ choose(activeItem);
394
731
  }
395
732
  /* Escape UNDOES, one step at a time and always the last: first what is
396
- written, then the comparison, then the field. Whoever
733
+ unfolded, then what is written, then the comparison, then the field. Whoever
397
734
  got the field wrong wants to change it, not start over — and
398
735
  whoever is not building anything does not expect anything to happen.
399
736
 
400
737
  Before, it only dismantled the step when a field had already been chosen,
401
738
  so with «vent» half-written it did nothing: the key that
402
739
  everybody presses to undo did not undo. */
740
+ if (e.key === "Escape" && unfolded !== null && open) {
741
+ e.preventDefault();
742
+ e.stopPropagation();
743
+ setActiveId(unfolded);
744
+ setUnfolded(null);
745
+ return;
746
+ }
403
747
  if (e.key === "Escape") {
404
748
  if (text !== "") {
405
749
  e.preventDefault();
@@ -410,7 +754,11 @@ export function SearchBar({ facets, model, criteria, onCriteriaChange, placehold
410
754
  if (step.op !== undefined) {
411
755
  e.preventDefault();
412
756
  e.stopPropagation();
413
- setStep({ field: step.field });
757
+ /* A relation searched by its records skipped the comparison: undoing goes
758
+ back to choosing the field, not to a step it never showed. */
759
+ setStep(records && step.field?.relation !== undefined
760
+ ? {}
761
+ : { field: step.field });
414
762
  return;
415
763
  }
416
764
  if (step.field !== undefined) {
@@ -476,11 +824,21 @@ export function SearchBar({ facets, model, criteria, onCriteriaChange, placehold
476
824
  : {}),
477
825
  active: at === active,
478
826
  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: () => {
827
+ })) }) })) : (_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"
828
+ ? "search.advanced"
829
+ : item.kind === "suggestion" && item.child !== true
830
+ ? "search.suggestion"
831
+ : "search.record",
832
+ /* The input keeps the focus: pressing an option must not take it. */
833
+ onMouseDown: (event) => event.preventDefault(), onClick: () => {
834
+ if (item.kind === "suggestion" && item.suggestion.kind === "unfold") {
835
+ toggle(item.id);
836
+ }
837
+ else
838
+ choose(item);
839
+ }, 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 ??
840
+ 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
841
  onOpenBuilder();
484
842
  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] }));
843
+ }, 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
844
  }
@@ -0,0 +1,49 @@
1
+ import type { FieldDefinition, ModelDefinition } from "./model.js";
2
+ import type { BrowseRecords, 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 «Buscar más…»: the whole list of a relation's records, in its chooser
39
+ * —another context, with its own search bar—. Offered under the records found, in the bar
40
+ * and in the builder. */
41
+ browseRecords?: BrowseRecords;
42
+ /** The application's own value controls in the builder. */
43
+ valueEditor?: ValueEditor;
44
+ }
45
+ export declare function SearchProvider({ searchRecords, browseRecords, valueEditor, children, }: SearchSettings & {
46
+ children: ReactNode;
47
+ }): import("react").JSX.Element;
48
+ /** What is in force for a piece: its own props first, then the provider's. */
49
+ export declare function useSearchSettings(own?: SearchSettings): SearchSettings;
@@ -0,0 +1,28 @@
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, browseRecords, 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
+ ...(browseRecords === undefined ? {} : { browseRecords }),
13
+ ...(valueEditor === undefined ? {} : { valueEditor }),
14
+ }), [outer, searchRecords, browseRecords, valueEditor]);
15
+ return _jsx(SearchContext.Provider, { value: value, children: children });
16
+ }
17
+ /** What is in force for a piece: its own props first, then the provider's. */
18
+ export function useSearchSettings(own = {}) {
19
+ const inherited = useContext(SearchContext);
20
+ const searchRecords = own.searchRecords ?? inherited.searchRecords;
21
+ const browseRecords = own.browseRecords ?? inherited.browseRecords;
22
+ const valueEditor = own.valueEditor ?? inherited.valueEditor;
23
+ return {
24
+ ...(searchRecords === undefined ? {} : { searchRecords }),
25
+ ...(browseRecords === undefined ? {} : { browseRecords }),
26
+ ...(valueEditor === undefined ? {} : { valueEditor }),
27
+ };
28
+ }