@sincpro/web-ui 1.9.0 → 1.10.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.
Files changed (55) hide show
  1. package/dist/components/canvas/Canvas.d.ts +14 -0
  2. package/dist/components/canvas/Canvas.js +9 -0
  3. package/dist/components/canvas/canvas.css +19 -0
  4. package/dist/components/canvas/index.d.ts +1 -0
  5. package/dist/components/canvas/index.js +2 -0
  6. package/dist/components/chat/ChatComposer.d.ts +10 -0
  7. package/dist/components/chat/ChatComposer.js +29 -0
  8. package/dist/components/chat/ChatThread.d.ts +13 -0
  9. package/dist/components/chat/ChatThread.js +76 -0
  10. package/dist/components/chat/ConversationList.d.ts +22 -0
  11. package/dist/components/chat/ConversationList.js +22 -0
  12. package/dist/components/chat/index.d.ts +4 -0
  13. package/dist/components/chat/index.js +5 -0
  14. package/dist/components/chat/model.d.ts +30 -0
  15. package/dist/components/chat/model.js +53 -0
  16. package/dist/components/index.d.ts +3 -0
  17. package/dist/components/index.js +3 -0
  18. package/dist/components/listing/ColumnsMenu.d.ts +7 -1
  19. package/dist/components/listing/ColumnsMenu.js +16 -5
  20. package/dist/components/listing/GroupingLevels.d.ts +5 -1
  21. package/dist/components/listing/GroupingLevels.js +7 -4
  22. package/dist/components/listing/ListingBar.js +2 -2
  23. package/dist/components/preview/FilePreview.d.ts +19 -0
  24. package/dist/components/preview/FilePreview.js +112 -0
  25. package/dist/components/preview/PdfPreview.d.ts +7 -0
  26. package/dist/components/preview/PdfPreview.js +47 -0
  27. package/dist/components/preview/index.d.ts +1 -0
  28. package/dist/components/preview/index.js +2 -0
  29. package/dist/components/record/SmartButtons.js +1 -1
  30. package/dist/components/search/FieldPath.d.ts +54 -0
  31. package/dist/components/search/FieldPath.js +159 -0
  32. package/dist/components/search/FilterBuilder.d.ts +38 -5
  33. package/dist/components/search/FilterBuilder.js +129 -25
  34. package/dist/components/search/SearchBar.js +7 -2
  35. package/dist/components/search/criteria.d.ts +23 -1
  36. package/dist/components/search/index.d.ts +4 -2
  37. package/dist/components/search/index.js +4 -0
  38. package/dist/components/search/paths.d.ts +49 -0
  39. package/dist/components/search/paths.js +75 -0
  40. package/dist/components/shell/TopBar.js +1 -1
  41. package/dist/foundations/copy.d.ts +86 -0
  42. package/dist/foundations/copy.es.js +63 -0
  43. package/dist/foundations/copy.js +57 -0
  44. package/dist/primitives/field/Field.js +2 -1
  45. package/dist/primitives/notice/Callout.d.ts +4 -1
  46. package/dist/primitives/notice/Callout.js +12 -2
  47. package/dist/primitives/notice/Notice.d.ts +26 -2
  48. package/dist/primitives/notice/Notice.js +64 -4
  49. package/dist/primitives/notice/Toast.js +10 -1
  50. package/dist/primitives/value/Markdown.d.ts +9 -0
  51. package/dist/primitives/value/Markdown.js +18 -0
  52. package/dist/primitives/value/index.d.ts +1 -0
  53. package/dist/primitives/value/index.js +1 -0
  54. package/dist/tokens.css +28 -0
  55. package/package.json +4 -1
