@easyvision/easyvision-ui 1.3.4

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.
package/dist/index.js ADDED
@@ -0,0 +1,2929 @@
1
+ import './easyvision-DCTYH6PP.css';
2
+ import './EasyVisionTable-643DMWO4.css';
3
+ import * as React8 from 'react';
4
+ import { createContext, forwardRef, useMemo, useState, useEffect, useRef, useCallback, useImperativeHandle, useSyncExternalStore, useContext, createElement } from 'react';
5
+ import { ChevronDown, ChevronUp, Check, Search, X, Plus, ChevronRight, Circle, Calendar as Calendar$1, ChevronLeft, ChevronsUpDown, Loader2, ArrowUp, ArrowDown, ArrowUpDown, Settings2 } from 'lucide-react';
6
+ import { clsx } from 'clsx';
7
+ import { twMerge } from 'tailwind-merge';
8
+ import { jsx, jsxs } from 'react/jsx-runtime';
9
+ import { createStore } from 'zustand/vanilla';
10
+ import * as SelectPrimitive from '@radix-ui/react-select';
11
+ import { Slot } from '@radix-ui/react-slot';
12
+ import { cva } from 'class-variance-authority';
13
+ import * as PopoverPrimitive from '@radix-ui/react-popover';
14
+ import { MagnifyingGlassIcon } from '@radix-ui/react-icons';
15
+ import { Command as Command$1 } from 'cmdk';
16
+ import * as CheckboxPrimitive from '@radix-ui/react-checkbox';
17
+ import { format } from 'date-fns';
18
+ import { es } from 'date-fns/locale';
19
+ import { DayPicker } from 'react-day-picker';
20
+ import { useReactTable, getCoreRowModel, flexRender } from '@tanstack/react-table';
21
+ import * as DropdownMenuPrimitive from '@radix-ui/react-dropdown-menu';
22
+
23
+ // index.ts
24
+ function cn(...inputs) {
25
+ return twMerge(clsx(inputs));
26
+ }
27
+ var Input = React8.forwardRef(
28
+ ({ className, type, ...props }, ref) => {
29
+ return /* @__PURE__ */ jsx(
30
+ "input",
31
+ {
32
+ type,
33
+ className: cn(
34
+ "flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
35
+ className
36
+ ),
37
+ ref,
38
+ ...props
39
+ }
40
+ );
41
+ }
42
+ );
43
+ Input.displayName = "Input";
44
+ var easyVisionRegistry = createStore((set, get) => ({
45
+ slices: {},
46
+ ensure: (_kind, fullId, init) => {
47
+ const existing = get().slices[fullId];
48
+ if (existing) return existing;
49
+ const created = init();
50
+ set((s) => ({ slices: { ...s.slices, [fullId]: created } }));
51
+ return created;
52
+ },
53
+ patch: (fullId, partial) => {
54
+ set((s) => {
55
+ const current = s.slices[fullId];
56
+ if (!current) return s;
57
+ return {
58
+ slices: {
59
+ ...s.slices,
60
+ [fullId]: { ...current, ...partial }
61
+ }
62
+ };
63
+ });
64
+ },
65
+ drop: (fullId) => {
66
+ set((s) => {
67
+ const next = {};
68
+ const prefix = `${fullId}.`;
69
+ for (const key of Object.keys(s.slices)) {
70
+ if (key !== fullId && !key.startsWith(prefix)) {
71
+ next[key] = s.slices[key];
72
+ }
73
+ }
74
+ return { slices: next };
75
+ });
76
+ },
77
+ reset: () => set({ slices: {} })
78
+ }));
79
+ var getSlice = (fullId) => easyVisionRegistry.getState().slices[fullId];
80
+
81
+ // store/slice-types.ts
82
+ var KIND_SUFFIX = {
83
+ input: "-input",
84
+ selector: "-selector",
85
+ multifilter: "-multifilter",
86
+ table: "-table"
87
+ };
88
+
89
+ // store/namespace.ts
90
+ var fullIdOf = (id, kind) => `${id}${KIND_SUFFIX[kind]}`;
91
+ var childIdOf = (parentFullId, childLocalId) => `${parentFullId}.${childLocalId}`;
92
+ var childFullIdOf = (parentFullId, childLocalId, childKind) => parentFullId ? `${childIdOf(parentFullId, childLocalId)}${KIND_SUFFIX[childKind]}` : fullIdOf(childLocalId, childKind);
93
+ var NamespaceContext = createContext(null);
94
+ function NamespaceProvider({
95
+ fullId,
96
+ children
97
+ }) {
98
+ return /* @__PURE__ */ jsx(NamespaceContext.Provider, { value: fullId, children });
99
+ }
100
+ var useParentFullId = () => useContext(NamespaceContext);
101
+
102
+ // store/useEasyVisionSlice.ts
103
+ function useEasyVisionSlice(kind, localId, opts) {
104
+ const parentFullId = useParentFullId();
105
+ const fullId = useMemo(
106
+ () => childFullIdOf(parentFullId, localId, kind),
107
+ [parentFullId, localId, kind]
108
+ );
109
+ if (!easyVisionRegistry.getState().slices[fullId]) {
110
+ easyVisionRegistry.getState().ensure(kind, fullId, opts.init);
111
+ }
112
+ const slice = useSyncExternalStore(
113
+ easyVisionRegistry.subscribe,
114
+ () => {
115
+ const s = easyVisionRegistry.getState().slices[fullId];
116
+ if (s) return s;
117
+ return easyVisionRegistry.getState().ensure(kind, fullId, opts.init);
118
+ },
119
+ () => easyVisionRegistry.getState().ensure(kind, fullId, opts.init)
120
+ );
121
+ useEffect(() => {
122
+ if (opts.clearWhen && opts.clearWhen(slice)) {
123
+ easyVisionRegistry.getState().drop(fullId);
124
+ easyVisionRegistry.getState().ensure(kind, fullId, opts.init);
125
+ }
126
+ }, [slice, fullId, kind, opts]);
127
+ useEffect(() => {
128
+ opts.onStateChange?.(slice);
129
+ }, [slice]);
130
+ useEffect(() => {
131
+ return () => {
132
+ if (!opts.persist) {
133
+ easyVisionRegistry.getState().drop(fullId);
134
+ }
135
+ };
136
+ }, [fullId]);
137
+ const patch = useMemo(
138
+ () => (partial) => easyVisionRegistry.getState().patch(fullId, partial),
139
+ [fullId]
140
+ );
141
+ const reset = useMemo(
142
+ () => () => {
143
+ easyVisionRegistry.getState().drop(fullId);
144
+ easyVisionRegistry.getState().ensure(kind, fullId, opts.init);
145
+ },
146
+ [fullId, kind, opts]
147
+ );
148
+ return { fullId, slice, patch, reset };
149
+ }
150
+ function useDebouncedValue(value, delayMs) {
151
+ const [debounced, setDebounced] = useState(value);
152
+ useEffect(() => {
153
+ if (delayMs <= 0) {
154
+ setDebounced(value);
155
+ return;
156
+ }
157
+ const timer = setTimeout(() => setDebounced(value), delayMs);
158
+ return () => clearTimeout(timer);
159
+ }, [value, delayMs]);
160
+ return debounced;
161
+ }
162
+ function EasyVisionInput({
163
+ id,
164
+ label,
165
+ placeholder,
166
+ debounceMs = 300,
167
+ mandatory = false,
168
+ defaultValue = "",
169
+ onChange,
170
+ onStateChange,
171
+ icon = "none",
172
+ showClearButton = false,
173
+ className,
174
+ disabled = false,
175
+ persist = false,
176
+ clearWhen
177
+ }) {
178
+ const { slice, patch } = useEasyVisionSlice("input", id, {
179
+ init: () => ({ kind: "input", value: defaultValue }),
180
+ persist,
181
+ clearWhen: clearWhen ? (s) => clearWhen(s.value) : void 0,
182
+ onStateChange: onStateChange ? (s) => onStateChange(s.value) : void 0
183
+ });
184
+ const debounced = useDebouncedValue(slice.value, debounceMs);
185
+ const lastEmittedRef = useRef(slice.value);
186
+ useEffect(() => {
187
+ if (debounced !== lastEmittedRef.current) {
188
+ lastEmittedRef.current = debounced;
189
+ onChange?.(debounced);
190
+ }
191
+ }, [debounced, onChange]);
192
+ const isInvalid = mandatory && slice.value.trim().length === 0;
193
+ return /* @__PURE__ */ jsxs("div", { className: `flex flex-col gap-1 ${className ?? ""}`, children: [
194
+ label && /* @__PURE__ */ jsxs("span", { className: "text-xs font-medium text-muted-foreground", children: [
195
+ label,
196
+ mandatory && /* @__PURE__ */ jsx("span", { className: "ml-0.5 text-destructive", children: "*" })
197
+ ] }),
198
+ /* @__PURE__ */ jsxs("div", { className: "relative", children: [
199
+ icon === "search" && /* @__PURE__ */ jsx(Search, { className: "absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground pointer-events-none" }),
200
+ /* @__PURE__ */ jsx(
201
+ Input,
202
+ {
203
+ className: `h-9 ${icon === "search" ? "pl-9" : ""} ${showClearButton && slice.value ? "pr-9" : ""} ${isInvalid ? "border-destructive focus-visible:ring-destructive/40" : ""}`,
204
+ placeholder,
205
+ value: slice.value,
206
+ onChange: (e) => patch({ value: e.target.value }),
207
+ disabled
208
+ }
209
+ ),
210
+ showClearButton && slice.value && !disabled && /* @__PURE__ */ jsx(
211
+ "button",
212
+ {
213
+ type: "button",
214
+ onClick: () => patch({ value: "" }),
215
+ className: "absolute right-2 top-1/2 -translate-y-1/2 p-0.5 hover:bg-muted rounded",
216
+ children: /* @__PURE__ */ jsx(X, { className: "w-3.5 h-3.5 text-muted-foreground" })
217
+ }
218
+ )
219
+ ] })
220
+ ] });
221
+ }
222
+ var Select = SelectPrimitive.Root;
223
+ var SelectValue = SelectPrimitive.Value;
224
+ var SelectTrigger = React8.forwardRef(({ className, children, ...props }, ref) => /* @__PURE__ */ jsxs(
225
+ SelectPrimitive.Trigger,
226
+ {
227
+ ref,
228
+ className: cn(
229
+ "flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background data-[placeholder]:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",
230
+ className
231
+ ),
232
+ ...props,
233
+ children: [
234
+ children,
235
+ /* @__PURE__ */ jsx(SelectPrimitive.Icon, { asChild: true, children: /* @__PURE__ */ jsx(ChevronDown, { className: "h-4 w-4 opacity-50" }) })
236
+ ]
237
+ }
238
+ ));
239
+ SelectTrigger.displayName = SelectPrimitive.Trigger.displayName;
240
+ var SelectScrollUpButton = React8.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
241
+ SelectPrimitive.ScrollUpButton,
242
+ {
243
+ ref,
244
+ className: cn(
245
+ "flex cursor-default items-center justify-center py-1",
246
+ className
247
+ ),
248
+ ...props,
249
+ children: /* @__PURE__ */ jsx(ChevronUp, { className: "h-4 w-4" })
250
+ }
251
+ ));
252
+ SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName;
253
+ var SelectScrollDownButton = React8.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
254
+ SelectPrimitive.ScrollDownButton,
255
+ {
256
+ ref,
257
+ className: cn(
258
+ "flex cursor-default items-center justify-center py-1",
259
+ className
260
+ ),
261
+ ...props,
262
+ children: /* @__PURE__ */ jsx(ChevronDown, { className: "h-4 w-4" })
263
+ }
264
+ ));
265
+ SelectScrollDownButton.displayName = SelectPrimitive.ScrollDownButton.displayName;
266
+ var SelectContent = React8.forwardRef(({ className, children, position = "popper", ...props }, ref) => /* @__PURE__ */ jsx(SelectPrimitive.Portal, { children: /* @__PURE__ */ jsxs(
267
+ SelectPrimitive.Content,
268
+ {
269
+ ref,
270
+ className: cn(
271
+ "relative z-50 max-h-[--radix-select-content-available-height] min-w-[8rem] overflow-y-auto overflow-x-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-select-content-transform-origin]",
272
+ position === "popper" && "data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
273
+ className
274
+ ),
275
+ position,
276
+ ...props,
277
+ children: [
278
+ /* @__PURE__ */ jsx(SelectScrollUpButton, {}),
279
+ /* @__PURE__ */ jsx(
280
+ SelectPrimitive.Viewport,
281
+ {
282
+ className: cn(
283
+ "p-1",
284
+ position === "popper" && "h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"
285
+ ),
286
+ children
287
+ }
288
+ ),
289
+ /* @__PURE__ */ jsx(SelectScrollDownButton, {})
290
+ ]
291
+ }
292
+ ) }));
293
+ SelectContent.displayName = SelectPrimitive.Content.displayName;
294
+ var SelectLabel = React8.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
295
+ SelectPrimitive.Label,
296
+ {
297
+ ref,
298
+ className: cn("py-1.5 pl-8 pr-2 text-sm font-semibold", className),
299
+ ...props
300
+ }
301
+ ));
302
+ SelectLabel.displayName = SelectPrimitive.Label.displayName;
303
+ var SelectItem = React8.forwardRef(({ className, children, ...props }, ref) => /* @__PURE__ */ jsxs(
304
+ SelectPrimitive.Item,
305
+ {
306
+ ref,
307
+ className: cn(
308
+ "relative flex w-full cursor-default select-none items-center rounded-md py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
309
+ className
310
+ ),
311
+ ...props,
312
+ children: [
313
+ /* @__PURE__ */ jsx("span", { className: "absolute left-2 flex h-3.5 w-3.5 items-center justify-center", children: /* @__PURE__ */ jsx(SelectPrimitive.ItemIndicator, { children: /* @__PURE__ */ jsx(Check, { className: "h-4 w-4" }) }) }),
314
+ /* @__PURE__ */ jsx(SelectPrimitive.ItemText, { children })
315
+ ]
316
+ }
317
+ ));
318
+ SelectItem.displayName = SelectPrimitive.Item.displayName;
319
+ var SelectSeparator = React8.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
320
+ SelectPrimitive.Separator,
321
+ {
322
+ ref,
323
+ className: cn("-mx-1 my-1 h-px bg-muted", className),
324
+ ...props
325
+ }
326
+ ));
327
+ SelectSeparator.displayName = SelectPrimitive.Separator.displayName;
328
+ var buttonVariants = cva(
329
+ "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
330
+ {
331
+ variants: {
332
+ variant: {
333
+ default: "bg-primary text-primary-foreground hover:bg-primary/90",
334
+ destructive: "bg-destructive text-destructive-foreground hover:bg-destructive/90",
335
+ outline: "border border-input bg-background hover:bg-accent hover:text-accent-foreground",
336
+ secondary: "bg-secondary text-secondary-foreground hover:bg-secondary/80",
337
+ ghost: "hover:bg-accent hover:text-accent-foreground",
338
+ link: "text-primary underline-offset-4 hover:underline"
339
+ },
340
+ size: {
341
+ default: "h-10 px-4 py-2",
342
+ sm: "h-9 rounded-md px-3",
343
+ lg: "h-11 rounded-md px-8",
344
+ icon: "h-10 w-10"
345
+ }
346
+ },
347
+ defaultVariants: {
348
+ variant: "default",
349
+ size: "default"
350
+ }
351
+ }
352
+ );
353
+ var Button = React8.forwardRef(
354
+ ({ className, variant, size, asChild = false, ...props }, ref) => {
355
+ const Comp = asChild ? Slot : "button";
356
+ return /* @__PURE__ */ jsx(
357
+ Comp,
358
+ {
359
+ className: cn(buttonVariants({ variant, size, className })),
360
+ ref,
361
+ ...props
362
+ }
363
+ );
364
+ }
365
+ );
366
+ Button.displayName = "Button";
367
+ var Popover = PopoverPrimitive.Root;
368
+ var PopoverTrigger = PopoverPrimitive.Trigger;
369
+ var PopoverContent = React8.forwardRef(({ className, align = "center", sideOffset = 4, ...props }, ref) => /* @__PURE__ */ jsx(PopoverPrimitive.Portal, { children: /* @__PURE__ */ jsx(
370
+ PopoverPrimitive.Content,
371
+ {
372
+ ref,
373
+ align,
374
+ sideOffset,
375
+ className: cn(
376
+ "z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-popover-content-transform-origin]",
377
+ className
378
+ ),
379
+ ...props
380
+ }
381
+ ) }));
382
+ PopoverContent.displayName = PopoverPrimitive.Content.displayName;
383
+ var Command = React8.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
384
+ Command$1,
385
+ {
386
+ ref,
387
+ className: cn(
388
+ "flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",
389
+ className
390
+ ),
391
+ ...props
392
+ }
393
+ ));
394
+ Command.displayName = Command$1.displayName;
395
+ var CommandInput = React8.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsxs("div", { className: "flex items-center border-b px-3", "cmdk-input-wrapper": "", children: [
396
+ /* @__PURE__ */ jsx(MagnifyingGlassIcon, { className: "mr-2 h-4 w-4 shrink-0 opacity-50" }),
397
+ /* @__PURE__ */ jsx(
398
+ Command$1.Input,
399
+ {
400
+ ref,
401
+ className: cn(
402
+ "flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",
403
+ className
404
+ ),
405
+ ...props
406
+ }
407
+ )
408
+ ] }));
409
+ CommandInput.displayName = Command$1.Input.displayName;
410
+ var CommandList = React8.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
411
+ Command$1.List,
412
+ {
413
+ ref,
414
+ className: cn("max-h-[300px] overflow-y-auto overflow-x-hidden", className),
415
+ ...props
416
+ }
417
+ ));
418
+ CommandList.displayName = Command$1.List.displayName;
419
+ var CommandEmpty = React8.forwardRef((props, ref) => /* @__PURE__ */ jsx(
420
+ Command$1.Empty,
421
+ {
422
+ ref,
423
+ className: "py-6 text-center text-sm",
424
+ ...props
425
+ }
426
+ ));
427
+ CommandEmpty.displayName = Command$1.Empty.displayName;
428
+ var CommandGroup = React8.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
429
+ Command$1.Group,
430
+ {
431
+ ref,
432
+ className: cn(
433
+ "overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",
434
+ className
435
+ ),
436
+ ...props
437
+ }
438
+ ));
439
+ CommandGroup.displayName = Command$1.Group.displayName;
440
+ var CommandSeparator = React8.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
441
+ Command$1.Separator,
442
+ {
443
+ ref,
444
+ className: cn("-mx-1 h-px bg-border", className),
445
+ ...props
446
+ }
447
+ ));
448
+ CommandSeparator.displayName = Command$1.Separator.displayName;
449
+ var CommandItem = React8.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
450
+ Command$1.Item,
451
+ {
452
+ ref,
453
+ className: cn(
454
+ "relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50",
455
+ className
456
+ ),
457
+ ...props
458
+ }
459
+ ));
460
+ CommandItem.displayName = Command$1.Item.displayName;
461
+ var SENTINEL_UNDEFINED = "__easyvision_undef__";
462
+ function EasyVisionSelector({
463
+ id,
464
+ label,
465
+ options,
466
+ placeholder = "Seleccionar...",
467
+ mandatory = false,
468
+ defaultValue,
469
+ confirmMode = false,
470
+ confirmLabel = "Confirmar",
471
+ searchable = false,
472
+ onChange,
473
+ onStateChange,
474
+ className,
475
+ disabled = false,
476
+ persist = false,
477
+ clearWhen
478
+ }) {
479
+ const { slice, patch } = useEasyVisionSlice("selector", id, {
480
+ init: () => ({ kind: "selector", value: defaultValue }),
481
+ persist,
482
+ clearWhen: clearWhen ? (s) => clearWhen(s.value) : void 0,
483
+ onStateChange: onStateChange ? (s) => onStateChange(s.value) : void 0
484
+ });
485
+ const value = slice.value;
486
+ const [resolved, setResolved] = useState(
487
+ Array.isArray(options) ? options : null
488
+ );
489
+ useEffect(() => {
490
+ if (typeof options === "function" && resolved === null) {
491
+ void options().then(setResolved).catch(() => setResolved([]));
492
+ } else if (Array.isArray(options)) {
493
+ setResolved(options);
494
+ }
495
+ }, [options, resolved]);
496
+ const opts = resolved ?? [];
497
+ const [pending, setPending] = useState(value);
498
+ useEffect(() => setPending(value), [value]);
499
+ const lastEmittedRef = useRef(value);
500
+ useEffect(() => {
501
+ if (value !== lastEmittedRef.current) {
502
+ lastEmittedRef.current = value;
503
+ onChange?.(value);
504
+ }
505
+ }, [value, onChange]);
506
+ const isInvalid = mandatory && (value === void 0 || value === "");
507
+ const commit = (v) => patch({ value: v });
508
+ const triggerClasses = `${isInvalid ? "border-destructive focus-visible:ring-destructive/40" : ""} ${className ?? ""}`;
509
+ if (searchable) {
510
+ const labelOf = (v) => opts.find((o) => o.value === v)?.label ?? "";
511
+ return /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1", children: [
512
+ label && /* @__PURE__ */ jsxs("span", { className: "text-xs font-medium text-muted-foreground", children: [
513
+ label,
514
+ mandatory && /* @__PURE__ */ jsx("span", { className: "ml-0.5 text-destructive", children: "*" })
515
+ ] }),
516
+ /* @__PURE__ */ jsxs(Popover, { children: [
517
+ /* @__PURE__ */ jsx(PopoverTrigger, { asChild: true, children: /* @__PURE__ */ jsxs(
518
+ Button,
519
+ {
520
+ variant: "outline",
521
+ role: "combobox",
522
+ disabled,
523
+ className: `h-10 justify-between font-normal ${triggerClasses}`,
524
+ children: [
525
+ value !== void 0 && value !== "" ? labelOf(value) : /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: placeholder }),
526
+ /* @__PURE__ */ jsx(ChevronsUpDown, { className: "ml-2 h-4 w-4 shrink-0 opacity-50" })
527
+ ]
528
+ }
529
+ ) }),
530
+ /* @__PURE__ */ jsx(PopoverContent, { className: "w-[var(--radix-popover-trigger-width)] p-0", align: "start", children: /* @__PURE__ */ jsxs(Command, { children: [
531
+ /* @__PURE__ */ jsx(CommandInput, { placeholder: "Buscar..." }),
532
+ /* @__PURE__ */ jsxs(CommandList, { children: [
533
+ /* @__PURE__ */ jsx(CommandEmpty, { children: "Sin resultados" }),
534
+ /* @__PURE__ */ jsx(CommandGroup, { children: opts.map((o) => /* @__PURE__ */ jsxs(
535
+ CommandItem,
536
+ {
537
+ value: o.label,
538
+ onSelect: () => commit(o.value),
539
+ children: [
540
+ /* @__PURE__ */ jsx(Check, { className: `mr-2 h-4 w-4 ${value === o.value ? "opacity-100" : "opacity-0"}` }),
541
+ o.label
542
+ ]
543
+ },
544
+ String(o.value)
545
+ )) })
546
+ ] })
547
+ ] }) })
548
+ ] })
549
+ ] });
550
+ }
551
+ const selectValue = value === void 0 || value === "" ? SENTINEL_UNDEFINED : String(value);
552
+ const onValueChange = (raw) => {
553
+ if (raw === SENTINEL_UNDEFINED) {
554
+ if (confirmMode) setPending(void 0);
555
+ else commit(void 0);
556
+ return;
557
+ }
558
+ const matched = opts.find((o) => String(o.value) === raw);
559
+ const next = matched?.value;
560
+ if (confirmMode) setPending(next);
561
+ else commit(next);
562
+ };
563
+ return /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1", children: [
564
+ label && /* @__PURE__ */ jsxs("span", { className: "text-xs font-medium text-muted-foreground", children: [
565
+ label,
566
+ mandatory && /* @__PURE__ */ jsx("span", { className: "ml-0.5 text-destructive", children: "*" })
567
+ ] }),
568
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
569
+ /* @__PURE__ */ jsxs(Select, { value: selectValue, onValueChange, disabled, children: [
570
+ /* @__PURE__ */ jsx(SelectTrigger, { className: triggerClasses, children: /* @__PURE__ */ jsx(SelectValue, { placeholder }) }),
571
+ /* @__PURE__ */ jsx(SelectContent, { children: opts.map((o) => /* @__PURE__ */ jsx(SelectItem, { value: String(o.value), children: o.label }, String(o.value))) })
572
+ ] }),
573
+ !mandatory && value !== void 0 && value !== "" && !disabled && /* @__PURE__ */ jsx(
574
+ "button",
575
+ {
576
+ type: "button",
577
+ onClick: () => confirmMode ? setPending(void 0) : commit(void 0),
578
+ className: "p-1 hover:bg-muted rounded",
579
+ "aria-label": "Limpiar",
580
+ children: /* @__PURE__ */ jsx(X, { className: "h-3.5 w-3.5 text-muted-foreground" })
581
+ }
582
+ ),
583
+ confirmMode && pending !== value && /* @__PURE__ */ jsx(Button, { size: "sm", onClick: () => commit(pending), children: confirmLabel })
584
+ ] })
585
+ ] });
586
+ }
587
+ function TextWidget({ definition, value, onChange, onRemove }) {
588
+ return /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 rounded-md border border-border bg-card px-3 py-1.5", children: [
589
+ /* @__PURE__ */ jsxs("span", { className: "text-xs font-medium text-muted-foreground whitespace-nowrap", children: [
590
+ definition.label,
591
+ definition.mandatory && /* @__PURE__ */ jsx("span", { className: "ml-0.5 text-destructive", children: "*" }),
592
+ ":"
593
+ ] }),
594
+ /* @__PURE__ */ jsx(
595
+ Input,
596
+ {
597
+ className: "h-7 min-w-[112px] w-28 border-0 bg-transparent p-0 px-2 text-xs focus-visible:ring-0 focus-visible:ring-offset-0",
598
+ placeholder: definition.placeholder,
599
+ value: value ?? "",
600
+ onChange: (e) => onChange(e.target.value)
601
+ }
602
+ ),
603
+ onRemove && /* @__PURE__ */ jsx(
604
+ "button",
605
+ {
606
+ type: "button",
607
+ onClick: onRemove,
608
+ className: "ml-1 p-0.5 hover:bg-muted rounded transition-colors",
609
+ children: /* @__PURE__ */ jsx(X, { className: "w-3.5 h-3.5 text-muted-foreground" })
610
+ }
611
+ )
612
+ ] });
613
+ }
614
+ var SENTINEL = "__easyvision_undef__";
615
+ function SelectorWidget({ definition, value, onChange, onRemove }) {
616
+ const [resolved, setResolved] = useState(
617
+ Array.isArray(definition.options) ? definition.options : null
618
+ );
619
+ useEffect(() => {
620
+ if (typeof definition.options === "function" && resolved === null) {
621
+ void definition.options().then((o) => setResolved(o)).catch(() => setResolved([]));
622
+ } else if (Array.isArray(definition.options)) {
623
+ setResolved(definition.options);
624
+ }
625
+ }, [definition.options, resolved]);
626
+ const opts = resolved ?? [];
627
+ const selectValue = value === void 0 || value === "" ? SENTINEL : String(value);
628
+ return /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 rounded-md border border-border bg-card px-3 py-1.5", children: [
629
+ /* @__PURE__ */ jsxs("span", { className: "text-xs font-medium text-muted-foreground whitespace-nowrap", children: [
630
+ definition.label,
631
+ definition.mandatory && /* @__PURE__ */ jsx("span", { className: "ml-0.5 text-destructive", children: "*" }),
632
+ ":"
633
+ ] }),
634
+ /* @__PURE__ */ jsxs(
635
+ Select,
636
+ {
637
+ value: selectValue,
638
+ onValueChange: (raw) => {
639
+ if (raw === SENTINEL) onChange(void 0);
640
+ else {
641
+ const matched = opts.find((o) => String(o.value) === raw);
642
+ onChange(matched?.value);
643
+ }
644
+ },
645
+ children: [
646
+ /* @__PURE__ */ jsx(SelectTrigger, { className: "h-7 min-w-[120px] border-0 bg-transparent p-0 px-2 text-xs focus:ring-0 focus:ring-offset-0", children: /* @__PURE__ */ jsx(SelectValue, { placeholder: definition.placeholder ?? "Seleccionar" }) }),
647
+ /* @__PURE__ */ jsx(SelectContent, { children: opts.map((o) => /* @__PURE__ */ jsx(SelectItem, { value: String(o.value), children: o.label }, String(o.value))) })
648
+ ]
649
+ }
650
+ ),
651
+ onRemove && /* @__PURE__ */ jsx(
652
+ "button",
653
+ {
654
+ type: "button",
655
+ onClick: onRemove,
656
+ className: "ml-1 p-0.5 hover:bg-muted rounded transition-colors",
657
+ children: /* @__PURE__ */ jsx(X, { className: "w-3.5 h-3.5 text-muted-foreground" })
658
+ }
659
+ )
660
+ ] });
661
+ }
662
+ var Checkbox = React8.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
663
+ CheckboxPrimitive.Root,
664
+ {
665
+ ref,
666
+ className: cn(
667
+ "peer h-4 w-4 shrink-0 rounded border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground flex items-center justify-center",
668
+ className
669
+ ),
670
+ ...props,
671
+ children: /* @__PURE__ */ jsx(
672
+ CheckboxPrimitive.Indicator,
673
+ {
674
+ className: cn("flex items-center justify-center text-current w-full h-full"),
675
+ children: /* @__PURE__ */ jsx(Check, { className: "h-3 w-3" })
676
+ }
677
+ )
678
+ }
679
+ ));
680
+ Checkbox.displayName = CheckboxPrimitive.Root.displayName;
681
+ function MultiSelectWidget({
682
+ definition,
683
+ value,
684
+ onChange,
685
+ onRemove
686
+ }) {
687
+ const [search, setSearch] = useState("");
688
+ const [resolved, setResolved] = useState(
689
+ Array.isArray(definition.options) ? definition.options : null
690
+ );
691
+ useEffect(() => {
692
+ if (typeof definition.options === "function" && resolved === null) {
693
+ void definition.options().then(setResolved).catch(() => setResolved([]));
694
+ } else if (Array.isArray(definition.options)) {
695
+ setResolved(definition.options);
696
+ }
697
+ }, [definition.options, resolved]);
698
+ const selected = Array.isArray(value) ? value : [];
699
+ const opts = resolved ?? [];
700
+ const filtered = useMemo(
701
+ () => opts.filter((o) => o.label.toLowerCase().includes(search.toLowerCase())),
702
+ [opts, search]
703
+ );
704
+ const toggle = (v) => {
705
+ onChange(selected.includes(v) ? selected.filter((x) => x !== v) : [...selected, v]);
706
+ };
707
+ const removeOne = (v) => onChange(selected.filter((x) => x !== v));
708
+ const labelOf = (v) => opts.find((o) => o.value === v)?.label ?? String(v);
709
+ return /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1.5 rounded-md border border-border bg-card px-2 py-1 flex-wrap", children: [
710
+ /* @__PURE__ */ jsxs("span", { className: "text-xs font-medium text-muted-foreground whitespace-nowrap", children: [
711
+ definition.label,
712
+ definition.mandatory && /* @__PURE__ */ jsx("span", { className: "ml-0.5 text-destructive", children: "*" }),
713
+ ":"
714
+ ] }),
715
+ selected.map((v) => /* @__PURE__ */ jsxs(
716
+ "span",
717
+ {
718
+ className: "inline-flex items-center gap-1 bg-primary/10 text-primary text-xs px-2 py-0.5 rounded-md",
719
+ children: [
720
+ labelOf(v),
721
+ /* @__PURE__ */ jsx(
722
+ "button",
723
+ {
724
+ type: "button",
725
+ onClick: () => removeOne(v),
726
+ className: "p-0.5 hover:bg-muted rounded",
727
+ children: /* @__PURE__ */ jsx(X, { className: "h-3 w-3" })
728
+ }
729
+ )
730
+ ]
731
+ },
732
+ String(v)
733
+ )),
734
+ /* @__PURE__ */ jsxs(Popover, { children: [
735
+ /* @__PURE__ */ jsx(PopoverTrigger, { asChild: true, children: /* @__PURE__ */ jsx(
736
+ "button",
737
+ {
738
+ type: "button",
739
+ className: "flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",
740
+ children: /* @__PURE__ */ jsx(ChevronDown, { className: "h-3.5 w-3.5" })
741
+ }
742
+ ) }),
743
+ /* @__PURE__ */ jsxs(PopoverContent, { className: "w-56 p-2", align: "start", children: [
744
+ /* @__PURE__ */ jsx(
745
+ Input,
746
+ {
747
+ className: "mb-2 h-8 text-xs",
748
+ placeholder: "Buscar...",
749
+ value: search,
750
+ onChange: (e) => setSearch(e.target.value)
751
+ }
752
+ ),
753
+ /* @__PURE__ */ jsxs("div", { className: "max-h-48 overflow-y-auto", children: [
754
+ filtered.map((o) => /* @__PURE__ */ jsxs(
755
+ "label",
756
+ {
757
+ className: "flex cursor-pointer items-center gap-2 rounded-sm px-2 py-1.5 text-xs hover:bg-muted",
758
+ children: [
759
+ /* @__PURE__ */ jsx(
760
+ Checkbox,
761
+ {
762
+ checked: selected.includes(o.value),
763
+ onCheckedChange: () => toggle(o.value)
764
+ }
765
+ ),
766
+ o.label
767
+ ]
768
+ },
769
+ String(o.value)
770
+ )),
771
+ filtered.length === 0 && /* @__PURE__ */ jsx("p", { className: "px-2 py-1 text-xs text-muted-foreground", children: "Sin opciones" })
772
+ ] })
773
+ ] })
774
+ ] }),
775
+ onRemove && /* @__PURE__ */ jsx(
776
+ "button",
777
+ {
778
+ type: "button",
779
+ onClick: onRemove,
780
+ className: "ml-1 p-0.5 hover:bg-muted rounded transition-colors",
781
+ children: /* @__PURE__ */ jsx(X, { className: "w-3.5 h-3.5 text-muted-foreground" })
782
+ }
783
+ )
784
+ ] });
785
+ }
786
+ function Calendar({
787
+ className,
788
+ classNames,
789
+ showOutsideDays = true,
790
+ ...props
791
+ }) {
792
+ return /* @__PURE__ */ jsx(
793
+ DayPicker,
794
+ {
795
+ showOutsideDays,
796
+ className: cn("p-3", className),
797
+ classNames: {
798
+ months: "flex flex-col sm:flex-row space-y-4 sm:space-x-4 sm:space-y-0",
799
+ month: "space-y-4",
800
+ caption: "flex justify-center pt-1 relative items-center",
801
+ caption_label: "text-sm font-medium",
802
+ nav: "space-x-1 flex items-center",
803
+ nav_button: cn(
804
+ buttonVariants({ variant: "outline" }),
805
+ "h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100"
806
+ ),
807
+ nav_button_previous: "absolute left-1",
808
+ nav_button_next: "absolute right-1",
809
+ table: "w-full border-collapse space-y-1",
810
+ head_row: "flex",
811
+ head_cell: "text-muted-foreground rounded-md w-9 font-normal text-[0.8rem]",
812
+ row: "flex w-full mt-2",
813
+ cell: "h-9 w-9 text-center text-sm p-0 relative [&:has([aria-selected].day-range-end)]:rounded-r-md [&:has([aria-selected].day-outside)]:bg-accent/50 [&:has([aria-selected])]:bg-accent first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md focus-within:relative focus-within:z-20",
814
+ day: cn(
815
+ buttonVariants({ variant: "ghost" }),
816
+ "h-9 w-9 p-0 font-normal aria-selected:opacity-100"
817
+ ),
818
+ day_range_end: "day-range-end",
819
+ day_selected: "bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground",
820
+ day_today: "bg-accent text-accent-foreground",
821
+ day_outside: "day-outside text-muted-foreground aria-selected:bg-accent/50 aria-selected:text-muted-foreground",
822
+ day_disabled: "text-muted-foreground opacity-50",
823
+ day_range_middle: "aria-selected:bg-accent aria-selected:text-accent-foreground",
824
+ day_hidden: "invisible",
825
+ ...classNames
826
+ },
827
+ components: {
828
+ IconLeft: ({ className: className2, ...props2 }) => /* @__PURE__ */ jsx(ChevronLeft, { className: cn("h-4 w-4", className2), ...props2 }),
829
+ IconRight: ({ className: className2, ...props2 }) => /* @__PURE__ */ jsx(ChevronRight, { className: cn("h-4 w-4", className2), ...props2 })
830
+ },
831
+ ...props
832
+ }
833
+ );
834
+ }
835
+ Calendar.displayName = "Calendar";
836
+ function DateRangeWidget({
837
+ definition,
838
+ value,
839
+ onChange,
840
+ onRemove
841
+ }) {
842
+ const range = value ?? {};
843
+ const label = (() => {
844
+ if (range.from && range.to) {
845
+ return `${format(range.from, "dd/MM/yy", { locale: es })} - ${format(range.to, "dd/MM/yy", { locale: es })}`;
846
+ }
847
+ if (range.from) return `Desde ${format(range.from, "dd/MM/yy", { locale: es })}`;
848
+ if (range.to) return `Hasta ${format(range.to, "dd/MM/yy", { locale: es })}`;
849
+ return definition.placeholder ?? "Seleccionar rango";
850
+ })();
851
+ return /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 rounded-md border border-border bg-card px-3 py-1.5", children: [
852
+ /* @__PURE__ */ jsxs("span", { className: "text-xs font-medium text-muted-foreground whitespace-nowrap", children: [
853
+ definition.label,
854
+ definition.mandatory && /* @__PURE__ */ jsx("span", { className: "ml-0.5 text-destructive", children: "*" }),
855
+ ":"
856
+ ] }),
857
+ /* @__PURE__ */ jsxs(Popover, { children: [
858
+ /* @__PURE__ */ jsx(PopoverTrigger, { asChild: true, children: /* @__PURE__ */ jsxs(
859
+ "button",
860
+ {
861
+ type: "button",
862
+ className: "flex items-center gap-1.5 text-xs hover:text-foreground",
863
+ children: [
864
+ /* @__PURE__ */ jsx(Calendar$1, { className: "h-3.5 w-3.5" }),
865
+ /* @__PURE__ */ jsx("span", { children: label })
866
+ ]
867
+ }
868
+ ) }),
869
+ /* @__PURE__ */ jsx(PopoverContent, { className: "w-auto p-0", align: "start", children: /* @__PURE__ */ jsx(
870
+ Calendar,
871
+ {
872
+ mode: "range",
873
+ selected: { from: range.from, to: range.to },
874
+ onSelect: (r) => onChange({ from: r?.from, to: r?.to }),
875
+ numberOfMonths: 2,
876
+ locale: es
877
+ }
878
+ ) })
879
+ ] }),
880
+ onRemove && /* @__PURE__ */ jsx(
881
+ "button",
882
+ {
883
+ type: "button",
884
+ onClick: onRemove,
885
+ className: "ml-1 p-0.5 hover:bg-muted rounded transition-colors",
886
+ children: /* @__PURE__ */ jsx(X, { className: "w-3.5 h-3.5 text-muted-foreground" })
887
+ }
888
+ )
889
+ ] });
890
+ }
891
+ function NumberRangeWidget({
892
+ definition,
893
+ value,
894
+ onChange,
895
+ onRemove
896
+ }) {
897
+ const range = value ?? {};
898
+ return /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 rounded-md border border-border bg-card px-3 py-1.5", children: [
899
+ /* @__PURE__ */ jsxs("span", { className: "text-xs font-medium text-muted-foreground whitespace-nowrap", children: [
900
+ definition.label,
901
+ definition.mandatory && /* @__PURE__ */ jsx("span", { className: "ml-0.5 text-destructive", children: "*" }),
902
+ ":"
903
+ ] }),
904
+ /* @__PURE__ */ jsx(
905
+ Input,
906
+ {
907
+ type: "number",
908
+ className: "h-7 w-20 border-0 bg-transparent p-0 px-2 text-xs focus-visible:ring-0 focus-visible:ring-offset-0",
909
+ placeholder: "Min",
910
+ value: range.min ?? "",
911
+ onChange: (e) => onChange({ ...range, min: e.target.value ? Number(e.target.value) : void 0 })
912
+ }
913
+ ),
914
+ /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: "\u2014" }),
915
+ /* @__PURE__ */ jsx(
916
+ Input,
917
+ {
918
+ type: "number",
919
+ className: "h-7 w-20 border-0 bg-transparent p-0 px-2 text-xs focus-visible:ring-0 focus-visible:ring-offset-0",
920
+ placeholder: "Max",
921
+ value: range.max ?? "",
922
+ onChange: (e) => onChange({ ...range, max: e.target.value ? Number(e.target.value) : void 0 })
923
+ }
924
+ ),
925
+ onRemove && /* @__PURE__ */ jsx(
926
+ "button",
927
+ {
928
+ type: "button",
929
+ onClick: onRemove,
930
+ className: "ml-1 p-0.5 hover:bg-muted rounded transition-colors",
931
+ children: /* @__PURE__ */ jsx(X, { className: "w-3.5 h-3.5 text-muted-foreground" })
932
+ }
933
+ )
934
+ ] });
935
+ }
936
+ function MultifilterField({
937
+ definition,
938
+ value,
939
+ onChange,
940
+ onRemove
941
+ }) {
942
+ switch (definition.type) {
943
+ case "text":
944
+ return /* @__PURE__ */ jsx(
945
+ TextWidget,
946
+ {
947
+ definition,
948
+ value,
949
+ onChange: (v) => onChange(v),
950
+ onRemove
951
+ }
952
+ );
953
+ case "selector":
954
+ return /* @__PURE__ */ jsx(
955
+ SelectorWidget,
956
+ {
957
+ definition,
958
+ value,
959
+ onChange: (v) => onChange(v),
960
+ onRemove
961
+ }
962
+ );
963
+ case "multiselect":
964
+ return /* @__PURE__ */ jsx(
965
+ MultiSelectWidget,
966
+ {
967
+ definition,
968
+ value,
969
+ onChange: (v) => onChange(v),
970
+ onRemove
971
+ }
972
+ );
973
+ case "dateRange":
974
+ return /* @__PURE__ */ jsx(
975
+ DateRangeWidget,
976
+ {
977
+ definition,
978
+ value,
979
+ onChange: (v) => onChange(v),
980
+ onRemove
981
+ }
982
+ );
983
+ case "numberRange":
984
+ return /* @__PURE__ */ jsx(
985
+ NumberRangeWidget,
986
+ {
987
+ definition,
988
+ value,
989
+ onChange: (v) => onChange(v),
990
+ onRemove
991
+ }
992
+ );
993
+ case "custom": {
994
+ const Component = definition.component;
995
+ return /* @__PURE__ */ jsx(
996
+ Component,
997
+ {
998
+ definition,
999
+ value,
1000
+ onChange,
1001
+ onRemove: onRemove ?? (() => {
1002
+ })
1003
+ }
1004
+ );
1005
+ }
1006
+ case "multifilter":
1007
+ return null;
1008
+ default:
1009
+ return null;
1010
+ }
1011
+ }
1012
+ function buildCondition(def, value) {
1013
+ if (value === void 0 || value === null || value === "") return void 0;
1014
+ const mapper = def.toCondition ?? def.transform;
1015
+ if (mapper) {
1016
+ const mapped = mapper(value);
1017
+ if (mapped === void 0 || mapped === null) return void 0;
1018
+ if (typeof mapped === "object" && !Array.isArray(mapped) && ("$or" in mapped || "$and" in mapped)) {
1019
+ return mapped;
1020
+ }
1021
+ if (def.field) return { [def.field]: mapped };
1022
+ return void 0;
1023
+ }
1024
+ if (!def.field) return void 0;
1025
+ switch (def.type) {
1026
+ case "text": {
1027
+ const str = String(value).trim();
1028
+ if (!str) return void 0;
1029
+ return { [def.field]: { $regex: `.*${str}.*`, $options: "i" } };
1030
+ }
1031
+ case "selector": {
1032
+ return { [def.field]: value };
1033
+ }
1034
+ case "multiselect": {
1035
+ const arr = value;
1036
+ if (!Array.isArray(arr) || arr.length === 0) return void 0;
1037
+ return { [def.field]: { $in: arr } };
1038
+ }
1039
+ case "dateRange": {
1040
+ const r = value;
1041
+ if (!r?.from && !r?.to) return void 0;
1042
+ const cond = {};
1043
+ if (r.from) cond.$gte = r.from.toISOString();
1044
+ if (r.to) cond.$lte = r.to.toISOString();
1045
+ return { [def.field]: cond };
1046
+ }
1047
+ case "numberRange": {
1048
+ const r = value;
1049
+ if (r?.min == null && r?.max == null) return void 0;
1050
+ const cond = {};
1051
+ if (r.min != null) cond.$gte = r.min;
1052
+ if (r.max != null) cond.$lte = r.max;
1053
+ return { [def.field]: cond };
1054
+ }
1055
+ default:
1056
+ return void 0;
1057
+ }
1058
+ }
1059
+ function useBuildQuery(config, values, childQueries) {
1060
+ return useCallback(() => {
1061
+ const where = {};
1062
+ if (config.searchField) {
1063
+ const c = buildCondition(config.searchField, values[config.searchField.id]);
1064
+ if (c) Object.assign(where, c);
1065
+ }
1066
+ for (const def of config.fields) {
1067
+ if (def.type === "multifilter") {
1068
+ const childWhere = childQueries[def.id]?.where;
1069
+ if (childWhere) Object.assign(where, childWhere);
1070
+ continue;
1071
+ }
1072
+ const c = buildCondition(def, values[def.id]);
1073
+ if (c) Object.assign(where, c);
1074
+ }
1075
+ const out = {};
1076
+ if (Object.keys(where).length > 0) out.where = where;
1077
+ if (config.defaultOrder) out.order = config.defaultOrder;
1078
+ if (config.defaultLimit) out.limit = config.defaultLimit;
1079
+ return out;
1080
+ }, [config, values, childQueries]);
1081
+ }
1082
+
1083
+ // lib/stableStringify.ts
1084
+ function stableStringify(value) {
1085
+ return JSON.stringify(normalize(value));
1086
+ }
1087
+ function normalize(value) {
1088
+ if (value === void 0) return void 0;
1089
+ if (value === null) return null;
1090
+ if (value instanceof Date) return value.toISOString();
1091
+ if (Array.isArray(value)) return value.map(normalize);
1092
+ if (typeof value === "object") {
1093
+ const obj = value;
1094
+ const out = {};
1095
+ for (const key of Object.keys(obj).sort()) {
1096
+ const norm = normalize(obj[key]);
1097
+ if (norm !== void 0) out[key] = norm;
1098
+ }
1099
+ return out;
1100
+ }
1101
+ return value;
1102
+ }
1103
+
1104
+ // multifilter/hooks/useDirtyTracking.ts
1105
+ function isNonEmpty(value) {
1106
+ if (value === void 0 || value === null) return false;
1107
+ if (typeof value === "string") return value.trim().length > 0;
1108
+ if (Array.isArray(value)) return value.length > 0;
1109
+ if (typeof value === "object") {
1110
+ const obj = value;
1111
+ if ("from" in obj || "to" in obj) {
1112
+ return obj.from !== void 0 || obj.to !== void 0;
1113
+ }
1114
+ if ("min" in obj || "max" in obj) {
1115
+ return obj.min !== void 0 || obj.max !== void 0;
1116
+ }
1117
+ return Object.values(obj).some(isNonEmpty);
1118
+ }
1119
+ return true;
1120
+ }
1121
+ function buildSnapshotKey(input) {
1122
+ const filtered = {};
1123
+ for (const key of Object.keys(input.values)) {
1124
+ if (isNonEmpty(input.values[key])) {
1125
+ filtered[key] = input.values[key];
1126
+ }
1127
+ }
1128
+ return stableStringify({
1129
+ activeFields: [...input.activeFields].sort(),
1130
+ values: filtered
1131
+ });
1132
+ }
1133
+ function isDirty(input, lastConfirmed) {
1134
+ const current = buildSnapshotKey(input);
1135
+ if (lastConfirmed === null) {
1136
+ return Object.values(input.values).some(isNonEmpty);
1137
+ }
1138
+ return current !== lastConfirmed;
1139
+ }
1140
+ var DEFAULT_LABELS = {
1141
+ search: "Buscar",
1142
+ clear: "Limpiar",
1143
+ perform: "Buscar",
1144
+ addFilter: "A\xF1adir filtro",
1145
+ noOptions: "Sin opciones",
1146
+ searchPlaceholder: "Buscar..."
1147
+ };
1148
+ function isFieldVisible(def, values) {
1149
+ if (def.visible === void 0) return true;
1150
+ if (typeof def.visible === "boolean") return def.visible;
1151
+ return def.visible(values);
1152
+ }
1153
+ function isMandatorySatisfied(def, value) {
1154
+ if (!def.mandatory) return true;
1155
+ return isNonEmpty(value);
1156
+ }
1157
+ var EasyVisionMultifilter = forwardRef(function EasyVisionMultifilter2(props, ref) {
1158
+ const {
1159
+ id,
1160
+ config,
1161
+ editable = true,
1162
+ performButton = false,
1163
+ performLabel,
1164
+ performIcon,
1165
+ performPosition = "inline",
1166
+ performTargetRef,
1167
+ performOnMount = false,
1168
+ onPerform,
1169
+ onChange,
1170
+ onStateChange,
1171
+ showClearAll,
1172
+ labels: labelOverrides,
1173
+ className,
1174
+ persist = false,
1175
+ clearWhen
1176
+ } = props;
1177
+ const labels = { ...DEFAULT_LABELS, ...labelOverrides };
1178
+ const showClear = showClearAll ?? editable;
1179
+ const initialActive = useMemo(() => {
1180
+ const ids = [];
1181
+ if (config.searchField) ids.push(config.searchField.id);
1182
+ for (const f of config.fields) {
1183
+ if (f.pinned || f.initiallyActive) ids.push(f.id);
1184
+ }
1185
+ return ids;
1186
+ }, [config]);
1187
+ const initialValues = useMemo(() => {
1188
+ const v = {};
1189
+ if (config.searchField?.defaultValue !== void 0) {
1190
+ v[config.searchField.id] = config.searchField.defaultValue;
1191
+ }
1192
+ for (const f of config.fields) {
1193
+ if (f.defaultValue !== void 0) v[f.id] = f.defaultValue;
1194
+ }
1195
+ return v;
1196
+ }, [config]);
1197
+ const { slice, fullId, patch } = useEasyVisionSlice("multifilter", id, {
1198
+ init: () => ({
1199
+ kind: "multifilter",
1200
+ activeFields: initialActive,
1201
+ values: initialValues,
1202
+ lastConfirmedSnapshotJSON: null
1203
+ }),
1204
+ persist,
1205
+ clearWhen: clearWhen ? (s) => clearWhen({
1206
+ values: s.values,
1207
+ activeFields: s.activeFields,
1208
+ isValid: false,
1209
+ isDirty: false,
1210
+ query: {}
1211
+ }) : void 0
1212
+ });
1213
+ const { activeFields, values, lastConfirmedSnapshotJSON } = slice;
1214
+ const [childTick, setChildTick] = useState(0);
1215
+ useEffect(() => {
1216
+ const unsub = easyVisionRegistry.subscribe(() => setChildTick((t) => t + 1));
1217
+ return unsub;
1218
+ }, []);
1219
+ const childSnapshots = useMemo(() => {
1220
+ const out = {};
1221
+ for (const f of config.fields) {
1222
+ if (f.type !== "multifilter") continue;
1223
+ const childFullId = `${fullId}.${f.id}-multifilter`;
1224
+ const childSlice = easyVisionRegistry.getState().slices[childFullId];
1225
+ if (childSlice) {
1226
+ out[f.id] = {
1227
+ values: childSlice.values,
1228
+ activeFields: childSlice.activeFields
1229
+ };
1230
+ }
1231
+ }
1232
+ return out;
1233
+ }, [fullId, config.fields, childTick]);
1234
+ const childQueries = useMemo(() => {
1235
+ const out = {};
1236
+ for (const f of config.fields) {
1237
+ if (f.type !== "multifilter") continue;
1238
+ const childSnap = childSnapshots[f.id];
1239
+ if (!childSnap) continue;
1240
+ out[f.id] = buildChildQueryDirect(f, childSnap.values);
1241
+ }
1242
+ return out;
1243
+ }, [config.fields, childSnapshots]);
1244
+ const buildQuery = useBuildQuery(config, values, childQueries);
1245
+ const composedValues = useMemo(() => {
1246
+ const out = { ...values };
1247
+ for (const f of config.fields) {
1248
+ if (f.type === "multifilter") {
1249
+ out[f.id] = childSnapshots[f.id]?.values ?? {};
1250
+ }
1251
+ }
1252
+ return out;
1253
+ }, [values, config.fields, childSnapshots]);
1254
+ const isValid = useMemo(() => {
1255
+ if (config.searchField && !isMandatorySatisfied(config.searchField, values[config.searchField.id])) {
1256
+ return false;
1257
+ }
1258
+ for (const f of config.fields) {
1259
+ if (f.type === "multifilter") {
1260
+ const childSnap = childSnapshots[f.id];
1261
+ if (!childSnap) {
1262
+ continue;
1263
+ }
1264
+ for (const cf of f.config.fields) {
1265
+ if (cf.mandatory && !isMandatorySatisfied(cf, childSnap.values[cf.id])) return false;
1266
+ }
1267
+ if (f.config.searchField?.mandatory && !isMandatorySatisfied(f.config.searchField, childSnap.values[f.config.searchField.id])) {
1268
+ return false;
1269
+ }
1270
+ } else if (!isMandatorySatisfied(f, values[f.id])) {
1271
+ return false;
1272
+ }
1273
+ }
1274
+ return true;
1275
+ }, [config, values, childSnapshots]);
1276
+ const snapshotKey = useMemo(
1277
+ () => buildSnapshotKey({ activeFields, values: composedValues }),
1278
+ [activeFields, composedValues]
1279
+ );
1280
+ const dirty = useMemo(
1281
+ () => isDirty({ activeFields, values: composedValues }, lastConfirmedSnapshotJSON),
1282
+ [activeFields, composedValues, lastConfirmedSnapshotJSON]
1283
+ );
1284
+ const snapshot = useMemo(
1285
+ () => ({
1286
+ values: composedValues,
1287
+ activeFields,
1288
+ isValid,
1289
+ isDirty: dirty,
1290
+ query: buildQuery()
1291
+ }),
1292
+ [composedValues, activeFields, isValid, dirty, buildQuery]
1293
+ );
1294
+ const lastEmittedKeyRef = useRef("");
1295
+ useEffect(() => {
1296
+ const key = `${snapshotKey}|${dirty}|${isValid}`;
1297
+ if (key === lastEmittedKeyRef.current) return;
1298
+ lastEmittedKeyRef.current = key;
1299
+ onChange?.(snapshot);
1300
+ onStateChange?.(snapshot);
1301
+ }, [snapshotKey, dirty, isValid, snapshot, onChange, onStateChange]);
1302
+ const performAction = useCallback(() => {
1303
+ const key = buildSnapshotKey({ activeFields, values: composedValues });
1304
+ patch({ lastConfirmedSnapshotJSON: key });
1305
+ onPerform?.({ ...snapshot, isDirty: false });
1306
+ }, [activeFields, composedValues, patch, onPerform, snapshot]);
1307
+ const didPerformOnMountRef = useRef(false);
1308
+ useEffect(() => {
1309
+ if (performOnMount && !didPerformOnMountRef.current && Object.values(composedValues).some(isNonEmpty)) {
1310
+ didPerformOnMountRef.current = true;
1311
+ performAction();
1312
+ }
1313
+ }, [performOnMount]);
1314
+ useImperativeHandle(ref, () => ({
1315
+ perform: performAction,
1316
+ getSnapshot: () => snapshot
1317
+ }));
1318
+ const updateValue = useCallback(
1319
+ (fieldId, value) => {
1320
+ patch({ values: { ...values, [fieldId]: value } });
1321
+ },
1322
+ [patch, values]
1323
+ );
1324
+ const addField = useCallback(
1325
+ (fieldId) => {
1326
+ if (activeFields.includes(fieldId)) return;
1327
+ patch({ activeFields: [...activeFields, fieldId] });
1328
+ },
1329
+ [activeFields, patch]
1330
+ );
1331
+ const removeField = useCallback(
1332
+ (fieldId) => {
1333
+ const nextValues = { ...values };
1334
+ delete nextValues[fieldId];
1335
+ patch({
1336
+ activeFields: activeFields.filter((f) => f !== fieldId),
1337
+ values: nextValues
1338
+ });
1339
+ },
1340
+ [activeFields, values, patch]
1341
+ );
1342
+ const clearAll = useCallback(() => {
1343
+ const seed = {};
1344
+ if (config.searchField?.defaultValue !== void 0) {
1345
+ seed[config.searchField.id] = config.searchField.defaultValue;
1346
+ }
1347
+ patch({
1348
+ values: seed,
1349
+ activeFields: initialActive.filter((id2) => {
1350
+ const def = config.fields.find((f) => f.id === id2);
1351
+ return def?.pinned;
1352
+ }).concat(config.searchField ? [config.searchField.id] : []),
1353
+ lastConfirmedSnapshotJSON: null
1354
+ });
1355
+ }, [config, patch, initialActive]);
1356
+ const visibleConfigFields = useMemo(
1357
+ () => config.fields.filter((f) => isFieldVisible(f, composedValues)),
1358
+ [config.fields, composedValues]
1359
+ );
1360
+ const isProminentTextField = (f) => f.type === "text" && f.prominent === true;
1361
+ const pinnedFields = useMemo(
1362
+ () => visibleConfigFields.filter((f) => f.pinned && !isProminentTextField(f)),
1363
+ [visibleConfigFields]
1364
+ );
1365
+ const chipFields = useMemo(
1366
+ () => visibleConfigFields.filter(
1367
+ (f) => !f.pinned && !isProminentTextField(f) && activeFields.includes(f.id)
1368
+ ),
1369
+ [visibleConfigFields, activeFields]
1370
+ );
1371
+ const prominentSlots = useMemo(() => {
1372
+ const slots = [];
1373
+ if (config.searchField) {
1374
+ slots.push({
1375
+ def: config.searchField,
1376
+ removable: false,
1377
+ // legacy slot is implicitly always-present
1378
+ isLegacySearchField: true
1379
+ });
1380
+ }
1381
+ for (const f of visibleConfigFields) {
1382
+ if (!isProminentTextField(f)) continue;
1383
+ if (!activeFields.includes(f.id)) continue;
1384
+ slots.push({
1385
+ def: f,
1386
+ removable: editable !== false && !f.pinned && !f.locked,
1387
+ isLegacySearchField: false
1388
+ });
1389
+ }
1390
+ return slots;
1391
+ }, [config.searchField, visibleConfigFields, activeFields, editable]);
1392
+ const availableToAdd = useMemo(
1393
+ () => visibleConfigFields.filter(
1394
+ (f) => !f.pinned && !activeFields.includes(f.id)
1395
+ ),
1396
+ [visibleConfigFields, activeFields]
1397
+ );
1398
+ const performEnabled = editable !== false && performButton && isValid && dirty;
1399
+ const performLabelText = performLabel ?? labels.perform;
1400
+ const renderField = (f) => {
1401
+ if (f.type === "multifilter") {
1402
+ const removable2 = editable && !f.pinned && !f.locked;
1403
+ return /* @__PURE__ */ jsxs(
1404
+ "div",
1405
+ {
1406
+ className: "rounded-md border border-dashed border-border bg-muted/30 p-2",
1407
+ children: [
1408
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 mb-2", children: [
1409
+ /* @__PURE__ */ jsx("span", { className: "text-xs font-medium text-muted-foreground", children: f.label }),
1410
+ removable2 && /* @__PURE__ */ jsx(
1411
+ "button",
1412
+ {
1413
+ type: "button",
1414
+ onClick: () => removeField(f.id),
1415
+ className: "ml-auto p-0.5 hover:bg-muted rounded",
1416
+ children: /* @__PURE__ */ jsx(X, { className: "w-3.5 h-3.5 text-muted-foreground" })
1417
+ }
1418
+ )
1419
+ ] }),
1420
+ /* @__PURE__ */ jsx(
1421
+ EasyVisionMultifilter2,
1422
+ {
1423
+ id: f.id,
1424
+ config: f.config,
1425
+ editable,
1426
+ performButton: false,
1427
+ labels: labelOverrides
1428
+ }
1429
+ )
1430
+ ]
1431
+ },
1432
+ f.id
1433
+ );
1434
+ }
1435
+ const removable = editable && !f.pinned && !f.locked;
1436
+ return /* @__PURE__ */ jsx(
1437
+ MultifilterField,
1438
+ {
1439
+ definition: f,
1440
+ value: values[f.id],
1441
+ onChange: (v) => updateValue(f.id, v),
1442
+ onRemove: removable ? () => removeField(f.id) : void 0
1443
+ },
1444
+ f.id
1445
+ );
1446
+ };
1447
+ return /* @__PURE__ */ jsx(NamespaceProvider, { fullId, children: /* @__PURE__ */ jsx("div", { className, children: /* @__PURE__ */ jsxs("div", { className: "p-3 space-y-2 bg-card border border-border rounded-md", children: [
1448
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [
1449
+ prominentSlots.map(({ def, removable, isLegacySearchField }) => /* @__PURE__ */ jsxs(
1450
+ "div",
1451
+ {
1452
+ className: "relative flex-1 min-w-[200px]",
1453
+ children: [
1454
+ /* @__PURE__ */ jsx(Search, { className: "absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground pointer-events-none" }),
1455
+ /* @__PURE__ */ jsx(
1456
+ Input,
1457
+ {
1458
+ className: `w-full h-9 pl-9 ${removable ? "pr-9" : "pr-3"} bg-muted border-0 rounded-md text-sm focus:ring-1 focus:ring-ring focus:bg-card`,
1459
+ placeholder: def.placeholder ?? def.label ?? labels.searchPlaceholder,
1460
+ value: values[def.id] ?? "",
1461
+ onChange: (e) => updateValue(def.id, e.target.value),
1462
+ onKeyDown: (e) => {
1463
+ if (e.key === "Enter" && performButton && performEnabled) {
1464
+ performAction();
1465
+ }
1466
+ }
1467
+ }
1468
+ ),
1469
+ removable && /* @__PURE__ */ jsx(
1470
+ "button",
1471
+ {
1472
+ type: "button",
1473
+ onClick: () => removeField(def.id),
1474
+ "aria-label": labels.clear,
1475
+ className: "absolute right-2 top-1/2 -translate-y-1/2 p-1 rounded hover:bg-muted-foreground/10",
1476
+ children: /* @__PURE__ */ jsx(X, { className: "w-3.5 h-3.5 text-muted-foreground" })
1477
+ }
1478
+ )
1479
+ ]
1480
+ },
1481
+ isLegacySearchField ? `__searchField__${def.id}` : def.id
1482
+ )),
1483
+ editable && availableToAdd.length > 0 && /* @__PURE__ */ jsxs(Popover, { children: [
1484
+ /* @__PURE__ */ jsx(PopoverTrigger, { asChild: true, children: /* @__PURE__ */ jsx(
1485
+ Button,
1486
+ {
1487
+ variant: "outline",
1488
+ size: "sm",
1489
+ className: "h-9 w-9 p-0 border border-dashed border-border hover:bg-muted rounded-md",
1490
+ "aria-label": labels.addFilter,
1491
+ children: /* @__PURE__ */ jsx(Plus, { className: "w-4 h-4 text-muted-foreground" })
1492
+ }
1493
+ ) }),
1494
+ /* @__PURE__ */ jsx(PopoverContent, { className: "w-52 p-1", align: "start", children: /* @__PURE__ */ jsx("div", { className: "space-y-0.5", children: availableToAdd.map((f) => /* @__PURE__ */ jsxs(
1495
+ "button",
1496
+ {
1497
+ type: "button",
1498
+ onClick: () => addField(f.id),
1499
+ className: "w-full text-left px-3 py-2 text-xs hover:bg-muted rounded-md flex items-center gap-2",
1500
+ children: [
1501
+ /* @__PURE__ */ jsx(Plus, { className: "w-3 h-3 text-muted-foreground" }),
1502
+ f.label
1503
+ ]
1504
+ },
1505
+ f.id
1506
+ )) }) })
1507
+ ] }),
1508
+ performButton && performPosition === "inline" && /* @__PURE__ */ jsxs(
1509
+ Button,
1510
+ {
1511
+ size: "sm",
1512
+ onClick: performAction,
1513
+ disabled: !performEnabled,
1514
+ className: "h-9 px-4 text-xs font-medium",
1515
+ children: [
1516
+ performIcon ?? /* @__PURE__ */ jsx(Search, { className: "w-3.5 h-3.5 mr-1.5" }),
1517
+ performLabelText
1518
+ ]
1519
+ }
1520
+ ),
1521
+ showClear && /* @__PURE__ */ jsxs(
1522
+ Button,
1523
+ {
1524
+ variant: "ghost",
1525
+ size: "sm",
1526
+ onClick: clearAll,
1527
+ className: "h-9 px-3 text-xs text-muted-foreground",
1528
+ children: [
1529
+ /* @__PURE__ */ jsx(X, { className: "w-3.5 h-3.5 mr-1" }),
1530
+ labels.clear
1531
+ ]
1532
+ }
1533
+ )
1534
+ ] }),
1535
+ pinnedFields.length > 0 && /* @__PURE__ */ jsx("div", { className: "flex flex-wrap items-center gap-2", children: pinnedFields.map(renderField) }),
1536
+ chipFields.length > 0 && /* @__PURE__ */ jsx("div", { className: "flex flex-wrap items-center gap-2", children: chipFields.map(renderField) }),
1537
+ performButton && performPosition === "belowRow" && /* @__PURE__ */ jsx("div", { className: "flex justify-end pt-1", children: /* @__PURE__ */ jsxs(
1538
+ Button,
1539
+ {
1540
+ size: "sm",
1541
+ onClick: performAction,
1542
+ disabled: !performEnabled,
1543
+ className: "h-9 px-4 text-xs font-medium",
1544
+ children: [
1545
+ performIcon ?? /* @__PURE__ */ jsx(Search, { className: "w-3.5 h-3.5 mr-1.5" }),
1546
+ performLabelText
1547
+ ]
1548
+ }
1549
+ ) })
1550
+ ] }) }) });
1551
+ });
1552
+ function buildChildQueryDirect(field, values) {
1553
+ const where = {};
1554
+ for (const def of field.config.fields) {
1555
+ if (def.type === "multifilter") continue;
1556
+ const v = values[def.id];
1557
+ if (v === void 0 || v === null || v === "") continue;
1558
+ if (!def.field) continue;
1559
+ switch (def.type) {
1560
+ case "text": {
1561
+ const str = String(v).trim();
1562
+ if (str) where[def.field] = { $regex: `.*${str}.*`, $options: "i" };
1563
+ break;
1564
+ }
1565
+ case "selector":
1566
+ where[def.field] = v;
1567
+ break;
1568
+ case "multiselect": {
1569
+ const arr = v;
1570
+ if (Array.isArray(arr) && arr.length > 0) where[def.field] = { $in: arr };
1571
+ break;
1572
+ }
1573
+ case "dateRange": {
1574
+ const r = v;
1575
+ if (r?.from || r?.to) {
1576
+ const cond = {};
1577
+ if (r.from) cond.$gte = r.from.toISOString();
1578
+ if (r.to) cond.$lte = r.to.toISOString();
1579
+ where[def.field] = cond;
1580
+ }
1581
+ break;
1582
+ }
1583
+ case "numberRange": {
1584
+ const r = v;
1585
+ if (r?.min != null || r?.max != null) {
1586
+ const cond = {};
1587
+ if (r.min != null) cond.$gte = r.min;
1588
+ if (r.max != null) cond.$lte = r.max;
1589
+ where[def.field] = cond;
1590
+ }
1591
+ break;
1592
+ }
1593
+ }
1594
+ }
1595
+ if (field.config.searchField) {
1596
+ const sv = values[field.config.searchField.id];
1597
+ if (typeof sv === "string" && sv.trim() && field.config.searchField.field) {
1598
+ where[field.config.searchField.field] = { $regex: `.*${sv.trim()}.*`, $options: "i" };
1599
+ }
1600
+ }
1601
+ return Object.keys(where).length > 0 ? { where } : {};
1602
+ }
1603
+ var join = (...parts) => parts.filter(Boolean).join(" ");
1604
+ var EasyVisionCard = React8.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
1605
+ "div",
1606
+ {
1607
+ ref,
1608
+ className: join(
1609
+ "rounded-md border border-border bg-card text-card-foreground shadow-sm",
1610
+ className
1611
+ ),
1612
+ ...props
1613
+ }
1614
+ ));
1615
+ EasyVisionCard.displayName = "EasyVisionCard";
1616
+ var EasyVisionCardHeader = React8.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
1617
+ "div",
1618
+ {
1619
+ ref,
1620
+ className: join("flex flex-col space-y-1.5 p-6", className),
1621
+ ...props
1622
+ }
1623
+ ));
1624
+ EasyVisionCardHeader.displayName = "EasyVisionCardHeader";
1625
+ var EasyVisionCardTitle = React8.forwardRef(({ className, children, ...props }, ref) => /* @__PURE__ */ jsx(
1626
+ "h3",
1627
+ {
1628
+ ref,
1629
+ className: join(
1630
+ "text-2xl font-semibold leading-none tracking-tight",
1631
+ className
1632
+ ),
1633
+ ...props,
1634
+ children
1635
+ }
1636
+ ));
1637
+ EasyVisionCardTitle.displayName = "EasyVisionCardTitle";
1638
+ var EasyVisionCardDescription = React8.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
1639
+ "p",
1640
+ {
1641
+ ref,
1642
+ className: join("text-sm text-muted-foreground", className),
1643
+ ...props
1644
+ }
1645
+ ));
1646
+ EasyVisionCardDescription.displayName = "EasyVisionCardDescription";
1647
+ var EasyVisionCardContent = React8.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx("div", { ref, className: join("p-6 pt-0", className), ...props }));
1648
+ EasyVisionCardContent.displayName = "EasyVisionCardContent";
1649
+ var EasyVisionCardFooter = React8.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
1650
+ "div",
1651
+ {
1652
+ ref,
1653
+ className: join("flex items-center p-6 pt-0", className),
1654
+ ...props
1655
+ }
1656
+ ));
1657
+ EasyVisionCardFooter.displayName = "EasyVisionCardFooter";
1658
+ var Table = React8.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx("div", { className: "relative w-full overflow-auto", children: /* @__PURE__ */ jsx(
1659
+ "table",
1660
+ {
1661
+ ref,
1662
+ className: cn("w-full caption-bottom text-sm", className),
1663
+ ...props
1664
+ }
1665
+ ) }));
1666
+ Table.displayName = "Table";
1667
+ var TableHeader = React8.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx("thead", { ref, className: cn("[&_tr]:border-b", className), ...props }));
1668
+ TableHeader.displayName = "TableHeader";
1669
+ var TableBody = React8.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
1670
+ "tbody",
1671
+ {
1672
+ ref,
1673
+ className: cn("[&_tr:last-child]:border-0", className),
1674
+ ...props
1675
+ }
1676
+ ));
1677
+ TableBody.displayName = "TableBody";
1678
+ var TableFooter = React8.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
1679
+ "tfoot",
1680
+ {
1681
+ ref,
1682
+ className: cn(
1683
+ "border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",
1684
+ className
1685
+ ),
1686
+ ...props
1687
+ }
1688
+ ));
1689
+ TableFooter.displayName = "TableFooter";
1690
+ var TableRow = React8.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
1691
+ "tr",
1692
+ {
1693
+ ref,
1694
+ className: cn(
1695
+ "border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",
1696
+ className
1697
+ ),
1698
+ ...props
1699
+ }
1700
+ ));
1701
+ TableRow.displayName = "TableRow";
1702
+ var TableHead = React8.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
1703
+ "th",
1704
+ {
1705
+ ref,
1706
+ className: cn(
1707
+ "h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",
1708
+ className
1709
+ ),
1710
+ ...props
1711
+ }
1712
+ ));
1713
+ TableHead.displayName = "TableHead";
1714
+ var TableCell = React8.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
1715
+ "td",
1716
+ {
1717
+ ref,
1718
+ className: cn("p-4 align-middle [&:has([role=checkbox])]:pr-0", className),
1719
+ ...props
1720
+ }
1721
+ ));
1722
+ TableCell.displayName = "TableCell";
1723
+ var TableCaption = React8.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
1724
+ "caption",
1725
+ {
1726
+ ref,
1727
+ className: cn("mt-4 text-sm text-muted-foreground", className),
1728
+ ...props
1729
+ }
1730
+ ));
1731
+ TableCaption.displayName = "TableCaption";
1732
+ var isNestedField = (field) => field.includes(".");
1733
+ var resolvePath = (obj, path) => path.split(".").reduce(
1734
+ (acc, key) => acc != null && typeof acc === "object" ? acc[key] : void 0,
1735
+ obj
1736
+ );
1737
+ function shouldDisableSorting(col, orderingMode, defaultSorting = "nonNested") {
1738
+ if (col.type === "ui") return true;
1739
+ if (col.sortable === false) return true;
1740
+ if (col.sortable === true) return false;
1741
+ if (defaultSorting === "disabled") return true;
1742
+ if (defaultSorting === "all") return false;
1743
+ if (orderingMode === "api" && isNestedField(col.field)) return true;
1744
+ return false;
1745
+ }
1746
+ function adaptColumns(columns, orderingMode, defaultSorting = "nonNested") {
1747
+ return columns.map((c) => {
1748
+ const widthCss = typeof c.width === "number" ? `${c.width}px` : c.width;
1749
+ const numericWidth = typeof c.width === "number" ? c.width : typeof c.width === "string" && /^\d+px$/.test(c.width) ? parseInt(c.width, 10) : void 0;
1750
+ const meta = {
1751
+ initiallyHidden: !!c.initiallyHidden,
1752
+ largeScreensOnly: !!c.largeScreensOnly,
1753
+ width: widthCss,
1754
+ truncate: !!c.truncate,
1755
+ resizable: !!c.resizable
1756
+ };
1757
+ const isUi = c.type === "ui";
1758
+ const userCell = c.cell;
1759
+ const wrappedCell = userCell ? ({ row }) => userCell(row.original) : ({ getValue }) => createElement(
1760
+ "span",
1761
+ { className: "text-sm text-foreground" },
1762
+ String(getValue() ?? "-")
1763
+ );
1764
+ const base = {
1765
+ id: c.field,
1766
+ header: c.header,
1767
+ cell: wrappedCell,
1768
+ enableSorting: !shouldDisableSorting(c, orderingMode, defaultSorting),
1769
+ enableHiding: true,
1770
+ enableResizing: !!c.resizable,
1771
+ meta
1772
+ };
1773
+ if (c.resizable) {
1774
+ base.size = numericWidth ?? 240;
1775
+ base.minSize = 60;
1776
+ } else if (numericWidth !== void 0) {
1777
+ base.size = numericWidth;
1778
+ }
1779
+ if (!isUi) {
1780
+ base.accessorFn = (row) => resolvePath(row, c.field);
1781
+ }
1782
+ return base;
1783
+ });
1784
+ }
1785
+
1786
+ // lib/isNestedAccessor.ts
1787
+ function getByPath(obj, path) {
1788
+ if (!obj || !path) return void 0;
1789
+ return path.split(".").reduce((acc, key) => {
1790
+ if (acc && typeof acc === "object") {
1791
+ return acc[key];
1792
+ }
1793
+ return void 0;
1794
+ }, obj);
1795
+ }
1796
+
1797
+ // lib/compareByPath.ts
1798
+ var numericRe = /-?\d+(?:[.,]\d+)?/;
1799
+ function extractFirstNumber(value) {
1800
+ if (typeof value === "number") return Number.isNaN(value) ? null : value;
1801
+ if (typeof value === "string") {
1802
+ const match = value.match(numericRe);
1803
+ if (match) {
1804
+ const parsed = parseFloat(match[0].replace(",", "."));
1805
+ return Number.isNaN(parsed) ? null : parsed;
1806
+ }
1807
+ }
1808
+ return null;
1809
+ }
1810
+ function compareByPath(a, b, path, descending) {
1811
+ const av = getByPath(a, path);
1812
+ const bv = getByPath(b, path);
1813
+ if (av == null && bv == null) return 0;
1814
+ if (av == null) return descending ? 1 : -1;
1815
+ if (bv == null) return descending ? -1 : 1;
1816
+ const an = extractFirstNumber(av);
1817
+ const bn = extractFirstNumber(bv);
1818
+ if (an !== null && bn !== null) {
1819
+ return descending ? bn - an : an - bn;
1820
+ }
1821
+ if (av instanceof Date && bv instanceof Date) {
1822
+ return descending ? bv.getTime() - av.getTime() : av.getTime() - bv.getTime();
1823
+ }
1824
+ const as = String(av);
1825
+ const bs = String(bv);
1826
+ return descending ? bs.localeCompare(as) : as.localeCompare(bs);
1827
+ }
1828
+
1829
+ // table/useTableData.ts
1830
+ function useTableData({
1831
+ data,
1832
+ columns,
1833
+ page,
1834
+ itemsPerPage,
1835
+ sort,
1836
+ paginationMode,
1837
+ orderingMode
1838
+ }) {
1839
+ return useMemo(() => {
1840
+ let rows = data ?? [];
1841
+ if (orderingMode === "local" && sort) {
1842
+ const col = columns.find((c) => c.field === sort.column);
1843
+ if (col && col.type !== "ui") {
1844
+ const next = [...rows];
1845
+ next.sort((a, b) => compareByPath(a, b, col.field, sort.descending));
1846
+ rows = next;
1847
+ }
1848
+ }
1849
+ const totalCount = rows.length;
1850
+ if (paginationMode === "local") {
1851
+ const start = (page - 1) * itemsPerPage;
1852
+ rows = rows.slice(start, start + itemsPerPage);
1853
+ }
1854
+ return { rows, totalCount };
1855
+ }, [data, columns, page, itemsPerPage, sort, paginationMode, orderingMode]);
1856
+ }
1857
+ var DropdownMenu = DropdownMenuPrimitive.Root;
1858
+ var DropdownMenuTrigger = DropdownMenuPrimitive.Trigger;
1859
+ var DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup;
1860
+ var DropdownMenuSubTrigger = React8.forwardRef(({ className, inset, children, ...props }, ref) => /* @__PURE__ */ jsxs(
1861
+ DropdownMenuPrimitive.SubTrigger,
1862
+ {
1863
+ ref,
1864
+ className: cn(
1865
+ "flex cursor-default select-none items-center gap-2 rounded-md px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
1866
+ inset && "pl-8",
1867
+ className
1868
+ ),
1869
+ ...props,
1870
+ children: [
1871
+ children,
1872
+ /* @__PURE__ */ jsx(ChevronRight, { className: "ml-auto" })
1873
+ ]
1874
+ }
1875
+ ));
1876
+ DropdownMenuSubTrigger.displayName = DropdownMenuPrimitive.SubTrigger.displayName;
1877
+ var DropdownMenuSubContent = React8.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
1878
+ DropdownMenuPrimitive.SubContent,
1879
+ {
1880
+ ref,
1881
+ className: cn(
1882
+ "z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-dropdown-menu-content-transform-origin]",
1883
+ className
1884
+ ),
1885
+ ...props
1886
+ }
1887
+ ));
1888
+ DropdownMenuSubContent.displayName = DropdownMenuPrimitive.SubContent.displayName;
1889
+ var DropdownMenuContent = React8.forwardRef(({ className, sideOffset = 4, ...props }, ref) => /* @__PURE__ */ jsx(DropdownMenuPrimitive.Portal, { children: /* @__PURE__ */ jsx(
1890
+ DropdownMenuPrimitive.Content,
1891
+ {
1892
+ ref,
1893
+ sideOffset,
1894
+ className: cn(
1895
+ "z-50 max-h-[var(--radix-dropdown-menu-content-available-height)] min-w-[8rem] overflow-y-auto overflow-x-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-dropdown-menu-content-transform-origin]",
1896
+ className
1897
+ ),
1898
+ ...props
1899
+ }
1900
+ ) }));
1901
+ DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName;
1902
+ var DropdownMenuItem = React8.forwardRef(({ className, inset, ...props }, ref) => /* @__PURE__ */ jsx(
1903
+ DropdownMenuPrimitive.Item,
1904
+ {
1905
+ ref,
1906
+ className: cn(
1907
+ "relative flex cursor-default select-none items-center gap-2 rounded-md px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
1908
+ inset && "pl-8",
1909
+ className
1910
+ ),
1911
+ ...props
1912
+ }
1913
+ ));
1914
+ DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName;
1915
+ var DropdownMenuCheckboxItem = React8.forwardRef(({ className, children, checked, ...props }, ref) => /* @__PURE__ */ jsxs(
1916
+ DropdownMenuPrimitive.CheckboxItem,
1917
+ {
1918
+ ref,
1919
+ className: cn(
1920
+ "relative flex cursor-default select-none items-center rounded-md py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
1921
+ className
1922
+ ),
1923
+ checked,
1924
+ ...props,
1925
+ children: [
1926
+ /* @__PURE__ */ jsx("span", { className: "absolute left-2 flex h-3.5 w-3.5 items-center justify-center", children: /* @__PURE__ */ jsx(DropdownMenuPrimitive.ItemIndicator, { children: /* @__PURE__ */ jsx(Check, { className: "h-4 w-4" }) }) }),
1927
+ children
1928
+ ]
1929
+ }
1930
+ ));
1931
+ DropdownMenuCheckboxItem.displayName = DropdownMenuPrimitive.CheckboxItem.displayName;
1932
+ var DropdownMenuRadioItem = React8.forwardRef(({ className, children, ...props }, ref) => /* @__PURE__ */ jsxs(
1933
+ DropdownMenuPrimitive.RadioItem,
1934
+ {
1935
+ ref,
1936
+ className: cn(
1937
+ "relative flex cursor-default select-none items-center rounded-md py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
1938
+ className
1939
+ ),
1940
+ ...props,
1941
+ children: [
1942
+ /* @__PURE__ */ jsx("span", { className: "absolute left-2 flex h-3.5 w-3.5 items-center justify-center", children: /* @__PURE__ */ jsx(DropdownMenuPrimitive.ItemIndicator, { children: /* @__PURE__ */ jsx(Circle, { className: "h-2 w-2 fill-current" }) }) }),
1943
+ children
1944
+ ]
1945
+ }
1946
+ ));
1947
+ DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName;
1948
+ var DropdownMenuLabel = React8.forwardRef(({ className, inset, ...props }, ref) => /* @__PURE__ */ jsx(
1949
+ DropdownMenuPrimitive.Label,
1950
+ {
1951
+ ref,
1952
+ className: cn(
1953
+ "px-2 py-1.5 text-sm font-semibold",
1954
+ inset && "pl-8",
1955
+ className
1956
+ ),
1957
+ ...props
1958
+ }
1959
+ ));
1960
+ DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName;
1961
+ var DropdownMenuSeparator = React8.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
1962
+ DropdownMenuPrimitive.Separator,
1963
+ {
1964
+ ref,
1965
+ className: cn("-mx-1 my-1 h-px bg-muted", className),
1966
+ ...props
1967
+ }
1968
+ ));
1969
+ DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName;
1970
+ function SelectAllControl({
1971
+ scope,
1972
+ toggleable,
1973
+ state,
1974
+ onToggle,
1975
+ onScopeChange,
1976
+ labels
1977
+ }) {
1978
+ return /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1", children: [
1979
+ /* @__PURE__ */ jsx(
1980
+ Checkbox,
1981
+ {
1982
+ checked: state === "checked" ? true : state === "indeterminate" ? "indeterminate" : false,
1983
+ onCheckedChange: (c) => onToggle(!!c),
1984
+ "aria-label": "Select all"
1985
+ }
1986
+ ),
1987
+ toggleable && /* @__PURE__ */ jsxs(DropdownMenu, { children: [
1988
+ /* @__PURE__ */ jsx(DropdownMenuTrigger, { asChild: true, children: /* @__PURE__ */ jsx(
1989
+ "button",
1990
+ {
1991
+ type: "button",
1992
+ className: "flex h-5 w-5 items-center justify-center rounded border border-border bg-background hover:bg-muted",
1993
+ "aria-label": "Toggle select-all scope",
1994
+ children: /* @__PURE__ */ jsx(ChevronDown, { className: "h-3.5 w-3.5" })
1995
+ }
1996
+ ) }),
1997
+ /* @__PURE__ */ jsx(DropdownMenuContent, { align: "start", children: /* @__PURE__ */ jsxs(
1998
+ DropdownMenuRadioGroup,
1999
+ {
2000
+ value: scope,
2001
+ onValueChange: (v) => onScopeChange(v),
2002
+ children: [
2003
+ /* @__PURE__ */ jsx(DropdownMenuRadioItem, { value: "page", children: labels.selectAllPage }),
2004
+ /* @__PURE__ */ jsx(DropdownMenuRadioItem, { value: "all", children: labels.selectAllAll })
2005
+ ]
2006
+ }
2007
+ ) })
2008
+ ] })
2009
+ ] });
2010
+ }
2011
+ function PaginationFooter({
2012
+ currentPage,
2013
+ totalCount,
2014
+ itemsPerPage,
2015
+ itemsPerPageOptions,
2016
+ onPageChange,
2017
+ onItemsPerPageChange,
2018
+ labels
2019
+ }) {
2020
+ const totalPages = Math.max(1, Math.ceil(totalCount / itemsPerPage));
2021
+ return /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between p-4 border-t border-border text-sm text-muted-foreground", children: [
2022
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
2023
+ /* @__PURE__ */ jsx("span", { children: labels.rowsPerPage }),
2024
+ /* @__PURE__ */ jsxs(
2025
+ Select,
2026
+ {
2027
+ value: String(itemsPerPage),
2028
+ onValueChange: (v) => onItemsPerPageChange(Number(v)),
2029
+ children: [
2030
+ /* @__PURE__ */ jsx(SelectTrigger, { className: "h-9 w-[70px] border border-border", children: /* @__PURE__ */ jsx(SelectValue, {}) }),
2031
+ /* @__PURE__ */ jsx(SelectContent, { children: itemsPerPageOptions.map((opt) => /* @__PURE__ */ jsx(SelectItem, { value: String(opt), children: opt }, opt)) })
2032
+ ]
2033
+ }
2034
+ ),
2035
+ /* @__PURE__ */ jsxs("span", { children: [
2036
+ totalCount,
2037
+ " ",
2038
+ labels.results
2039
+ ] })
2040
+ ] }),
2041
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
2042
+ /* @__PURE__ */ jsx("span", { children: labels.page }),
2043
+ /* @__PURE__ */ jsxs(
2044
+ Select,
2045
+ {
2046
+ value: String(currentPage),
2047
+ onValueChange: (v) => onPageChange(Number(v)),
2048
+ children: [
2049
+ /* @__PURE__ */ jsx(SelectTrigger, { className: "h-9 w-16 border border-border", children: /* @__PURE__ */ jsx(SelectValue, {}) }),
2050
+ /* @__PURE__ */ jsx(SelectContent, { children: Array.from({ length: totalPages }, (_, i) => i + 1).map((p) => /* @__PURE__ */ jsx(SelectItem, { value: String(p), children: p }, p)) })
2051
+ ]
2052
+ }
2053
+ ),
2054
+ /* @__PURE__ */ jsxs("span", { children: [
2055
+ labels.of,
2056
+ " ",
2057
+ totalPages
2058
+ ] }),
2059
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1 ml-1", children: [
2060
+ /* @__PURE__ */ jsx(
2061
+ Button,
2062
+ {
2063
+ variant: "ghost",
2064
+ size: "icon",
2065
+ className: "h-8 w-8",
2066
+ disabled: currentPage <= 1,
2067
+ onClick: () => onPageChange(currentPage - 1),
2068
+ children: /* @__PURE__ */ jsx(ChevronLeft, { className: "h-4 w-4" })
2069
+ }
2070
+ ),
2071
+ /* @__PURE__ */ jsx(
2072
+ Button,
2073
+ {
2074
+ variant: "ghost",
2075
+ size: "icon",
2076
+ className: "h-8 w-8",
2077
+ disabled: currentPage >= totalPages,
2078
+ onClick: () => onPageChange(currentPage + 1),
2079
+ children: /* @__PURE__ */ jsx(ChevronRight, { className: "h-4 w-4" })
2080
+ }
2081
+ )
2082
+ ] })
2083
+ ] })
2084
+ ] });
2085
+ }
2086
+ function ColumnVisibilityMenu({ table, label }) {
2087
+ return /* @__PURE__ */ jsxs(DropdownMenu, { children: [
2088
+ /* @__PURE__ */ jsx(DropdownMenuTrigger, { asChild: true, children: /* @__PURE__ */ jsxs(Button, { variant: "outline", size: "sm", children: [
2089
+ /* @__PURE__ */ jsx(Settings2, { className: "mr-2 h-4 w-4" }),
2090
+ label
2091
+ ] }) }),
2092
+ /* @__PURE__ */ jsx(DropdownMenuContent, { align: "end", className: "max-h-64 overflow-y-auto", children: table.getAllColumns().filter((col) => col.getCanHide() && col.id !== "_select").map((col) => {
2093
+ const rawHeader = col.columnDef.header;
2094
+ const headerLabel = typeof rawHeader === "string" && rawHeader.trim().length > 0 ? rawHeader : col.id;
2095
+ return /* @__PURE__ */ jsx(
2096
+ DropdownMenuCheckboxItem,
2097
+ {
2098
+ checked: col.getIsVisible(),
2099
+ onCheckedChange: (v) => col.toggleVisibility(!!v),
2100
+ className: "capitalize",
2101
+ children: headerLabel
2102
+ },
2103
+ col.id
2104
+ );
2105
+ }) })
2106
+ ] });
2107
+ }
2108
+
2109
+ // adapters/loopback.ts
2110
+ function createLoopbackTableFetcher(opts) {
2111
+ const { fetchPage, fetchCount, include, fields, defaultOrder } = opts;
2112
+ return async ({
2113
+ page,
2114
+ itemsPerPage,
2115
+ sort,
2116
+ filter
2117
+ }) => {
2118
+ const order = sort ? [`${sort.column} ${sort.descending ? "DESC" : "ASC"}`] : defaultOrder ?? [];
2119
+ const skip = (page - 1) * itemsPerPage;
2120
+ const where = filter?.where ?? {};
2121
+ const pageFilter = {
2122
+ where,
2123
+ skip,
2124
+ limit: itemsPerPage,
2125
+ order,
2126
+ ...include ? { include } : {},
2127
+ ...fields ? { fields } : {}
2128
+ };
2129
+ const [rows, count] = await Promise.all([
2130
+ fetchPage(pageFilter),
2131
+ fetchCount({ where })
2132
+ ]);
2133
+ return { rows, totalCount: count.count };
2134
+ };
2135
+ }
2136
+ function matchLoopbackWhere(row, where) {
2137
+ if (!where) return true;
2138
+ const w = where;
2139
+ const keys = Object.keys(w);
2140
+ if (keys.length === 0) return true;
2141
+ for (const key of keys) {
2142
+ const value = w[key];
2143
+ if (key === "$and") {
2144
+ if (!Array.isArray(value)) return false;
2145
+ if (!value.every((sub) => matchLoopbackWhere(row, sub))) {
2146
+ return false;
2147
+ }
2148
+ continue;
2149
+ }
2150
+ if (key === "$or") {
2151
+ if (!Array.isArray(value)) return false;
2152
+ if (!value.some((sub) => matchLoopbackWhere(row, sub))) {
2153
+ return false;
2154
+ }
2155
+ continue;
2156
+ }
2157
+ if (key === "$not") {
2158
+ if (matchLoopbackWhere(row, value)) return false;
2159
+ continue;
2160
+ }
2161
+ const values = resolvePath2(row, key.split("."));
2162
+ if (!values.some((v) => matchLeaf(v, value))) return false;
2163
+ }
2164
+ return true;
2165
+ }
2166
+ function resolvePath2(node, path) {
2167
+ if (path.length === 0) return [node];
2168
+ if (node == null) return [void 0];
2169
+ if (Array.isArray(node)) {
2170
+ return node.flatMap((item) => resolvePath2(item, path));
2171
+ }
2172
+ if (typeof node !== "object") return [void 0];
2173
+ const [head, ...rest] = path;
2174
+ return resolvePath2(node[head], rest);
2175
+ }
2176
+ function matchLeaf(value, condition) {
2177
+ if (condition === null || typeof condition !== "object") {
2178
+ if (Array.isArray(value)) return value.some((v) => v === condition);
2179
+ return value === condition;
2180
+ }
2181
+ const cond = condition;
2182
+ const keys = Object.keys(cond);
2183
+ if (keys.length === 0) return true;
2184
+ if (!keys.some((k) => k.startsWith("$"))) return false;
2185
+ for (const op of keys) {
2186
+ const arg = cond[op];
2187
+ switch (op) {
2188
+ case "$eq":
2189
+ if (Array.isArray(value) ? !value.includes(arg) : value !== arg) return false;
2190
+ break;
2191
+ case "$ne":
2192
+ case "$neq":
2193
+ if (Array.isArray(value) ? value.includes(arg) : value === arg) return false;
2194
+ break;
2195
+ case "$in":
2196
+ if (!Array.isArray(arg)) return false;
2197
+ if (Array.isArray(value)) {
2198
+ if (!value.some((v) => arg.includes(v))) return false;
2199
+ } else if (!arg.includes(value)) {
2200
+ return false;
2201
+ }
2202
+ break;
2203
+ case "$nin":
2204
+ if (!Array.isArray(arg)) return false;
2205
+ if (Array.isArray(value)) {
2206
+ if (value.some((v) => arg.includes(v))) return false;
2207
+ } else if (arg.includes(value)) {
2208
+ return false;
2209
+ }
2210
+ break;
2211
+ case "$gt":
2212
+ if (value == null || !(value > arg)) return false;
2213
+ break;
2214
+ case "$gte":
2215
+ if (value == null || !(value >= arg)) return false;
2216
+ break;
2217
+ case "$lt":
2218
+ if (value == null || !(value < arg)) return false;
2219
+ break;
2220
+ case "$lte":
2221
+ if (value == null || !(value <= arg)) return false;
2222
+ break;
2223
+ case "$exists": {
2224
+ const exists = value !== void 0 && value !== null;
2225
+ if (Boolean(arg) !== exists) return false;
2226
+ break;
2227
+ }
2228
+ case "$regex": {
2229
+ const opts = typeof cond.$options === "string" ? cond.$options : "";
2230
+ let re;
2231
+ try {
2232
+ re = arg instanceof RegExp ? arg : new RegExp(String(arg), opts);
2233
+ } catch {
2234
+ return false;
2235
+ }
2236
+ if (Array.isArray(value)) {
2237
+ if (!value.some((v) => typeof v === "string" && re.test(v))) return false;
2238
+ } else if (typeof value !== "string" || !re.test(value)) {
2239
+ return false;
2240
+ }
2241
+ break;
2242
+ }
2243
+ case "$options":
2244
+ break;
2245
+ default:
2246
+ return false;
2247
+ }
2248
+ }
2249
+ return true;
2250
+ }
2251
+ var DEFAULT_LABELS2 = {
2252
+ rowsPerPage: "Resultados por p\xE1gina:",
2253
+ results: "Resultados",
2254
+ page: "P\xE1gina:",
2255
+ of: "de",
2256
+ noData: "Sin datos",
2257
+ loading: "Cargando...",
2258
+ customizeColumns: "Columnas",
2259
+ selectAllPage: "Seleccionar p\xE1gina",
2260
+ selectAllAll: "Seleccionar todo",
2261
+ selectedAllBanner: (n) => `Todos los ${n} registros seleccionados`,
2262
+ selectedCountBanner: (n) => `${n} ${n === 1 ? "registro seleccionado" : "registros seleccionados"}`,
2263
+ clearSelection: "Limpiar selecci\xF3n"
2264
+ };
2265
+ function EasyVisionTable(props) {
2266
+ const {
2267
+ id,
2268
+ columns,
2269
+ paginationMode: paginationModeProp = "local",
2270
+ orderingMode: orderingModeProp = "local",
2271
+ defaultSorting = "nonNested",
2272
+ data,
2273
+ fetchData: fetchDataProp,
2274
+ loopback,
2275
+ onDataLoaded,
2276
+ multifilter,
2277
+ multifilterRef,
2278
+ refetchSignal,
2279
+ externalFilter,
2280
+ localMatch: localMatchProp,
2281
+ getRowId: getRowIdProp,
2282
+ itemsPerPage: itemsPerPageProp = 10,
2283
+ itemsPerPageOptions = [10, 15, 20],
2284
+ enableRowSelection = false,
2285
+ selectAllScope = "toggleable",
2286
+ selectAllResolution = "lazy",
2287
+ onSelectionChange,
2288
+ isLoading: isLoadingProp = false,
2289
+ emptyMessage,
2290
+ emptyAction,
2291
+ onRowClick,
2292
+ isRowHighlighted,
2293
+ toolbarLeft,
2294
+ toolbarRight,
2295
+ showColumnVisibility = true,
2296
+ maxBodyHeight,
2297
+ labels: labelOverrides,
2298
+ className,
2299
+ persist = false
2300
+ } = props;
2301
+ const labels = { ...DEFAULT_LABELS2, ...labelOverrides };
2302
+ const lbFetchPage = loopback?.fetchPage;
2303
+ const lbFetchCount = loopback?.fetchCount;
2304
+ const lbIncludeKey = JSON.stringify(loopback?.include ?? null);
2305
+ const lbFieldsKey = JSON.stringify(loopback?.fields ?? null);
2306
+ const lbOrderKey = JSON.stringify(loopback?.defaultOrder ?? null);
2307
+ const loopbackFetcher = useMemo(
2308
+ () => loopback ? createLoopbackTableFetcher(loopback) : void 0,
2309
+ // eslint-disable-next-line react-hooks/exhaustive-deps
2310
+ [lbFetchPage, lbFetchCount, lbIncludeKey, lbFieldsKey, lbOrderKey]
2311
+ );
2312
+ const fetchData = fetchDataProp ?? loopbackFetcher;
2313
+ const paginationMode = loopback ? "api" : paginationModeProp;
2314
+ const orderingMode = loopback ? "api" : orderingModeProp;
2315
+ const getRowId = useMemo(
2316
+ () => getRowIdProp ?? ((row) => String(row?.id ?? "")),
2317
+ [getRowIdProp]
2318
+ );
2319
+ const localMatch = localMatchProp ?? matchLoopbackWhere;
2320
+ const { slice, fullId, patch } = useEasyVisionSlice("table", id, {
2321
+ init: () => ({
2322
+ kind: "table",
2323
+ page: 1,
2324
+ itemsPerPage: itemsPerPageProp,
2325
+ sort: null,
2326
+ selection: {
2327
+ ids: {},
2328
+ scope: selectAllScope === "all" ? "all" : "page"
2329
+ }
2330
+ }),
2331
+ persist
2332
+ });
2333
+ const { page, itemsPerPage, sort, selection } = slice;
2334
+ const lastSnapshotRef = useRef(null);
2335
+ const [localFilterTick, setLocalFilterTick] = useState(0);
2336
+ const innerMultifilterRef = useRef(null);
2337
+ const setMultifilterRef = useCallback(
2338
+ (handle) => {
2339
+ innerMultifilterRef.current = handle;
2340
+ if (typeof multifilterRef === "function") {
2341
+ multifilterRef(handle);
2342
+ } else if (multifilterRef && "current" in multifilterRef) {
2343
+ multifilterRef.current = handle;
2344
+ }
2345
+ },
2346
+ [multifilterRef]
2347
+ );
2348
+ const [apiRows, setApiRows] = useState([]);
2349
+ const [apiTotalCount, setApiTotalCount] = useState(0);
2350
+ const [apiLoading, setApiLoading] = useState(false);
2351
+ const fetchSeqRef = useRef(0);
2352
+ const isApi = paginationMode === "api" || orderingMode === "api";
2353
+ const [eagerAllIds, setEagerAllIds] = useState(null);
2354
+ const [eagerAllRows, setEagerAllRows] = useState([]);
2355
+ const [isResolvingEager, setIsResolvingEager] = useState(false);
2356
+ const eagerSeqRef = useRef(0);
2357
+ const runFetch = useCallback(async () => {
2358
+ if (!fetchData) return;
2359
+ const seq = ++fetchSeqRef.current;
2360
+ setApiLoading(true);
2361
+ try {
2362
+ const mfQuery = lastSnapshotRef.current?.query;
2363
+ const merged = externalFilter || mfQuery ? {
2364
+ ...mfQuery,
2365
+ where: {
2366
+ ...externalFilter?.where ?? {},
2367
+ ...mfQuery?.where ?? {}
2368
+ }
2369
+ } : void 0;
2370
+ const result = await fetchData({
2371
+ page,
2372
+ itemsPerPage,
2373
+ sort,
2374
+ filter: merged
2375
+ });
2376
+ if (seq !== fetchSeqRef.current) return;
2377
+ setApiRows(result.rows);
2378
+ setApiTotalCount(result.totalCount);
2379
+ onDataLoaded?.(result.rows, result.totalCount);
2380
+ } finally {
2381
+ if (seq === fetchSeqRef.current) setApiLoading(false);
2382
+ }
2383
+ }, [fetchData, page, itemsPerPage, sort, externalFilter, onDataLoaded]);
2384
+ useEffect(() => {
2385
+ if (isApi && fetchData) void runFetch();
2386
+ }, [isApi, page, itemsPerPage, sort, refetchSignal]);
2387
+ const resolveEagerAll = useCallback(async () => {
2388
+ if (!fetchData) return;
2389
+ const seq = ++eagerSeqRef.current;
2390
+ setIsResolvingEager(true);
2391
+ try {
2392
+ const mfQuery = lastSnapshotRef.current?.query;
2393
+ const merged = externalFilter || mfQuery ? {
2394
+ ...mfQuery,
2395
+ where: {
2396
+ ...externalFilter?.where ?? {},
2397
+ ...mfQuery?.where ?? {}
2398
+ }
2399
+ } : void 0;
2400
+ const PAGE_SIZE = 200;
2401
+ const ids = [];
2402
+ const rowsAcc = [];
2403
+ let knownTotal = Infinity;
2404
+ for (let p = 1; ids.length < knownTotal; p++) {
2405
+ const result = await fetchData({
2406
+ page: p,
2407
+ itemsPerPage: PAGE_SIZE,
2408
+ sort,
2409
+ filter: merged
2410
+ });
2411
+ if (seq !== eagerSeqRef.current) return;
2412
+ knownTotal = result.totalCount;
2413
+ for (const row of result.rows) {
2414
+ const rid = getRowId(row);
2415
+ if (rid) {
2416
+ ids.push(rid);
2417
+ rowsAcc.push(row);
2418
+ }
2419
+ }
2420
+ if (result.rows.length < PAGE_SIZE) break;
2421
+ }
2422
+ if (seq !== eagerSeqRef.current) return;
2423
+ setEagerAllIds(ids);
2424
+ setEagerAllRows(rowsAcc);
2425
+ } finally {
2426
+ if (seq === eagerSeqRef.current) setIsResolvingEager(false);
2427
+ }
2428
+ }, [fetchData, externalFilter, sort, getRowId]);
2429
+ const prevRefetchRef = useRef(refetchSignal);
2430
+ useEffect(() => {
2431
+ if (prevRefetchRef.current !== refetchSignal && page !== 1) {
2432
+ prevRefetchRef.current = refetchSignal;
2433
+ patch({ page: 1 });
2434
+ } else {
2435
+ prevRefetchRef.current = refetchSignal;
2436
+ }
2437
+ setEagerAllIds(null);
2438
+ setEagerAllRows([]);
2439
+ eagerSeqRef.current++;
2440
+ setIsResolvingEager(false);
2441
+ }, [refetchSignal]);
2442
+ const filteredData = useMemo(() => {
2443
+ if (paginationMode !== "local") return data;
2444
+ if (!data || data.length === 0) return data;
2445
+ const mfWhere = lastSnapshotRef.current?.query?.where;
2446
+ const extWhere = externalFilter?.where;
2447
+ const merged = extWhere || mfWhere ? { ...extWhere ?? {}, ...mfWhere ?? {} } : void 0;
2448
+ if (!merged || Object.keys(merged).length === 0) return data;
2449
+ return data.filter((row) => localMatch(row, merged));
2450
+ }, [data, paginationMode, localMatch, localFilterTick, externalFilter]);
2451
+ const local = useTableData({
2452
+ data: filteredData,
2453
+ columns,
2454
+ page,
2455
+ itemsPerPage,
2456
+ sort,
2457
+ paginationMode,
2458
+ orderingMode
2459
+ });
2460
+ const rows = isApi ? apiRows : local.rows;
2461
+ const totalCount = isApi ? apiTotalCount : local.totalCount;
2462
+ const isLoading = isLoadingProp || apiLoading;
2463
+ const tanstackColumns = useMemo(
2464
+ () => adaptColumns(columns, orderingMode, defaultSorting),
2465
+ [columns, orderingMode, defaultSorting]
2466
+ );
2467
+ const allColumns = useMemo(() => {
2468
+ if (!enableRowSelection) return tanstackColumns;
2469
+ const checkboxCol = {
2470
+ id: "_select",
2471
+ header: () => null,
2472
+ // we render our own header in the header row below
2473
+ cell: ({ row }) => /* @__PURE__ */ jsx(
2474
+ Checkbox,
2475
+ {
2476
+ checked: row.getIsSelected(),
2477
+ onCheckedChange: (v) => row.toggleSelected(!!v),
2478
+ onClick: (e) => e.stopPropagation(),
2479
+ "aria-label": "Select row"
2480
+ }
2481
+ ),
2482
+ enableSorting: false,
2483
+ enableHiding: false
2484
+ };
2485
+ return [checkboxCol, ...tanstackColumns];
2486
+ }, [enableRowSelection, tanstackColumns]);
2487
+ const [columnVisibility, setColumnVisibility] = useState(() => {
2488
+ const v = {};
2489
+ for (const c of columns) {
2490
+ if (c.initiallyHidden) v[c.field] = false;
2491
+ }
2492
+ return v;
2493
+ });
2494
+ const rowSelection = useMemo(() => {
2495
+ if (selection.scope === "all") return {};
2496
+ const r = {};
2497
+ for (const id2 of Object.keys(selection.ids)) r[id2] = true;
2498
+ return r;
2499
+ }, [selection]);
2500
+ const sortingState = sort ? [{ id: sort.column, desc: sort.descending }] : [];
2501
+ const isEagerWildcard = selectAllResolution === "eager" && isApi && selection.scope === "all";
2502
+ const tableInstance = useReactTable({
2503
+ data: rows,
2504
+ columns: allColumns,
2505
+ state: {
2506
+ columnVisibility,
2507
+ ...enableRowSelection ? { rowSelection } : {},
2508
+ sorting: sortingState
2509
+ },
2510
+ onColumnVisibilityChange: setColumnVisibility,
2511
+ enableRowSelection,
2512
+ onRowSelectionChange: enableRowSelection ? (updater) => {
2513
+ const next = typeof updater === "function" ? updater(rowSelection) : updater;
2514
+ const ids = {};
2515
+ for (const k of Object.keys(next)) {
2516
+ if (next[k]) ids[k] = true;
2517
+ }
2518
+ patch({ selection: { ...selection, ids } });
2519
+ } : void 0,
2520
+ onSortingChange: (updater) => {
2521
+ if (isEagerWildcard) return;
2522
+ const next = typeof updater === "function" ? updater(sortingState) : updater;
2523
+ const first = next[0];
2524
+ const newSort = first ? { column: first.id, descending: !!first.desc } : null;
2525
+ patch({ sort: newSort });
2526
+ },
2527
+ getCoreRowModel: getCoreRowModel(),
2528
+ manualPagination: true,
2529
+ manualSorting: true,
2530
+ enableColumnResizing: true,
2531
+ columnResizeMode: "onChange",
2532
+ pageCount: Math.ceil(totalCount / itemsPerPage),
2533
+ getRowId
2534
+ });
2535
+ const lastSelectionEmittedRef = useRef("");
2536
+ useEffect(() => {
2537
+ if (!enableRowSelection) return;
2538
+ if (isEagerWildcard && (isResolvingEager || eagerAllIds === null)) return;
2539
+ let event;
2540
+ if (selection.scope === "all") {
2541
+ if (paginationMode === "local") {
2542
+ const allRows = filteredData ?? data ?? [];
2543
+ const ids = allRows.map(getRowId).filter(Boolean);
2544
+ event = { scope: "all", mode: "in-memory", ids, rows: allRows };
2545
+ } else if (selectAllResolution === "eager" && eagerAllIds) {
2546
+ const exceptSet = new Set(Object.keys(selection.exceptIds ?? {}));
2547
+ let ids;
2548
+ let outRows;
2549
+ if (exceptSet.size) {
2550
+ ids = [];
2551
+ outRows = [];
2552
+ for (let i = 0; i < eagerAllIds.length; i++) {
2553
+ const rid = eagerAllIds[i];
2554
+ if (exceptSet.has(rid)) continue;
2555
+ ids.push(rid);
2556
+ const r = eagerAllRows[i];
2557
+ if (r !== void 0) outRows.push(r);
2558
+ }
2559
+ } else {
2560
+ ids = eagerAllIds;
2561
+ outRows = eagerAllRows;
2562
+ }
2563
+ event = { scope: "all", mode: "in-memory", ids, rows: outRows };
2564
+ } else {
2565
+ const exceptIds = Object.keys(selection.exceptIds ?? {});
2566
+ const exceptSet = new Set(exceptIds);
2567
+ const pageRows = rows.filter((r) => !exceptSet.has(getRowId(r)));
2568
+ const ids = pageRows.map(getRowId).filter(Boolean);
2569
+ event = {
2570
+ scope: "all",
2571
+ mode: "wildcard",
2572
+ ids,
2573
+ exceptIds,
2574
+ rows: pageRows
2575
+ };
2576
+ }
2577
+ } else {
2578
+ const ids = Object.keys(selection.ids);
2579
+ const idSet = new Set(ids);
2580
+ const selectedRows = rows.filter((r) => idSet.has(getRowId(r)));
2581
+ event = { scope: "page", ids, rows: selectedRows };
2582
+ }
2583
+ const key = JSON.stringify({ ...event, rows: event.rows.length });
2584
+ if (key === lastSelectionEmittedRef.current) return;
2585
+ lastSelectionEmittedRef.current = key;
2586
+ onSelectionChange?.(event);
2587
+ }, [
2588
+ enableRowSelection,
2589
+ selection,
2590
+ paginationMode,
2591
+ data,
2592
+ filteredData,
2593
+ rows,
2594
+ getRowId,
2595
+ onSelectionChange,
2596
+ selectAllResolution,
2597
+ eagerAllIds,
2598
+ eagerAllRows,
2599
+ isResolvingEager,
2600
+ isEagerWildcard
2601
+ ]);
2602
+ const rowIdOf = useCallback(
2603
+ (row) => getRowId(row),
2604
+ [getRowId]
2605
+ );
2606
+ const headerState = useMemo(() => {
2607
+ if (selection.scope === "all") {
2608
+ const except = Object.keys(selection.exceptIds ?? {}).length;
2609
+ if (except === 0) return "checked";
2610
+ return "indeterminate";
2611
+ }
2612
+ const visibleIds = rows.map(rowIdOf).filter(Boolean);
2613
+ if (visibleIds.length === 0) return "unchecked";
2614
+ let selectedOnPage = 0;
2615
+ for (const id2 of visibleIds) {
2616
+ if (selection.ids[id2]) selectedOnPage++;
2617
+ }
2618
+ if (selectedOnPage === 0) return "unchecked";
2619
+ if (selectedOnPage === visibleIds.length) return "checked";
2620
+ return "indeterminate";
2621
+ }, [selection, rows, rowIdOf]);
2622
+ const onHeaderToggle = useCallback(
2623
+ (checked) => {
2624
+ if (selection.scope === "all") {
2625
+ if (checked) {
2626
+ patch({ selection: { ids: {}, scope: "all", exceptIds: {} } });
2627
+ } else {
2628
+ const exceptIds = { ...selection.exceptIds ?? {} };
2629
+ for (const r of rows) {
2630
+ const rid = rowIdOf(r);
2631
+ if (rid) exceptIds[rid] = true;
2632
+ }
2633
+ patch({ selection: { ...selection, exceptIds } });
2634
+ }
2635
+ return;
2636
+ }
2637
+ const next = { ...selection.ids };
2638
+ const visibleIds = rows.map(rowIdOf).filter(Boolean);
2639
+ if (checked) {
2640
+ for (const rid of visibleIds) next[rid] = true;
2641
+ } else {
2642
+ for (const rid of visibleIds) delete next[rid];
2643
+ }
2644
+ patch({ selection: { ...selection, ids: next } });
2645
+ },
2646
+ [patch, selection, rows, rowIdOf]
2647
+ );
2648
+ const onScopeChange = useCallback(
2649
+ (scope) => {
2650
+ if (scope === "all") {
2651
+ patch({ selection: { ids: {}, scope: "all", exceptIds: {} } });
2652
+ if (selectAllResolution === "eager" && isApi) {
2653
+ setEagerAllIds(null);
2654
+ setEagerAllRows([]);
2655
+ void resolveEagerAll();
2656
+ }
2657
+ } else {
2658
+ patch({ selection: { ids: {}, scope: "page" } });
2659
+ setEagerAllIds(null);
2660
+ setEagerAllRows([]);
2661
+ eagerSeqRef.current++;
2662
+ setIsResolvingEager(false);
2663
+ }
2664
+ },
2665
+ [patch, selectAllResolution, isApi, resolveEagerAll]
2666
+ );
2667
+ const firstPerformAfterMountRef = useRef(true);
2668
+ const handlePerform = useCallback(
2669
+ (snap) => {
2670
+ const isFirstAfterMount = firstPerformAfterMountRef.current;
2671
+ firstPerformAfterMountRef.current = false;
2672
+ lastSnapshotRef.current = snap;
2673
+ if (selection.scope === "all") {
2674
+ patch({ selection: { ids: {}, scope: "all", exceptIds: {} } });
2675
+ }
2676
+ setEagerAllIds(null);
2677
+ setEagerAllRows([]);
2678
+ eagerSeqRef.current++;
2679
+ setIsResolvingEager(false);
2680
+ if (!isFirstAfterMount) patch({ page: 1 });
2681
+ multifilter?.onPerform?.(snap);
2682
+ if (isApi) void runFetch();
2683
+ else setLocalFilterTick((n) => n + 1);
2684
+ },
2685
+ [isApi, multifilter, patch, runFetch, selection.scope]
2686
+ );
2687
+ const totalPages = Math.max(1, Math.ceil(totalCount / itemsPerPage));
2688
+ const hasResolvedDataRef = useRef(false);
2689
+ useEffect(() => {
2690
+ if (isApi) {
2691
+ if (apiLoading) return;
2692
+ if (!hasResolvedDataRef.current) {
2693
+ if (apiTotalCount > 0 || apiRows.length > 0) {
2694
+ hasResolvedDataRef.current = true;
2695
+ } else {
2696
+ return;
2697
+ }
2698
+ }
2699
+ }
2700
+ if (page > totalPages) patch({ page: totalPages });
2701
+ }, [page, totalPages, patch, isApi, apiLoading, apiTotalCount, apiRows.length]);
2702
+ useEffect(() => {
2703
+ if (isApi) return;
2704
+ if (paginationMode === "page") return;
2705
+ if (page > 1 && page > Math.max(1, Math.ceil(totalCount / itemsPerPage))) {
2706
+ patch({ page: 1 });
2707
+ }
2708
+ }, [totalCount, itemsPerPage, page, paginationMode, patch, isApi]);
2709
+ return /* @__PURE__ */ jsx(NamespaceProvider, { fullId, children: /* @__PURE__ */ jsxs("div", { className, children: [
2710
+ multifilter && /* @__PURE__ */ jsx("div", { className: "mb-2", children: /* @__PURE__ */ jsx(
2711
+ EasyVisionMultifilter,
2712
+ {
2713
+ ...multifilter,
2714
+ ref: setMultifilterRef,
2715
+ onPerform: handlePerform
2716
+ }
2717
+ ) }),
2718
+ /* @__PURE__ */ jsxs("div", { className: "rounded-md border border-border overflow-hidden bg-card", children: [
2719
+ (toolbarLeft || toolbarRight || enableRowSelection || showColumnVisibility) && /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-2 px-4 py-2 border-b border-border", children: [
2720
+ /* @__PURE__ */ jsx("div", { className: "flex items-center gap-2", children: toolbarLeft }),
2721
+ enableRowSelection && (() => {
2722
+ const isAllScope = selection.scope === "all";
2723
+ const pageCount = isAllScope ? 0 : Object.keys(selection.ids ?? {}).length;
2724
+ const eagerCount = isEagerWildcard && eagerAllIds ? Math.max(
2725
+ 0,
2726
+ eagerAllIds.length - Object.keys(selection.exceptIds ?? {}).length
2727
+ ) : null;
2728
+ const allCount = isAllScope ? eagerCount ?? Math.max(0, totalCount - Object.keys(selection.exceptIds ?? {}).length) : 0;
2729
+ if (!isAllScope && pageCount === 0) return null;
2730
+ return /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 rounded-sm border border-primary/30 bg-primary/5 px-3 py-1 text-xs", children: [
2731
+ isEagerWildcard && isResolvingEager && /* @__PURE__ */ jsx(Loader2, { className: "w-3 h-2 animate-spin text-primary" }),
2732
+ /* @__PURE__ */ jsx("span", { className: "text-primary font-medium", children: isAllScope ? isEagerWildcard && isResolvingEager ? `${labels.loading}\u2026` : labels.selectedAllBanner(allCount) : labels.selectedCountBanner(pageCount) }),
2733
+ /* @__PURE__ */ jsxs(
2734
+ Button,
2735
+ {
2736
+ variant: "ghost",
2737
+ size: "sm",
2738
+ onClick: () => onScopeChange("page"),
2739
+ className: "ml-auto h-6 text-xs",
2740
+ children: [
2741
+ /* @__PURE__ */ jsx(X, { className: "w-3 h-2 mr-1" }),
2742
+ labels.clearSelection
2743
+ ]
2744
+ }
2745
+ )
2746
+ ] });
2747
+ })(),
2748
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
2749
+ toolbarRight,
2750
+ showColumnVisibility && /* @__PURE__ */ jsx(ColumnVisibilityMenu, { table: tableInstance, label: labels.customizeColumns })
2751
+ ] })
2752
+ ] }),
2753
+ /* @__PURE__ */ jsx(
2754
+ "div",
2755
+ {
2756
+ className: "easyvision-table-scroll relative w-full overflow-auto",
2757
+ style: maxBodyHeight !== void 0 ? {
2758
+ maxHeight: typeof maxBodyHeight === "number" ? `${maxBodyHeight}px` : maxBodyHeight
2759
+ } : void 0,
2760
+ children: /* @__PURE__ */ jsxs("table", { className: "w-full caption-bottom text-sm min-w-max", children: [
2761
+ /* @__PURE__ */ jsx(
2762
+ TableHeader,
2763
+ {
2764
+ className: maxBodyHeight !== void 0 ? "sticky top-0 z-10 bg-card shadow-[inset_0_-1px_0_0_hsl(var(--border))]" : void 0,
2765
+ children: tableInstance.getHeaderGroups().map((hg) => /* @__PURE__ */ jsx(TableRow, { children: hg.headers.map((header) => {
2766
+ if (header.column.id === "_select" && enableRowSelection) {
2767
+ return /* @__PURE__ */ jsx(TableHead, { className: "w-[60px] whitespace-nowrap", children: /* @__PURE__ */ jsx(
2768
+ SelectAllControl,
2769
+ {
2770
+ scope: selection.scope,
2771
+ toggleable: selectAllScope === "toggleable",
2772
+ state: headerState,
2773
+ onToggle: onHeaderToggle,
2774
+ onScopeChange,
2775
+ labels: {
2776
+ selectAllPage: labels.selectAllPage,
2777
+ selectAllAll: labels.selectAllAll
2778
+ }
2779
+ }
2780
+ ) }, header.id);
2781
+ }
2782
+ const colDef = columns.find(
2783
+ (c) => c.field === header.column.id
2784
+ );
2785
+ const sortable = colDef && !shouldDisableSorting(colDef, orderingMode, defaultSorting) && !isEagerWildcard;
2786
+ const colMeta = header.column.columnDef.meta ?? {};
2787
+ const headerWidthStyle = colMeta.resizable ? { width: header.getSize(), minWidth: header.getSize() } : colMeta.width ? { width: colMeta.width, minWidth: colMeta.width } : void 0;
2788
+ return /* @__PURE__ */ jsxs(
2789
+ TableHead,
2790
+ {
2791
+ style: headerWidthStyle,
2792
+ className: [
2793
+ "relative",
2794
+ colMeta.largeScreensOnly ? "hidden lg:table-cell" : ""
2795
+ ].filter(Boolean).join(" "),
2796
+ children: [
2797
+ header.isPlaceholder ? null : sortable ? /* @__PURE__ */ jsxs(
2798
+ "button",
2799
+ {
2800
+ className: "flex items-center gap-1 select-none hover:opacity-70",
2801
+ onClick: header.column.getToggleSortingHandler(),
2802
+ children: [
2803
+ flexRender(header.column.columnDef.header, header.getContext()),
2804
+ header.column.getIsSorted() === "asc" ? /* @__PURE__ */ jsx(ArrowUp, { className: "h-3 w-3" }) : header.column.getIsSorted() === "desc" ? /* @__PURE__ */ jsx(ArrowDown, { className: "h-3 w-3" }) : /* @__PURE__ */ jsx(ArrowUpDown, { className: "h-3 w-3 text-muted-foreground opacity-50" })
2805
+ ]
2806
+ }
2807
+ ) : flexRender(header.column.columnDef.header, header.getContext()),
2808
+ colMeta.resizable && header.column.getCanResize() && /* @__PURE__ */ jsx(
2809
+ "div",
2810
+ {
2811
+ onMouseDown: header.getResizeHandler(),
2812
+ onTouchStart: header.getResizeHandler(),
2813
+ onClick: (e) => e.stopPropagation(),
2814
+ role: "separator",
2815
+ "aria-orientation": "vertical",
2816
+ "aria-label": "Resize column",
2817
+ className: [
2818
+ "group absolute top-0 right-0 h-full w-3 -mr-1.5 cursor-col-resize select-none touch-none",
2819
+ "after:content-[''] after:absolute after:right-1.5 after:top-1/2 after:-translate-y-1/2",
2820
+ "after:h-1/2 after:w-px after:bg-border after:transition-all",
2821
+ "hover:after:w-1.5 hover:after:h-full hover:after:top-0 hover:after:translate-y-0 hover:after:bg-primary/30",
2822
+ header.column.getIsResizing() ? "after:!w-1.5 after:!h-full after:!top-0 after:!translate-y-0 after:!bg-primary/60" : ""
2823
+ ].filter(Boolean).join(" ")
2824
+ }
2825
+ )
2826
+ ]
2827
+ },
2828
+ header.id
2829
+ );
2830
+ }) }, hg.id))
2831
+ }
2832
+ ),
2833
+ /* @__PURE__ */ jsx(TableBody, { children: isLoading ? /* @__PURE__ */ jsx(TableRow, { children: /* @__PURE__ */ jsx(TableCell, { colSpan: allColumns.length, className: "h-48 text-center", children: /* @__PURE__ */ jsx("div", { className: "flex items-center justify-center", children: /* @__PURE__ */ jsx(Loader2, { className: "h-6 w-6 animate-spin text-muted-foreground" }) }) }) }) : tableInstance.getRowModel().rows.length === 0 ? /* @__PURE__ */ jsx(TableRow, { children: /* @__PURE__ */ jsx(TableCell, { colSpan: allColumns.length, className: "h-48 text-center", children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center gap-3", children: [
2834
+ /* @__PURE__ */ jsx("p", { className: "text-muted-foreground", children: emptyMessage ?? labels.noData }),
2835
+ emptyAction
2836
+ ] }) }) }) : tableInstance.getRowModel().rows.map((row) => {
2837
+ const rid = rowIdOf(row.original);
2838
+ const isAllSelected = selection.scope === "all" && !selection.exceptIds?.[rid];
2839
+ const highlighted = isRowHighlighted?.(row.original) ?? false;
2840
+ return /* @__PURE__ */ jsx(
2841
+ TableRow,
2842
+ {
2843
+ "data-state": row.getIsSelected() || isAllSelected ? "selected" : void 0,
2844
+ "data-highlighted": highlighted ? "true" : void 0,
2845
+ className: [
2846
+ onRowClick ? "cursor-pointer" : "",
2847
+ highlighted ? "bg-muted/50" : ""
2848
+ ].filter(Boolean).join(" "),
2849
+ onClick: () => onRowClick?.(row.original),
2850
+ children: row.getVisibleCells().map((cell) => {
2851
+ if (cell.column.id === "_select" && selection.scope === "all") {
2852
+ return /* @__PURE__ */ jsx(TableCell, { children: /* @__PURE__ */ jsx(
2853
+ Checkbox,
2854
+ {
2855
+ checked: !selection.exceptIds?.[rid],
2856
+ onCheckedChange: (v) => {
2857
+ const exceptIds = { ...selection.exceptIds ?? {} };
2858
+ if (v) delete exceptIds[rid];
2859
+ else exceptIds[rid] = true;
2860
+ patch({ selection: { ...selection, exceptIds } });
2861
+ },
2862
+ onClick: (e) => e.stopPropagation()
2863
+ }
2864
+ ) }, cell.id);
2865
+ }
2866
+ const cellMeta = cell.column.columnDef.meta ?? {};
2867
+ const cellWidthStyle = cellMeta.resizable ? { width: cell.column.getSize(), minWidth: cell.column.getSize() } : cellMeta.width ? { width: cellMeta.width, minWidth: cellMeta.width } : void 0;
2868
+ const rendered = flexRender(
2869
+ cell.column.columnDef.cell,
2870
+ cell.getContext()
2871
+ );
2872
+ let titleAttr;
2873
+ if (cellMeta.truncate) {
2874
+ try {
2875
+ const raw = cell.getValue();
2876
+ if (raw != null && (typeof raw === "string" || typeof raw === "number")) {
2877
+ const s = String(raw);
2878
+ if (s) titleAttr = s;
2879
+ }
2880
+ } catch {
2881
+ }
2882
+ }
2883
+ return /* @__PURE__ */ jsx(
2884
+ TableCell,
2885
+ {
2886
+ style: cellWidthStyle,
2887
+ className: [
2888
+ cellMeta.largeScreensOnly ? "hidden lg:table-cell" : "",
2889
+ cellMeta.truncate ? "max-w-0" : ""
2890
+ ].filter(Boolean).join(" "),
2891
+ children: cellMeta.truncate ? /* @__PURE__ */ jsx(
2892
+ "div",
2893
+ {
2894
+ className: "truncate",
2895
+ title: titleAttr,
2896
+ children: rendered
2897
+ }
2898
+ ) : rendered
2899
+ },
2900
+ cell.id
2901
+ );
2902
+ })
2903
+ },
2904
+ row.id
2905
+ );
2906
+ }) })
2907
+ ] })
2908
+ }
2909
+ ),
2910
+ /* @__PURE__ */ jsx(
2911
+ PaginationFooter,
2912
+ {
2913
+ currentPage: page,
2914
+ totalCount,
2915
+ itemsPerPage,
2916
+ itemsPerPageOptions,
2917
+ onPageChange: (p) => patch({ page: p }),
2918
+ onItemsPerPageChange: (n) => patch({ itemsPerPage: n, page: 1 }),
2919
+ labels
2920
+ }
2921
+ )
2922
+ ] })
2923
+ ] }) });
2924
+ }
2925
+ var defaultCell = (content, title) => /* @__PURE__ */ jsx("span", { className: "text-sm text-foreground", title, children: content });
2926
+
2927
+ export { EasyVisionCard, EasyVisionCardContent, EasyVisionCardDescription, EasyVisionCardFooter, EasyVisionCardHeader, EasyVisionCardTitle, EasyVisionInput, EasyVisionMultifilter, EasyVisionSelector, EasyVisionTable, createLoopbackTableFetcher, defaultCell, easyVisionRegistry, getSlice, matchLoopbackWhere };
2928
+ //# sourceMappingURL=index.js.map
2929
+ //# sourceMappingURL=index.js.map