@@ -0,0 +1,112 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { attachmentKind, fileExtension, formatFileSize, } from "../attachments/files.js";
4
+ import { useUiCopy } from "../../foundations/copy.js";
5
+ import { Button, ButtonLink } from "../../primitives/button/Button.js";
6
+ import { Empty, Failed, Skeleton } from "../../primitives/notice/Notice.js";
7
+ import { Download } from "lucide-react";
8
+ import { lazy, Suspense, useEffect, useState } from "react";
9
+ /* ==================================================================== *
10
+ * FILE PREVIEW — the file itself, drawn by what it is.
11
+ *
12
+ * Context: `Attachments` lists a record's files and says WHERE to open one
13
+ * (`onOpen`); this is what the application puts there — a peek, a side panel,
14
+ * a modal of the composer — so the person sees the file without leaving the
15
+ * record. The renderer is chosen by the file's kind, and the kinds with no
16
+ * honest preview (a spreadsheet, a Word file) say so and keep the download.
17
+ *
18
+ * ── Each renderer costs only when it is used ────────────────────────
19
+ *
20
+ * image an <img>, fit to the pane or at its real size
21
+ * pdf pdf.js, loaded on demand (PdfPreview)
22
+ * markdown streamdown, sanitized (Markdown)
23
+ * text the text in mono, up to a limit (a log can be gigabytes)
24
+ * other the icon's name and the download — no preview pretended
25
+ *
26
+ * ── The download is always there ────────────────────────────────────
27
+ *
28
+ * Whatever can or cannot be drawn, the file can be taken: a real `<a
29
+ * download>`, the same one the list uses, so the browser's own download
30
+ * manager keeps a large file out of the tab's memory.
31
+ * ==================================================================== */
32
+ /** The PDF renderer is its own chunk: pdf.js is not in the main bundle. */
33
+ const PdfPreview = lazy(() => import("./PdfPreview.js"));
34
+ /** streamdown is ~160 KB gzipped: a preview of an image or a PDF does not pay for it. */
35
+ const MarkdownView = lazy(() => import("../../primitives/value/Markdown.js").then((m) => ({ default: m.Markdown })));
36
+ /** A text preview larger than this is not read into the tab: download instead. */
37
+ const MAX_TEXT_BYTES = 1_000_000;
38
+ const TEXT_EXTENSIONS = new Set(["txt", "csv", "json", "log", "xml", "yaml", "yml"]);
39
+ const MARKDOWN_EXTENSIONS = new Set(["md", "markdown"]);
40
+ /** The renderer for a file. Pure, so the choice is tested without a browser. */
41
+ export function previewKind(name, type) {
42
+ const kind = attachmentKind(name, type);
43
+ if (kind === "image" || kind === "pdf")
44
+ return kind;
45
+ const extension = fileExtension(name).toLowerCase();
46
+ if (MARKDOWN_EXTENSIONS.has(extension))
47
+ return "markdown";
48
+ if (TEXT_EXTENSIONS.has(extension) || type?.startsWith("text/") === true)
49
+ return "text";
50
+ return "other";
51
+ }
52
+ export function FilePreview({ file, pdfWorkerUrl }) {
53
+ const copy = useUiCopy();
54
+ const kind = previewKind(file.name, file.type);
55
+ const size = file.size === undefined ? "" : ` · ${formatFileSize(file.size, copy.locale)}`;
56
+ return (_jsxs("section", { "aria-label": file.name, className: "flex min-h-0 flex-col gap-4", children: [_jsxs("header", { className: "flex flex-wrap items-center gap-x-4 gap-y-2", children: [_jsxs("div", { className: "min-w-0 flex-1", children: [_jsx("p", { className: "truncate text-body font-medium text-ink", children: file.name }), _jsxs("p", { className: "text-meta text-muted", children: [copy.preview.kind[kind], size] })] }), _jsx(ButtonLink, { href: file.url, download: file.name, role: "secondary", size: "sm", icon: Download, children: copy.preview.download })] }), _jsx("div", { className: "flex min-h-0 flex-1 justify-center overflow-auto rounded-control bg-ground p-5", children: _jsx(Body, { kind: kind, file: file, pdfWorkerUrl: pdfWorkerUrl }) })] }));
57
+ }
58
+ function Body({ kind, file, pdfWorkerUrl, }) {
59
+ const copy = useUiCopy();
60
+ if (kind === "image")
61
+ return _jsx(ImagePreview, { file: file });
62
+ if (kind === "pdf") {
63
+ return (_jsx(Suspense, { fallback: _jsx(Skeleton, { rows: 3, label: copy.preview.loading }), children: _jsx(PdfPreview, { url: file.url, workerUrl: pdfWorkerUrl }) }));
64
+ }
65
+ if (kind === "markdown" || kind === "text")
66
+ return _jsx(TextPreview, { kind: kind, file: file });
67
+ return _jsx(Unsupported, {});
68
+ }
69
+ function ImagePreview({ file }) {
70
+ const copy = useUiCopy();
71
+ const [actual, setActual] = useState(false);
72
+ return (_jsxs("div", { className: "flex flex-col items-center gap-3", children: [_jsx(Button, { role: "ghost", size: "sm", onClick: () => setActual((a) => !a), children: actual ? copy.preview.fit : copy.preview.actualSize }), _jsx("img", { src: file.url, alt: file.name, className: actual ? "max-w-none" : "max-h-full max-w-full object-contain" })] }));
73
+ }
74
+ function TextPreview({ kind, file }) {
75
+ const copy = useUiCopy();
76
+ const [text, setText] = useState(null);
77
+ const [failure, setFailure] = useState(null);
78
+ const tooLarge = file.size !== undefined && file.size > MAX_TEXT_BYTES;
79
+ useEffect(() => {
80
+ if (tooLarge)
81
+ return;
82
+ const controller = new AbortController();
83
+ fetch(file.url, { signal: controller.signal })
84
+ .then((response) => {
85
+ if (!response.ok)
86
+ throw new Error(`HTTP ${response.status}`);
87
+ return response.text();
88
+ })
89
+ .then((body) => setText(body))
90
+ .catch((error) => {
91
+ if (controller.signal.aborted)
92
+ return;
93
+ setFailure(error instanceof Error ? error.message : String(error));
94
+ });
95
+ return () => controller.abort();
96
+ }, [file.url, tooLarge]);
97
+ if (tooLarge)
98
+ return _jsx(Unsupported, {});
99
+ if (failure !== null) {
100
+ return (_jsx(Failed, { heading: copy.preview.failed, sentence: copy.preview.unsupported, detail: failure }));
101
+ }
102
+ if (text === null)
103
+ return _jsx(Skeleton, { rows: 4, label: copy.preview.loading });
104
+ if (kind === "markdown") {
105
+ return (_jsx("div", { className: "w-full", children: _jsx(Suspense, { fallback: _jsx(Skeleton, { rows: 4, label: copy.preview.loading }), children: _jsx(MarkdownView, { label: file.name, children: text }) }) }));
106
+ }
107
+ return (_jsx("pre", { className: "w-full font-mono text-meta leading-relaxed whitespace-pre-wrap text-ink select-text", children: text }));
108
+ }
109
+ function Unsupported() {
110
+ const copy = useUiCopy();
111
+ return _jsx(Empty, { sentence: copy.preview.unsupported });
112
+ }
@@ -0,0 +1,7 @@
1
+ export type PdfPreviewProps = {
2
+ /** Where the PDF downloads from. Same origin, or a CORS-enabled host. */
3
+ url: string;
4
+ /** The pdf.js worker. Absent = the one shipped with the dependency. */
5
+ workerUrl?: string;
6
+ };
7
+ export default function PdfPreview({ url, workerUrl }: PdfPreviewProps): import("react").JSX.Element;
@@ -0,0 +1,47 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { fillCopy, useUiCopy } from "../../foundations/copy.js";
4
+ import { IconButton } from "../../primitives/button/Button.js";
5
+ import { Failed } from "../../primitives/notice/Notice.js";
6
+ import { ChevronLeft, ChevronRight } from "lucide-react";
7
+ import { useState } from "react";
8
+ import { Document, Page, pdfjs } from "react-pdf";
9
+ /* ==================================================================== *
10
+ * THE PDF RENDERER — pdf.js through react-pdf, loaded on demand.
11
+ *
12
+ * Context: pdf.js is about a megabyte of code, and most screens never open a
13
+ * PDF. So this module is NOT part of the package's main entry: `FilePreview`
14
+ * loads it with `lazy()`, the bundler splits it into its own chunk, and the
15
+ * chunk arrives only when a person opens a PDF. The tests in Node never import
16
+ * it (pdf.js expects a browser).
17
+ *
18
+ * ── The worker runs off the page ────────────────────────────────────
19
+ *
20
+ * Parsing a PDF is heavy, so pdf.js does it in a Web Worker. The default
21
+ * worker is resolved from this package's own dependency, which a modern
22
+ * bundler (Vite, webpack 5) copies with the chunk. An application that
23
+ * serves the worker from its own origin or a CDN passes `workerUrl`.
24
+ *
25
+ * ── Text and links are not drawn as layers ─────────────────────────
26
+ *
27
+ * react-pdf can paint a selectable text layer and clickable link layer; both
28
+ * need their own stylesheets. The preview is for reading and printing, not
29
+ * for editing, so both are off: one less stylesheet to ship, and no layers to
30
+ * misalign at a zoom the browser chose.
31
+ * ==================================================================== */
32
+ const DEFAULT_WORKER = new URL("pdfjs-dist/build/pdf.worker.min.mjs", import.meta.url).toString();
33
+ export default function PdfPreview({ url, workerUrl }) {
34
+ const copy = useUiCopy();
35
+ /* The worker is a global of pdf.js: setting it again to the same value is a no-op. */
36
+ pdfjs.GlobalWorkerOptions.workerSrc = workerUrl ?? DEFAULT_WORKER;
37
+ const [total, setTotal] = useState(0);
38
+ const [page, setPage] = useState(1);
39
+ const [failure, setFailure] = useState(null);
40
+ if (failure !== null) {
41
+ return (_jsx(Failed, { heading: copy.preview.failed, sentence: copy.preview.unsupported, detail: failure }));
42
+ }
43
+ return (_jsxs("div", { className: "flex min-h-0 flex-col items-center gap-3", children: [_jsxs("nav", { "aria-label": copy.preview.label, className: "flex items-center gap-2", children: [_jsx(IconButton, { icon: ChevronLeft, label: copy.preview.previousPage, disabled: page <= 1, onClick: () => setPage((p) => Math.max(1, p - 1)) }), _jsx("span", { className: "min-w-28 text-center text-meta text-muted tabular-nums", "aria-live": "polite", children: fillCopy(copy.preview.page, { page: String(page), total: String(total) }) }), _jsx(IconButton, { icon: ChevronRight, label: copy.preview.nextPage, disabled: total === 0 || page >= total, onClick: () => setPage((p) => Math.min(total, p + 1)) })] }), _jsx(Document, { file: url, loading: _jsx("p", { className: "text-meta text-muted", children: copy.preview.loading }), onLoadSuccess: ({ numPages }) => {
44
+ setTotal(numPages);
45
+ setPage(1);
46
+ }, onLoadError: (error) => setFailure(error.message), onSourceError: (error) => setFailure(error.message), children: _jsx(Page, { pageNumber: page, renderTextLayer: false, renderAnnotationLayer: false, className: "overflow-hidden rounded-control border border-line bg-surface shadow-sm" }) })] }));
47
+ }
@@ -0,0 +1 @@
1
+ export { FilePreview, type FilePreviewProps, type PreviewFile, type PreviewKind, previewKind, } from "./FilePreview.js";
@@ -0,0 +1,2 @@
1
+ /* PREVIEW — the file itself, drawn by what it is: an image, a PDF, markdown or text. */
2
+ export { FilePreview, previewKind, } from "./FilePreview.js";
@@ -34,5 +34,5 @@ export function SmartButtons({ children }) {
34
34
  return _jsx("div", { className: "flex flex-wrap items-stretch gap-1.5", children: children });
35
35
  }
36
36
  const items = Children.toArray(children);
37
- return (_jsx(SmartGroup.Provider, { value: true, children: _jsx("div", { className: "flex min-w-0 items-stretch overflow-hidden rounded-control border border-chrome-ink/15 bg-chrome-ink/8", children: items.map((child, i) => (_jsx("div", { className: i === 0 ? "flex min-w-0" : "flex min-w-0 border-l border-chrome-ink/20", children: child }, i))) }) }));
37
+ return (_jsx(SmartGroup.Provider, { value: true, children: _jsx("div", { className: "scroll-quiet flex max-w-full min-w-0 items-stretch rounded-control border border-chrome-ink/15 bg-chrome-ink/8", children: items.map((child, i) => (_jsx("div", { className: i === 0 ? "flex shrink-0" : "flex shrink-0 border-l border-chrome-ink/20", children: child }, i))) }) }));
38
38
  }
@@ -0,0 +1,54 @@
1
+ import { type FieldDefinition, type ModelDefinition } from "./model.js";
2
+ import { type FieldPathStep, type FieldPathValue, type LoadModel, type ModelCache } from "./paths.js";
3
+ import { type LucideIcon } from "lucide-react";
4
+ /** A rule about a field met while walking: its definition, its name, and the path of
5
+ * relations that leads to its model (`[]` at the root). */
6
+ export type FieldPathRule = (field: FieldDefinition, name: string, at: FieldPathValue) => boolean;
7
+ export type FieldPathProps = {
8
+ /** The root model: the record the path starts from. */
9
+ model: ModelDefinition;
10
+ /** The model at the end of a path of relations. Absent = relations are not walked. */
11
+ loadModel?: LoadModel;
12
+ /** A cache shared with other pickers over the same root. Absent = one of its own. */
13
+ models?: ModelCache;
14
+ /** The chosen path; `[]` is nothing chosen. */
15
+ value: FieldPathValue;
16
+ /** The new path, with each step's definition and label already resolved. */
17
+ onChange: (path: string[], steps: FieldPathStep[]) => void;
18
+ /** Which fields can be chosen. Absent = all of them. */
19
+ filter?: FieldPathRule;
20
+ /** Which relations open. Default: all, when `loadModel` is there. */
21
+ followRelations?: boolean | FieldPathRule;
22
+ /** The accessible name of the trigger and of the popover: «Campo», «Columna». */
23
+ label: string;
24
+ /** What the trigger says with nothing chosen. Default: «Elegir un campo». */
25
+ placeholder?: string;
26
+ /** `select` reads like the other controls of a row; `button` is a toolbar action
27
+ * («Agregar columna») that always shows its placeholder. */
28
+ look?: "select" | "button";
29
+ /** The icon of the `button` look. */
30
+ icon?: LucideIcon;
31
+ };
32
+ /**
33
+ * A `FieldPath` offered as an ACTION of another piece: «Agregar columna» in the columns menu,
34
+ * «Agrupar por otro campo» in the grouping panel. The piece draws the button; what the chosen
35
+ * path becomes — a column, a level — is decided by whoever orchestrates the screen.
36
+ */
37
+ export type PathPick = {
38
+ model: ModelDefinition;
39
+ loadModel?: LoadModel;
40
+ filter?: FieldPathRule;
41
+ followRelations?: FieldPathProps["followRelations"];
42
+ onPick: (path: string[], steps: FieldPathStep[]) => void;
43
+ };
44
+ /** The cache a picker uses: the one it was given, or its own over its root. */
45
+ export declare function useModelCache(model: ModelDefinition, loadModel?: LoadModel, models?: ModelCache): ModelCache;
46
+ /**
47
+ * The steps of a path, once its models arrived: `undefined` while they come, `null` when the
48
+ * path does not exist in the model (or a model could not be loaded).
49
+ *
50
+ * The rows of a filter use it to learn the LAST field's operators and type: «Monto» reached
51
+ * through two relations compares like a number, not like the relation it came through.
52
+ */
53
+ export declare function useFieldPathSteps(models: ModelCache, path: FieldPathValue): FieldPathStep[] | null | undefined;
54
+ export declare function FieldPath({ model, loadModel, models: shared, value, onChange, filter, followRelations, label, placeholder, look, icon, }: FieldPathProps): import("react").JSX.Element;
@@ -0,0 +1,159 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
+ import { fieldLabel, } from "./model.js";
4
+ import { createModelCache, isRelation, pathLabel, peekLabels, resolvePath, } from "./paths.js";
5
+ import { fillCopy, useUiCopy } from "../../foundations/copy.js";
6
+ import { useSurface } from "../../foundations/surface.js";
7
+ import { Button, IconButton } from "../../primitives/button/Button.js";
8
+ import { SearchField } from "../../primitives/choice/SearchField.js";
9
+ import { listOptionStyles } from "../../primitives/field/aria.js";
10
+ import { Failed, Skeleton } from "../../primitives/notice/Notice.js";
11
+ import { Popover } from "../../primitives/overlay/Popover.js";
12
+ import { ChevronDown, ChevronLeft, ChevronRight } from "lucide-react";
13
+ import { useEffect, useMemo, useState } from "react";
14
+ import { Button as AriaButton, Dialog, DialogTrigger, ListBox, ListBoxItem, Pressable, } from "react-aria-components";
15
+ /** The cache a picker uses: the one it was given, or its own over its root. */
16
+ export function useModelCache(model, loadModel, models) {
17
+ return useMemo(() => models ?? createModelCache(model, loadModel), [models, model, loadModel]);
18
+ }
19
+ /**
20
+ * The steps of a path, once its models arrived: `undefined` while they come, `null` when the
21
+ * path does not exist in the model (or a model could not be loaded).
22
+ *
23
+ * The rows of a filter use it to learn the LAST field's operators and type: «Monto» reached
24
+ * through two relations compares like a number, not like the relation it came through.
25
+ */
26
+ export function useFieldPathSteps(models, path) {
27
+ const copy = useUiCopy();
28
+ const at = path.join("\u0000");
29
+ const [steps, setSteps] = useState();
30
+ useEffect(() => {
31
+ let alive = true;
32
+ const asked = at === "" ? [] : at.split("\u0000");
33
+ resolvePath(models, asked, copy.locale).then((found) => {
34
+ if (alive)
35
+ setSteps({ at, steps: found });
36
+ }, () => {
37
+ if (alive)
38
+ setSteps({ at, steps: null });
39
+ });
40
+ return () => {
41
+ alive = false;
42
+ };
43
+ }, [models, at, copy.locale]);
44
+ return steps === undefined || steps.at !== at ? undefined : steps.steps;
45
+ }
46
+ function follows(rule, canLoad) {
47
+ if (!canLoad || rule === false)
48
+ return () => false;
49
+ if (rule === undefined || rule === true)
50
+ return (field) => isRelation(field);
51
+ return (field, name, at) => isRelation(field) && rule(field, name, at);
52
+ }
53
+ export function FieldPath({ model, loadModel, models: shared, value, onChange, filter, followRelations, label, placeholder, look = "select", icon, }) {
54
+ const copy = useUiCopy();
55
+ const surface = useSurface();
56
+ const models = useModelCache(model, loadModel, shared);
57
+ const [open, setOpen] = useState(false);
58
+ const steps = useFieldPathSteps(models, value);
59
+ const canFollow = follows(followRelations, models.canLoad);
60
+ const canChoose = filter ?? (() => true);
61
+ const shown = value.length === 0
62
+ ? (placeholder ?? copy.fieldPath.choose)
63
+ : pathLabel(steps?.map((step) => step.label) ?? peekLabels(models, value, copy.locale));
64
+ const frame = surface === "chrome"
65
+ ? "border-chrome-ink/20 bg-chrome text-chrome-ink"
66
+ : "border-ink/15 bg-surface text-ink";
67
+ return (_jsxs(DialogTrigger, { isOpen: open, onOpenChange: setOpen, children: [look === "button" ? (_jsx(Pressable, { children: _jsx(Button, { role: "secondary", size: "sm", expanded: open, haspopup: "dialog", ...(icon === undefined ? {} : { icon }), children: placeholder ?? copy.fieldPath.choose }) })) : (_jsxs(AriaButton, { "aria-label": value.length === 0 ? label : `${label}: ${shown}`, className: `flex min-w-0 flex-1 basis-40 items-center gap-2 rounded-control border px-2 py-1 text-left text-meta outline-0 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-primary ${frame}`, children: [_jsx("span", { className: `min-w-0 flex-1 truncate ${value.length === 0 ? "text-muted" : ""}`, children: shown }), _jsx(ChevronDown, { className: "size-(--size-icon-sm) shrink-0 text-muted", "aria-hidden": true })] })), _jsx(Popover, { placement: "bottom start", children: _jsx(Dialog, { "aria-label": label, className: "flex w-72 max-w-full flex-col gap-2 p-2 outline-0", children: ({ close }) => (_jsx(Levels, { models: models, start: value.slice(0, -1), canChoose: canChoose, canFollow: canFollow, onChoose: (path) => {
68
+ void resolvePath(models, path, copy.locale).then((found) => {
69
+ if (found !== null)
70
+ onChange(path, found);
71
+ });
72
+ close();
73
+ } })) }) })] }));
74
+ }
75
+ const SELF = "\u0000self";
76
+ function fold(text) {
77
+ return text
78
+ .normalize("NFD")
79
+ .replace(/\p{Diacritic}/gu, "")
80
+ .toLocaleLowerCase();
81
+ }
82
+ function Levels({ models, start, canChoose, canFollow, onChoose, }) {
83
+ const copy = useUiCopy();
84
+ const [at, setAt] = useState(start);
85
+ const [query, setQuery] = useState("");
86
+ const [level, setLevel] = useState({ status: "loading" });
87
+ const [attempt, setAttempt] = useState(0);
88
+ useEffect(() => {
89
+ let alive = true;
90
+ setLevel({ status: "loading" });
91
+ models.get(at).then((model) => {
92
+ if (alive)
93
+ setLevel({ status: "ready", model });
94
+ }, (error) => {
95
+ if (alive)
96
+ setLevel({
97
+ status: "failed",
98
+ error: error instanceof Error ? error.message : String(error),
99
+ });
100
+ });
101
+ return () => {
102
+ alive = false;
103
+ };
104
+ }, [models, at, attempt]);
105
+ function enter(name) {
106
+ setAt([...at, name]);
107
+ setQuery("");
108
+ }
109
+ function back() {
110
+ setAt(at.slice(0, -1));
111
+ setQuery("");
112
+ }
113
+ /* Backspace in an empty search goes up a level, the way it does in Odoo: the hand that
114
+ typed the search is already on the key. */
115
+ function onKeyDown(event) {
116
+ if (event.key === "Backspace" && query === "" && at.length > 0) {
117
+ event.preventDefault();
118
+ back();
119
+ }
120
+ }
121
+ const here = pathLabel(peekLabels(models, at, copy.locale));
122
+ /* The relation this level is inside, to offer choosing it as a whole. */
123
+ const parent = at.length === 0 ? undefined : models.peek(at.slice(0, -1));
124
+ const relationName = at[at.length - 1];
125
+ const relationField = relationName === undefined ? undefined : parent?.fields[relationName];
126
+ const offerSelf = relationField !== undefined &&
127
+ relationName !== undefined &&
128
+ canChoose(relationField, relationName, at.slice(0, -1));
129
+ const rows = level.status !== "ready"
130
+ ? []
131
+ : Object.entries(level.model.fields)
132
+ .map(([name, field]) => ({
133
+ name,
134
+ field,
135
+ label: fieldLabel(level.model, name, copy.locale),
136
+ choose: canChoose(field, name, at),
137
+ follow: canFollow(field, name, at),
138
+ }))
139
+ .filter((row) => row.choose || row.follow)
140
+ .filter((row) => {
141
+ const q = fold(query.trim());
142
+ return q === "" || fold(row.label).includes(q) || fold(row.name).includes(q);
143
+ })
144
+ .sort((a, b) => a.label.localeCompare(b.label, copy.locale));
145
+ return (_jsxs("div", { onKeyDown: onKeyDown, className: "flex min-w-0 flex-col gap-2", children: [at.length === 0 ? null : (_jsxs("div", { className: "flex min-w-0 items-center gap-1", children: [_jsx(IconButton, { icon: ChevronLeft, label: copy.fieldPath.back, onClick: back }), _jsx("p", { className: "min-w-0 flex-1 truncate text-meta font-medium text-ink", children: here })] })), _jsx(SearchField, { value: query, onChange: setQuery, "aria-label": copy.fieldPath.search, placeholder: copy.fieldPath.search }), level.status === "loading" ? (_jsx(Skeleton, { rows: 4, label: copy.fieldPath.loading })) : level.status === "failed" ? (_jsx(Failed, { heading: copy.fieldPath.failed, sentence: copy.fieldPath.failedHint, detail: `${at.join(".") || "/"} — ${level.error}`, action: _jsx(Button, { role: "secondary", size: "sm", onClick: () => setAttempt((n) => n + 1), children: copy.attachments.retry }) })) : rows.length === 0 && !offerSelf ? (_jsx("p", { className: "px-2 py-3 text-meta text-muted", children: copy.fieldPath.empty })) : (_jsxs(ListBox, { "aria-label": at.length === 0 ? copy.fieldPath.search : here, className: "max-h-72 min-w-0 overflow-auto outline-0", onAction: (key) => {
146
+ const name = String(key);
147
+ if (name === SELF)
148
+ return onChoose([...at]);
149
+ const row = rows.find((one) => one.name === name);
150
+ if (row === undefined)
151
+ return;
152
+ if (row.follow)
153
+ enter(name);
154
+ else if (row.choose)
155
+ onChoose([...at, name]);
156
+ }, children: [offerSelf && relationField !== undefined ? (_jsx(ListBoxItem, { id: SELF, textValue: fillCopy(copy.fieldPath.self, { label: here }), className: (state) => `${listOptionStyles(state)} border-b border-line font-medium`, children: fillCopy(copy.fieldPath.self, {
157
+ label: peekLabels(models, at, copy.locale).at(-1) ?? "",
158
+ }) })) : null, rows.map((row) => (_jsxs(ListBoxItem, { id: row.name, textValue: row.label, className: (state) => listOptionStyles(state), children: [_jsx("span", { className: "min-w-0 flex-1 truncate", children: row.label }), row.follow ? (_jsxs(_Fragment, { children: [_jsx("span", { className: "sr-only", children: copy.fieldPath.opens }), _jsx(ChevronRight, { className: "size-(--size-icon-sm) shrink-0 text-muted", "aria-hidden": true })] })) : null] }, row.name)))] }))] }));
159
+ }
@@ -1,12 +1,25 @@
1
- import type { BuiltFilter, CriteriaJoin } from "./criteria.js";
1
+ import type { BuiltFilter, CriteriaJoin, ThroughMatch } from "./criteria.js";
2
2
  import { type ModelDefinition } from "./model.js";
3
+ import { type LoadModel, type ModelCache } from "./paths.js";
3
4
  /** Si esto es una de las formas que el filtro reconoce — condición, o grupo `all`/`any`/
4
5
  * `negate`. Un JSON válido que no es ninguna de éstas —`{}`, `{"foo": 1}`, un array suelto—
5
6
  * no es un filtro que este componente sepa dibujar, y se trata como error de forma en vez de
6
7
  * intentar mostrar cualquier cosa. */
7
8
  export declare function isRecognizedFilter(value: unknown): value is BuiltFilter;
9
+ /** One relation crossed on the way to a condition's field: «Líneas», and how many of the
10
+ * lines have to match. A to-one relation (`many: false`) reaches one record: no `match`. */
11
+ export interface TreeHop {
12
+ field: string;
13
+ many: boolean;
14
+ match: ThroughMatch;
15
+ }
8
16
  export interface TreeCondition {
9
17
  kind: "condition";
18
+ /** The relations crossed before `field`, in order: `Líneas > Impuestos` of «Líneas >
19
+ * Impuestos > Monto». Absent or empty = a field of the record itself. */
20
+ through?: TreeHop[];
21
+ /** The LAST field of the path: the one compared. Its operators and its type decide the
22
+ * rest of the row. */
10
23
  field: string;
11
24
  operator: string;
12
25
  value: string;
@@ -78,19 +91,27 @@ export declare function treeFromFilter(filter: unknown): TreeNode | null;
78
91
  * Un grupo anidado se encierra entre paréntesis, que es lo que evita que «a y (b o c)» se
79
92
  * lea como «(a y b) o c». Para más de tres condiciones se corta: una ficha que no entra en
80
93
  * la barra no dice nada — para eso está abrir el constructor y verlo entero. */
81
- export declare function describeFilter(node: BuiltFilter, model?: ModelDefinition): string;
94
+ export declare function describeFilter(node: BuiltFilter, model?: ModelDefinition,
95
+ /** The model at the end of a path of relations, when it already arrived: it names the
96
+ * fields of a `through`. Without it they keep their raw names. */
97
+ modelAt?: (path: readonly string[]) => ModelDefinition | undefined): string;
82
98
  /** El filtro dibujado tal como es, recursivo: una condición es una línea, `all`/`any` son un
83
99
  * grupo con su rótulo y sus hijos adentro, `negate` es «no» envolviendo al que niega.
84
100
  *
85
101
  * Es la mitad de sólo lectura de este archivo, y también sirve sola: mostrar qué dice un
86
102
  * filtro que ya está puesto no necesita abrir el constructor. */
87
- export declare function ExpressionView({ node, model, depth, }: {
103
+ export declare function ExpressionView({ node, model, depth, modelAt, at, }: {
88
104
  node: BuiltFilter;
89
105
  /** Quién sabe cómo se llama un campo. Sin él queda el nombre crudo. */
90
106
  model?: ModelDefinition;
91
107
  depth?: number;
108
+ /** El modelo al final de un camino de relaciones, si ya llegó: nombra los campos de un
109
+ * `through`. */
110
+ modelAt?: (path: readonly string[]) => ModelDefinition | undefined;
111
+ /** El camino hasta acá (por los `through` de afuera). */
112
+ at?: readonly string[];
92
113
  }): import("react").JSX.Element;
93
- export declare function WhereTree({ model, group, onChange, depth, focus, }: {
114
+ export declare function WhereTree({ model, group, onChange, depth, focus, loadModel, models: shared, }: {
94
115
  model: ModelDefinition;
95
116
  group: TreeGroup;
96
117
  onChange: (next: TreeGroup) => void;
@@ -114,9 +135,21 @@ export declare function WhereTree({ model, group, onChange, depth, focus, }: {
114
135
  * el otro.
115
136
  */
116
137
  focus?: string;
138
+ /** El modelo al final de un camino de relaciones. Con esto, el campo de cada regla puede
139
+ * ser uno de un registro relacionado («Líneas > Impuestos > Monto»). */
140
+ loadModel?: LoadModel;
141
+ /** La caché de modelos que comparten las reglas. La arma el árbol de afuera. */
142
+ models?: ModelCache;
117
143
  }): import("react").JSX.Element;
118
- export declare function FilterBuilder({ model, initial, onApply, onCancel, }: {
144
+ export declare function FilterBuilder({ model, initial, onApply, onCancel, loadModel, models: shared, }: {
119
145
  model: ModelDefinition;
146
+ /** El modelo al final de un camino de relaciones. Con esto, una regla puede preguntar por
147
+ * un campo de un registro relacionado: «alguna línea con algún impuesto con monto > 10».
148
+ * web-ui no pide nada: quien dibuja el constructor sabe de dónde salen los modelos. */
149
+ loadModel?: LoadModel;
150
+ /** Una caché de modelos compartida con quien dibuja el constructor —la misma que usa para
151
+ * describir el filtro aplicado con `describeFilter(…, modelAt)`—. Sin esto, una propia. */
152
+ models?: ModelCache;
120
153
  /** El filtro que ya estaba puesto, si había uno. Reabrir el constructor con esto adentro
121
154
  * tiene que seguir donde quedó, no empezar en blanco. */
122
155
  initial?: BuiltFilter;