@dubix/ui 0.9.0 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +466 -15
- package/dist/checkbox/Checkbox.d.ts +61 -0
- package/dist/checkbox/Checkbox.js +41 -0
- package/dist/checkbox/index.d.ts +2 -0
- package/dist/checkbox/index.js +1 -0
- package/dist/filter-bar/AppliedFilters.d.ts +41 -0
- package/dist/filter-bar/AppliedFilters.js +123 -0
- package/dist/filter-bar/FilterAmountRange.d.ts +27 -0
- package/dist/filter-bar/FilterAmountRange.js +86 -0
- package/dist/filter-bar/FilterBar.d.ts +32 -0
- package/dist/filter-bar/FilterBar.js +21 -0
- package/dist/filter-bar/FilterOptions.d.ts +71 -0
- package/dist/filter-bar/FilterOptions.js +181 -0
- package/dist/filter-bar/FilterPanel.d.ts +63 -0
- package/dist/filter-bar/FilterPanel.js +50 -0
- package/dist/filter-bar/FilterPeriod.d.ts +25 -0
- package/dist/filter-bar/FilterPeriod.js +71 -0
- package/dist/filter-bar/FilterSearch.d.ts +54 -0
- package/dist/filter-bar/FilterSearch.js +100 -0
- package/dist/filter-bar/FilterToggle.d.ts +16 -0
- package/dist/filter-bar/FilterToggle.js +24 -0
- package/dist/filter-bar/format.d.ts +53 -0
- package/dist/filter-bar/format.js +104 -0
- package/dist/filter-bar/index.d.ts +18 -0
- package/dist/filter-bar/index.js +9 -0
- package/dist/pagination/Pagination.d.ts +11 -8
- package/dist/pagination/Pagination.js +7 -2
- package/dist/popover/Popover.d.ts +65 -0
- package/dist/popover/Popover.js +87 -0
- package/dist/popover/index.d.ts +2 -0
- package/dist/popover/index.js +1 -0
- package/dist/select/Select.d.ts +5 -1
- package/dist/select/Select.js +2 -2
- package/dist/select/index.d.ts +1 -1
- package/dist/styles.css +965 -72
- package/dist/table/Table.d.ts +14 -3
- package/dist/table/Table.js +10 -4
- package/dist/tooltip/Tooltip.d.ts +6 -1
- package/dist/tooltip/Tooltip.js +5 -4
- package/package.json +13 -1
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
+
import { useId, useRef, useState } from 'react';
|
|
4
|
+
import { Button } from '../button/index.js';
|
|
5
|
+
import { CheckboxMark } from '../checkbox/Checkbox.js';
|
|
6
|
+
import { usePopoverClose } from '../popover/Popover.js';
|
|
7
|
+
import { SearchInput } from '../search-input/index.js';
|
|
8
|
+
import { Skeleton } from '../skeleton/index.js';
|
|
9
|
+
/** Con más opciones que esto, la lista lleva el campo para buscar (salvo que `searchable` diga otra cosa). */
|
|
10
|
+
const SEARCH_THRESHOLD = 8;
|
|
11
|
+
/** Filas de Skeleton mientras carga. */
|
|
12
|
+
const LOADING_ROWS = 4;
|
|
13
|
+
const LOADING_WIDTHS = ['72%', '54%', '80%', '62%'];
|
|
14
|
+
/** Tiempo entre teclas para que la búsqueda por letra siga la misma palabra, en ms (el de los menús de Radix). */
|
|
15
|
+
const TYPEAHEAD_MS = 500;
|
|
16
|
+
const cx = (own, extra) => (extra ? own + ' ' + extra : own);
|
|
17
|
+
/** Para comparar sin mayúsculas ni tildes: «Crédito» → «credito». */
|
|
18
|
+
const fold = (text) => text.normalize('NFD').replace(/\p{Diacritic}/gu, '').toLocaleLowerCase('es');
|
|
19
|
+
/** Tilde de la opción elegida (un valor): el check de 16px de DropdownMenu, en línea. */
|
|
20
|
+
const Check = () => (_jsx("svg", { viewBox: "0 0 16 16", width: "16", height: "16", fill: "none", stroke: "currentColor", strokeWidth: "1.75", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", focusable: "false", children: _jsx("path", { d: "M3.5 8.5l3 3 6-7" }) }));
|
|
21
|
+
/** Agrupa por `group`, en el orden en que aparece cada grupo; las opciones sin grupo forman su propia parte, sin título. */
|
|
22
|
+
function sectionsOf(options) {
|
|
23
|
+
const sections = [];
|
|
24
|
+
const byGroup = new Map();
|
|
25
|
+
for (const option of options) {
|
|
26
|
+
let section = byGroup.get(option.group);
|
|
27
|
+
if (!section) {
|
|
28
|
+
section = { group: option.group, options: [] };
|
|
29
|
+
byGroup.set(option.group, section);
|
|
30
|
+
sections.push(section);
|
|
31
|
+
}
|
|
32
|
+
section.options.push(option);
|
|
33
|
+
}
|
|
34
|
+
return sections;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Lista de opciones de un filtro, para ir dentro de un PopoverContent (lo que abre un FilterButton o un FilterChip). Todo se
|
|
38
|
+
* aplica al elegir, sin «Aplicar». Un valor: elegir marca y cierra el Popover (el foco vuelve a lo que lo abrió). Varios
|
|
39
|
+
* valores: cada opción con la caja de Checkbox, marcar no cierra y, con `onClear`, «Quitar filtro» abajo. Con búsqueda, un
|
|
40
|
+
* combobox con la lista (`aria-activedescendant`); sin búsqueda, un listbox con el foco en las opciones (patrones de APG).
|
|
41
|
+
*/
|
|
42
|
+
export function FilterOptions(props) {
|
|
43
|
+
const { options, 'aria-label': ariaLabel, searchable, searchLabel = 'Buscar', emptyText = 'No hay coincidencias', loading = false, busy = false, query: controlledQuery, onQueryChange, filter = true, status, className, } = props;
|
|
44
|
+
const close = usePopoverClose();
|
|
45
|
+
const id = useId();
|
|
46
|
+
const [ownQuery, setOwnQuery] = useState('');
|
|
47
|
+
const query = controlledQuery ?? ownQuery;
|
|
48
|
+
const setQuery = (text) => {
|
|
49
|
+
if (controlledQuery === undefined)
|
|
50
|
+
setOwnQuery(text);
|
|
51
|
+
onQueryChange?.(text);
|
|
52
|
+
};
|
|
53
|
+
const [active, setActive] = useState(null);
|
|
54
|
+
const input = useRef(null);
|
|
55
|
+
const list = useRef(null);
|
|
56
|
+
const typeahead = useRef({ text: '', at: 0 });
|
|
57
|
+
const selected = props.multiple ? props.value : props.value === null ? [] : [props.value];
|
|
58
|
+
const isSelected = (value) => selected.includes(value);
|
|
59
|
+
const withSearch = searchable ?? options.length > SEARCH_THRESHOLD;
|
|
60
|
+
const q = fold(query.trim());
|
|
61
|
+
const visible = loading ? [] : q === '' || !filter ? [...options] : options.filter((o) => fold(o.label).includes(q));
|
|
62
|
+
const enabled = visible.filter((o) => !o.disabled);
|
|
63
|
+
const sections = sectionsOf(visible);
|
|
64
|
+
const optionId = (value) => id + '-o-' + String(options.findIndex((o) => o.value === value));
|
|
65
|
+
// La opción activa: la elegida, o la primera habilitada, mientras no haya una activa que siga a la vista.
|
|
66
|
+
const fallback = enabled.find((o) => isSelected(o.value))?.value ?? enabled[0]?.value ?? null;
|
|
67
|
+
const current = active !== null && enabled.some((o) => o.value === active) ? active : fallback;
|
|
68
|
+
const element = (value) => list.current?.ownerDocument.getElementById(optionId(value)) ?? null;
|
|
69
|
+
/** Mueve la opción activa; sin búsqueda, también el foco (el listbox tiene el foco en las opciones). */
|
|
70
|
+
const activate = (value, focus = !withSearch) => {
|
|
71
|
+
if (value === null)
|
|
72
|
+
return;
|
|
73
|
+
setActive(value);
|
|
74
|
+
const el = element(value);
|
|
75
|
+
if (focus)
|
|
76
|
+
el?.focus({ preventScroll: false });
|
|
77
|
+
else
|
|
78
|
+
el?.scrollIntoView({ block: 'nearest' });
|
|
79
|
+
};
|
|
80
|
+
const choose = (option) => {
|
|
81
|
+
if (option.disabled)
|
|
82
|
+
return;
|
|
83
|
+
setActive(option.value);
|
|
84
|
+
if (props.multiple) {
|
|
85
|
+
const next = isSelected(option.value) ? props.value.filter((v) => v !== option.value) : [...props.value, option.value];
|
|
86
|
+
props.onValueChange(next);
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
if (props.value !== option.value)
|
|
90
|
+
props.onValueChange(option.value);
|
|
91
|
+
if (!option.keepOpen)
|
|
92
|
+
close?.();
|
|
93
|
+
};
|
|
94
|
+
const move = (event, step) => {
|
|
95
|
+
event.preventDefault();
|
|
96
|
+
if (!enabled.length)
|
|
97
|
+
return;
|
|
98
|
+
const at = enabled.findIndex((o) => o.value === current);
|
|
99
|
+
const index = step === 'first' ? 0 : step === 'last' ? enabled.length - 1 : Math.min(Math.max(at + step, 0), enabled.length - 1);
|
|
100
|
+
activate(enabled[index]?.value ?? null);
|
|
101
|
+
};
|
|
102
|
+
// Teclado del listbox (sin búsqueda): flechas, Home, End, Espacio y Enter, y la búsqueda por letra.
|
|
103
|
+
const onListKeyDown = (event) => {
|
|
104
|
+
if (event.key === 'ArrowDown')
|
|
105
|
+
move(event, 1);
|
|
106
|
+
else if (event.key === 'ArrowUp')
|
|
107
|
+
move(event, -1);
|
|
108
|
+
else if (event.key === 'Home')
|
|
109
|
+
move(event, 'first');
|
|
110
|
+
else if (event.key === 'End')
|
|
111
|
+
move(event, 'last');
|
|
112
|
+
else if (event.key === 'Enter' || event.key === ' ') {
|
|
113
|
+
event.preventDefault();
|
|
114
|
+
const option = enabled.find((o) => o.value === current);
|
|
115
|
+
if (option)
|
|
116
|
+
choose(option);
|
|
117
|
+
}
|
|
118
|
+
else if (event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey) {
|
|
119
|
+
const now = event.timeStamp;
|
|
120
|
+
const t = typeahead.current;
|
|
121
|
+
t.text = (now - t.at < TYPEAHEAD_MS ? t.text : '') + fold(event.key);
|
|
122
|
+
t.at = now;
|
|
123
|
+
// Desde la activa (la misma letra repetida pasa a la siguiente que empieza igual), dando la vuelta.
|
|
124
|
+
const at = enabled.findIndex((o) => o.value === current);
|
|
125
|
+
const repeat = t.text.length > 1 && t.text.split('').every((c) => c === t.text[0]);
|
|
126
|
+
const needle = repeat ? t.text[0] ?? '' : t.text;
|
|
127
|
+
const start = repeat || t.text.length === 1 ? at + 1 : at;
|
|
128
|
+
const order = [...enabled.slice(start), ...enabled.slice(0, start)];
|
|
129
|
+
const found = order.find((o) => fold(o.label).startsWith(needle));
|
|
130
|
+
if (found)
|
|
131
|
+
activate(found.value);
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
// Teclado del combobox (con búsqueda): el foco queda en el campo; las flechas mueven la activa y Enter elige o marca.
|
|
135
|
+
const onInputKeyDown = (event) => {
|
|
136
|
+
if (event.key === 'ArrowDown')
|
|
137
|
+
move(event, 1);
|
|
138
|
+
else if (event.key === 'ArrowUp')
|
|
139
|
+
move(event, -1);
|
|
140
|
+
else if (event.key === 'Enter') {
|
|
141
|
+
event.preventDefault();
|
|
142
|
+
const option = enabled.find((o) => o.value === current);
|
|
143
|
+
if (option)
|
|
144
|
+
choose(option);
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
const showClear = props.multiple && props.onClear !== undefined && props.value.length > 0;
|
|
148
|
+
const clear = () => {
|
|
149
|
+
if (!props.multiple)
|
|
150
|
+
return;
|
|
151
|
+
props.onClear?.();
|
|
152
|
+
// El botón desaparece: el foco pasa al campo para buscar o a la opción activa.
|
|
153
|
+
if (withSearch)
|
|
154
|
+
input.current?.focus();
|
|
155
|
+
else if (current !== null)
|
|
156
|
+
element(current)?.focus();
|
|
157
|
+
};
|
|
158
|
+
const listId = id + '-lista';
|
|
159
|
+
const renderOption = (option) => {
|
|
160
|
+
const on = isSelected(option.value);
|
|
161
|
+
const isActive = option.value === current;
|
|
162
|
+
const oid = optionId(option.value);
|
|
163
|
+
const hasDescription = option.description !== undefined && option.description !== '';
|
|
164
|
+
const hasMeta = option.meta !== undefined && option.meta !== '';
|
|
165
|
+
const describedBy = [...(hasDescription ? [oid + '-d'] : []), ...(hasMeta ? [oid + '-m'] : [])].join(' ');
|
|
166
|
+
return (_jsxs("div", { id: oid, role: "option", className: "dx-filter-options__option", "aria-selected": on, "aria-disabled": option.disabled ? true : undefined, "aria-labelledby": oid + '-l', "aria-describedby": describedBy || undefined, "data-active": isActive ? 'true' : undefined, "data-selected": on ? 'true' : undefined, tabIndex: withSearch || !isActive ? -1 : 0, onClick: () => { choose(option); },
|
|
167
|
+
// Con búsqueda, el clic no saca el foco del campo.
|
|
168
|
+
onMouseDown: withSearch ? (event) => { event.preventDefault(); } : undefined, onPointerMove: () => { if (!option.disabled && !isActive)
|
|
169
|
+
activate(option.value); }, children: [props.multiple && _jsx(CheckboxMark, { checked: on }), _jsxs("span", { className: "dx-filter-options__text", children: [_jsx("span", { className: "dx-filter-options__label", id: oid + '-l', children: option.label }), hasDescription && _jsx("span", { className: "dx-filter-options__description", id: oid + '-d', children: option.description })] }), hasMeta && _jsx("span", { className: "dx-filter-options__meta", id: oid + '-m', children: option.meta }), !props.multiple && on && _jsx("span", { className: "dx-filter-options__mark", children: _jsx(Check, {}) })] }, option.value));
|
|
170
|
+
};
|
|
171
|
+
let groupIndex = 0;
|
|
172
|
+
const body = loading
|
|
173
|
+
? Array.from({ length: LOADING_ROWS }, (_, i) => (_jsx("div", { className: "dx-filter-options__skeleton", "aria-hidden": "true", children: _jsx(Skeleton, { width: LOADING_WIDTHS[i % LOADING_WIDTHS.length] }) }, i)))
|
|
174
|
+
: sections.map((section) => {
|
|
175
|
+
if (section.group === undefined)
|
|
176
|
+
return section.options.map(renderOption);
|
|
177
|
+
const gid = id + '-g-' + String(groupIndex++);
|
|
178
|
+
return (_jsxs("div", { role: "group", "aria-labelledby": gid, className: "dx-filter-options__group", children: [_jsx("div", { role: "presentation", id: gid, className: "dx-filter-options__group-label", children: section.group }), section.options.map(renderOption)] }, 'g:' + section.group));
|
|
179
|
+
});
|
|
180
|
+
return (_jsxs("div", { className: cx('dx-filter-options', className), "data-multiple": props.multiple ? 'true' : undefined, children: [withSearch && (_jsx("div", { className: "dx-filter-options__search", children: _jsx(SearchInput, { ref: input, role: "combobox", "aria-label": searchLabel, placeholder: searchLabel, "aria-expanded": true, "aria-controls": listId, "aria-autocomplete": "list", "aria-activedescendant": current !== null ? optionId(current) : undefined, value: query, onValueChange: (text) => { setQuery(text); setActive(null); }, onKeyDown: onInputKeyDown }) })), _jsx("div", { ref: list, id: listId, role: "listbox", "aria-label": ariaLabel, "aria-multiselectable": props.multiple ? true : undefined, "aria-busy": loading || busy ? true : undefined, className: "dx-filter-options__list", onKeyDown: withSearch ? undefined : onListKeyDown, children: body }), _jsx("div", { className: "dx-filter-options__empty", role: "status", children: status !== undefined ? status : !loading && q !== '' && visible.length === 0 ? emptyText : null }), showClear && (_jsx("div", { className: "dx-filter-options__footer", children: _jsx(Button, { variant: "ghost", size: "xs", onClick: clear, children: props.clearLabel ?? 'Quitar filtro' }) }))] }));
|
|
181
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { type ComponentPropsWithRef, type ReactNode } from 'react';
|
|
2
|
+
export interface FilterPanelProps {
|
|
3
|
+
/** El nombre del listado (p. ej. «Comprobantes de venta»): el subtítulo del panel. */
|
|
4
|
+
listName: ReactNode;
|
|
5
|
+
/** Las secciones (FilterPanelSection) que arma la pantalla, p. ej. «A la vista en la barra» y «Más filtros». */
|
|
6
|
+
children: ReactNode;
|
|
7
|
+
/**
|
|
8
|
+
* Los chips de los filtros aplicados (los mismos FilterChip de la fila de la barra), como lista: van en la sección
|
|
9
|
+
* «Aplicados», en un AppliedFilters sin «Limpiar filtros». Sin chips, la sección no aparece.
|
|
10
|
+
*/
|
|
11
|
+
applied?: ReactNode;
|
|
12
|
+
/** Con `onClear`, a la izquierda del pie va «Limpiar filtros» (Button ghost sm). */
|
|
13
|
+
onClear?: (() => void) | undefined;
|
|
14
|
+
/** Texto de `onClear`. Por defecto «Limpiar filtros». */
|
|
15
|
+
clearLabel?: string | undefined;
|
|
16
|
+
/** Texto del botón del pie que cierra el panel (Button primary sm), p. ej. «Ver los 7 comprobantes». Por defecto «Ver resultados». */
|
|
17
|
+
submitLabel?: string | undefined;
|
|
18
|
+
/** Texto del disparador. Por defecto «Filtrar». */
|
|
19
|
+
triggerLabel?: string | undefined;
|
|
20
|
+
/** Título del panel. Por defecto «Filtros». */
|
|
21
|
+
title?: string | undefined;
|
|
22
|
+
/** Título de la sección de los chips. Por defecto «Aplicados». */
|
|
23
|
+
appliedLabel?: string | undefined;
|
|
24
|
+
/** Abierto (controlado). Sin `open`, el panel maneja su propio estado. */
|
|
25
|
+
open?: boolean | undefined;
|
|
26
|
+
onOpenChange?: ((open: boolean) => void) | undefined;
|
|
27
|
+
}
|
|
28
|
+
export interface FilterPanelSectionProps extends Omit<ComponentPropsWithRef<'section'>, 'title'> {
|
|
29
|
+
/** El título chico de la sección (como el título de un grupo de FilterOptions). */
|
|
30
|
+
title: string;
|
|
31
|
+
children: ReactNode;
|
|
32
|
+
}
|
|
33
|
+
export interface FilterFieldProps {
|
|
34
|
+
/** La etiqueta visible arriba, como la de Field (p. ej. «Punto de venta»). Nombra el campo y el popover. */
|
|
35
|
+
label: string;
|
|
36
|
+
/** El valor a la vista («Mes actual»). Vacío y sin `values`: `placeholder`, apagado. */
|
|
37
|
+
value?: string | undefined;
|
|
38
|
+
/** Varios valores, resumidos como en FilterChip: «Mayorista, Distribuidor y 2 más». */
|
|
39
|
+
values?: readonly string[] | undefined;
|
|
40
|
+
/** Cuántos valores se muestran antes de «y N más». Por defecto 2. */
|
|
41
|
+
maxValues?: number | undefined;
|
|
42
|
+
/** Sin valor. Por defecto «Cualquiera». */
|
|
43
|
+
placeholder?: string | undefined;
|
|
44
|
+
/** Lo que se abre: el mismo contenido que en la barra (FilterOptions, FilterPeriod, FilterSearch o FilterAmountRange). */
|
|
45
|
+
children: ReactNode;
|
|
46
|
+
/** Se suma a `dx-filter-field`. */
|
|
47
|
+
className?: string | undefined;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* El panel «Filtrar»: un Drawer de ancho detail (el panel, el velo, el foco y el cierre son los de Drawer) que se abre con un
|
|
51
|
+
* Button secondary sm «Filtrar» con el ícono de filtros, puesto en el lugar del componente (en la barra, después de los
|
|
52
|
+
* filtros a la vista). Título «Filtros», el nombre del listado como subtítulo, «Aplicados» con los chips, las secciones de la
|
|
53
|
+
* pantalla y, en el pie, «Limpiar filtros» y el botón que cierra («Ver resultados»). Todo se aplica al elegir.
|
|
54
|
+
*/
|
|
55
|
+
export declare function FilterPanel({ listName, children, applied, onClear, clearLabel, submitLabel, triggerLabel, title, appliedLabel, open, onOpenChange, }: FilterPanelProps): import("react").JSX.Element;
|
|
56
|
+
/** Una sección del panel: `<section>` nombrada por su título chico (h3). */
|
|
57
|
+
export declare function FilterPanelSection({ title, children, className, ...rest }: FilterPanelSectionProps): import("react").JSX.Element;
|
|
58
|
+
/**
|
|
59
|
+
* Un filtro dentro del panel: la etiqueta arriba (como Field) y un botón con aspecto de campo (el alto de los campos, la flecha
|
|
60
|
+
* a la derecha) con el valor o «Cualquiera», que abre un Popover debajo con el mismo contenido que en la barra, como mínimo del
|
|
61
|
+
* ancho del campo. El nombre del botón es la etiqueta y el valor.
|
|
62
|
+
*/
|
|
63
|
+
export declare function FilterField({ label, value, values, maxValues, placeholder, children, className }: FilterFieldProps): import("react").JSX.Element;
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
+
import { Children, useId, useRef, useState } from 'react';
|
|
4
|
+
import { Button } from '../button/index.js';
|
|
5
|
+
import { Drawer, DrawerContent, DrawerTrigger } from '../drawer/index.js';
|
|
6
|
+
import { Popover, PopoverContent, PopoverTrigger } from '../popover/index.js';
|
|
7
|
+
import { AppliedFilters } from './AppliedFilters.js';
|
|
8
|
+
import { summarizeValues } from './format.js';
|
|
9
|
+
const cx = (own, extra) => (extra ? own + ' ' + extra : own);
|
|
10
|
+
/** Líneas con controles deslizantes (16px): los trazos de SlidersHorizontal de lucide (ISC), en línea. */
|
|
11
|
+
const SlidersIcon = () => (_jsx("svg", { viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", focusable: "false", children: _jsx("path", { d: "M21 4h-7M10 4H3M21 12h-9M8 12H3M21 20h-5M12 20H3M14 2v4M8 10v4M16 18v4" }) }));
|
|
12
|
+
/** Flecha hacia abajo de 16px, la del disparador de Select. */
|
|
13
|
+
const Chevron = () => (_jsx("svg", { viewBox: "0 0 16 16", width: "16", height: "16", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", focusable: "false", children: _jsx("path", { d: "M4 6l4 4 4-4" }) }));
|
|
14
|
+
/**
|
|
15
|
+
* El panel «Filtrar»: un Drawer de ancho detail (el panel, el velo, el foco y el cierre son los de Drawer) que se abre con un
|
|
16
|
+
* Button secondary sm «Filtrar» con el ícono de filtros, puesto en el lugar del componente (en la barra, después de los
|
|
17
|
+
* filtros a la vista). Título «Filtros», el nombre del listado como subtítulo, «Aplicados» con los chips, las secciones de la
|
|
18
|
+
* pantalla y, en el pie, «Limpiar filtros» y el botón que cierra («Ver resultados»). Todo se aplica al elegir.
|
|
19
|
+
*/
|
|
20
|
+
export function FilterPanel({ listName, children, applied, onClear, clearLabel = 'Limpiar filtros', submitLabel = 'Ver resultados', triggerLabel = 'Filtrar', title = 'Filtros', appliedLabel = 'Aplicados', open, onOpenChange, }) {
|
|
21
|
+
const [ownOpen, setOwnOpen] = useState(false);
|
|
22
|
+
const isOpen = open ?? ownOpen;
|
|
23
|
+
const setOpen = (next) => {
|
|
24
|
+
if (open === undefined)
|
|
25
|
+
setOwnOpen(next);
|
|
26
|
+
onOpenChange?.(next);
|
|
27
|
+
};
|
|
28
|
+
const body = useRef(null);
|
|
29
|
+
const hasApplied = Children.toArray(applied).length > 0;
|
|
30
|
+
const footer = (_jsxs("div", { className: "dx-filter-panel__footer", children: [onClear && _jsx(Button, { variant: "ghost", size: "sm", onClick: onClear, children: clearLabel }), _jsx(Button, { variant: "primary", size: "sm", className: "dx-filter-panel__submit", onClick: () => { setOpen(false); }, children: submitLabel })] }));
|
|
31
|
+
return (_jsxs(Drawer, { open: isOpen, onOpenChange: setOpen, children: [_jsx(DrawerTrigger, { children: _jsx(Button, { size: "sm", iconStart: _jsx(SlidersIcon, {}), className: "dx-filter-panel__trigger", children: triggerLabel }) }), _jsx(DrawerContent, { title: title, subtitle: listName, width: "detail", footer: footer, children: _jsxs("div", { className: "dx-filter-panel", ref: body, tabIndex: -1, children: [hasApplied && (_jsx(FilterPanelSection, { title: appliedLabel, children: _jsx(AppliedFilters, { "aria-label": appliedLabel, returnFocusRef: body, children: applied }) })), children] }) })] }));
|
|
32
|
+
}
|
|
33
|
+
/** Una sección del panel: `<section>` nombrada por su título chico (h3). */
|
|
34
|
+
export function FilterPanelSection({ title, children, className, ...rest }) {
|
|
35
|
+
const id = useId();
|
|
36
|
+
return (_jsxs("section", { ...rest, "aria-labelledby": id, className: cx('dx-filter-panel__section', className), children: [_jsx("h3", { className: "dx-filter-panel__title", id: id, children: title }), _jsx("div", { className: "dx-filter-panel__content", children: children })] }));
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Un filtro dentro del panel: la etiqueta arriba (como Field) y un botón con aspecto de campo (el alto de los campos, la flecha
|
|
40
|
+
* a la derecha) con el valor o «Cualquiera», que abre un Popover debajo con el mismo contenido que en la barra, como mínimo del
|
|
41
|
+
* ancho del campo. El nombre del botón es la etiqueta y el valor.
|
|
42
|
+
*/
|
|
43
|
+
export function FilterField({ label, value, values, maxValues = 2, placeholder = 'Cualquiera', children, className }) {
|
|
44
|
+
const id = useId();
|
|
45
|
+
const labelId = id + '-etiqueta';
|
|
46
|
+
const valueId = id + '-valor';
|
|
47
|
+
const text = values && values.length > 0 ? summarizeValues(values, maxValues) : (value ?? '');
|
|
48
|
+
const empty = text === '';
|
|
49
|
+
return (_jsxs("div", { className: cx('dx-filter-field', className), children: [_jsx("span", { className: "dx-filter-field__label", id: labelId, children: label }), _jsxs(Popover, { children: [_jsx(PopoverTrigger, { children: _jsxs("button", { type: "button", className: "dx-filter-field__control", "aria-labelledby": labelId + ' ' + valueId, "data-empty": empty ? 'true' : undefined, children: [_jsx("span", { className: "dx-filter-field__value", id: valueId, children: empty ? placeholder : text }), _jsx("span", { className: "dx-filter-field__icon", children: _jsx(Chevron, {}) })] }) }), _jsx(PopoverContent, { "aria-label": label, matchTriggerWidth: true, children: children })] })] }));
|
|
50
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { type FilterPeriodPreset, type FilterPeriodValue } from './format.js';
|
|
2
|
+
export interface FilterPeriodProps {
|
|
3
|
+
/** `{ preset }`, `{ from?, to? }` (ISO aaaa-mm-dd) o `null`. La app calcula qué fechas son cada período. */
|
|
4
|
+
value: FilterPeriodValue;
|
|
5
|
+
onValueChange: (value: FilterPeriodValue) => void;
|
|
6
|
+
/** Nombre de la lista de períodos (p. ej. «Fecha»). Obligatorio. */
|
|
7
|
+
'aria-label': string;
|
|
8
|
+
/** Los períodos. Por defecto, FILTER_PERIOD_PRESETS (Hoy, Semana actual… Último año). */
|
|
9
|
+
presets?: readonly FilterPeriodPreset[] | undefined;
|
|
10
|
+
/** La última opción, que abre los campos. Por defecto «Entre fechas». */
|
|
11
|
+
rangeLabel?: string | undefined;
|
|
12
|
+
/** Etiquetas de los campos. Por defecto «Desde» y «Hasta». */
|
|
13
|
+
fromLabel?: string | undefined;
|
|
14
|
+
toLabel?: string | undefined;
|
|
15
|
+
/** Error cuando Hasta es anterior a Desde. Por defecto «La fecha final es anterior a la inicial». */
|
|
16
|
+
rangeErrorText?: string | undefined;
|
|
17
|
+
/** Se suma a `dx-filter-period`. */
|
|
18
|
+
className?: string | undefined;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Filtro de período, para ir dentro de un PopoverContent. Arriba, la lista de períodos (FilterOptions de un valor): elegir uno
|
|
22
|
+
* marca, aplica y cierra. Al final, «Entre fechas»: no cierra, abre los campos Desde y Hasta (Input type="date") y lleva el
|
|
23
|
+
* foco a Desde. Aplica cada vez que un campo queda con una fecha completa; vaciar los dos deja `null`. Sin «Aplicar».
|
|
24
|
+
*/
|
|
25
|
+
export declare function FilterPeriod({ value, onValueChange, 'aria-label': ariaLabel, presets, rangeLabel, fromLabel, toLabel, rangeErrorText, className, }: FilterPeriodProps): import("react").JSX.Element;
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
+
import { useLayoutEffect, useRef, useState } from 'react';
|
|
4
|
+
import { Field } from '../field/index.js';
|
|
5
|
+
import { Input } from '../input/index.js';
|
|
6
|
+
import { FilterOptions } from './FilterOptions.js';
|
|
7
|
+
import { FILTER_PERIOD_PRESETS, isPeriodPreset } from './format.js';
|
|
8
|
+
/**
|
|
9
|
+
* Fecha máxima de los dos campos: el año en 4 cifras. Las fechas se comparan como texto ISO (aaaa-mm-dd), y un año de 5 cifras
|
|
10
|
+
* («10000-01-01») quedaría antes que «2026-11-01».
|
|
11
|
+
*/
|
|
12
|
+
const MAX_DATE = '9999-12-31';
|
|
13
|
+
/** Clave interna de «Entre fechas» en la lista: no puede chocar con la de un período (las claves no llevan «\u0000»). */
|
|
14
|
+
const RANGE = '\u0000entre-fechas';
|
|
15
|
+
const cx = (own, extra) => (extra ? own + ' ' + extra : own);
|
|
16
|
+
/**
|
|
17
|
+
* Filtro de período, para ir dentro de un PopoverContent. Arriba, la lista de períodos (FilterOptions de un valor): elegir uno
|
|
18
|
+
* marca, aplica y cierra. Al final, «Entre fechas»: no cierra, abre los campos Desde y Hasta (Input type="date") y lleva el
|
|
19
|
+
* foco a Desde. Aplica cada vez que un campo queda con una fecha completa; vaciar los dos deja `null`. Sin «Aplicar».
|
|
20
|
+
*/
|
|
21
|
+
export function FilterPeriod({ value, onValueChange, 'aria-label': ariaLabel, presets = FILTER_PERIOD_PRESETS, rangeLabel = 'Entre fechas', fromLabel = 'Desde', toLabel = 'Hasta', rangeErrorText = 'La fecha final es anterior a la inicial', className, }) {
|
|
22
|
+
const initialRange = value !== null && !isPeriodPreset(value) ? value : null;
|
|
23
|
+
const [rangeOpen, setRangeOpen] = useState(initialRange !== null);
|
|
24
|
+
const [from, setFrom] = useState(initialRange?.from ?? '');
|
|
25
|
+
const [to, setTo] = useState(initialRange?.to ?? '');
|
|
26
|
+
const fromInput = useRef(null);
|
|
27
|
+
const focusFrom = useRef(false);
|
|
28
|
+
// Después de elegir «Entre fechas», con los campos ya en el DOM: el foco va a Desde.
|
|
29
|
+
useLayoutEffect(() => {
|
|
30
|
+
if (!focusFrom.current)
|
|
31
|
+
return;
|
|
32
|
+
focusFrom.current = false;
|
|
33
|
+
fromInput.current?.focus();
|
|
34
|
+
});
|
|
35
|
+
// ISO aaaa-mm-dd se ordena como texto.
|
|
36
|
+
const reversed = from !== '' && to !== '' && to < from;
|
|
37
|
+
const apply = (f, t) => {
|
|
38
|
+
if (f !== '' && t !== '' && t < f)
|
|
39
|
+
return;
|
|
40
|
+
if (f === '' && t === '') {
|
|
41
|
+
onValueChange(null);
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
onValueChange({ ...(f ? { from: f } : {}), ...(t ? { to: t } : {}) });
|
|
45
|
+
};
|
|
46
|
+
// Un campo de fecha a medio escribir vale '' con badInput: no se aplica hasta que la fecha esté completa (o vacía de verdad).
|
|
47
|
+
const change = (which) => (event) => {
|
|
48
|
+
const next = event.target.value;
|
|
49
|
+
if (which === 'from')
|
|
50
|
+
setFrom(next);
|
|
51
|
+
else
|
|
52
|
+
setTo(next);
|
|
53
|
+
if (event.target.validity.badInput)
|
|
54
|
+
return;
|
|
55
|
+
if (which === 'from')
|
|
56
|
+
apply(next, to);
|
|
57
|
+
else
|
|
58
|
+
apply(from, next);
|
|
59
|
+
};
|
|
60
|
+
const options = [...presets.map((p) => ({ value: p.value, label: p.label })), { value: RANGE, label: rangeLabel, keepOpen: true }];
|
|
61
|
+
const listValue = rangeOpen ? RANGE : value !== null && isPeriodPreset(value) ? value.preset : null;
|
|
62
|
+
return (_jsxs("div", { className: cx('dx-filter-period', className), children: [_jsx(FilterOptions, { "aria-label": ariaLabel, options: options, value: listValue, searchable: false, onValueChange: (chosen) => {
|
|
63
|
+
if (chosen === RANGE) {
|
|
64
|
+
focusFrom.current = true;
|
|
65
|
+
setRangeOpen(true);
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
setRangeOpen(false);
|
|
69
|
+
onValueChange({ preset: chosen });
|
|
70
|
+
} }), rangeOpen && (_jsxs("div", { className: "dx-filter-period__range", children: [_jsx(Field, { label: fromLabel, children: _jsx(Input, { ref: fromInput, type: "date", value: from, max: MAX_DATE, onChange: change('from') }) }), _jsx(Field, { label: toLabel, error: reversed ? rangeErrorText : undefined, children: _jsx(Input, { type: "date", value: to, min: from || undefined, max: MAX_DATE, onChange: change('to') }) })] }))] }));
|
|
71
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { type FilterOption } from './FilterOptions.js';
|
|
2
|
+
/** Busca en el servidor: devuelve las opciones para `query`. Con `signal` abortado, la respuesta ya no se usa. */
|
|
3
|
+
export type FilterSearchLoader = (query: string, signal: AbortSignal) => Promise<readonly FilterOption[]>;
|
|
4
|
+
interface FilterSearchBase {
|
|
5
|
+
/** Busca las opciones (la app, en el servidor). El componente no filtra: muestra lo que devuelve. */
|
|
6
|
+
loadOptions: FilterSearchLoader;
|
|
7
|
+
/** Nombre de la lista (p. ej. «Cliente»). Obligatorio. */
|
|
8
|
+
'aria-label': string;
|
|
9
|
+
/** Lo elegido, con su texto (el valor es solo el id): se ve primero mientras no se busca, y da el texto al elegir. */
|
|
10
|
+
selectedOptions?: readonly FilterOption[] | undefined;
|
|
11
|
+
/** Lo que se muestra antes de buscar, después de lo elegido (p. ej. los clientes usados hace poco). */
|
|
12
|
+
defaultOptions?: readonly FilterOption[] | undefined;
|
|
13
|
+
/** Letras mínimas para buscar. Por defecto 2. */
|
|
14
|
+
minQueryLength?: number | undefined;
|
|
15
|
+
/** Nombre y placeholder del campo. Por defecto «Buscar». */
|
|
16
|
+
searchLabel?: string | undefined;
|
|
17
|
+
/** Aviso con menos letras y nada para mostrar. Por defecto «Escribí al menos {minQueryLength} letras para buscar». */
|
|
18
|
+
minQueryText?: string | undefined;
|
|
19
|
+
/** Sin resultados. Por defecto «No hay coincidencias». */
|
|
20
|
+
emptyText?: string | undefined;
|
|
21
|
+
/** Si loadOptions falla. Por defecto «No se pudo buscar». */
|
|
22
|
+
errorText?: string | undefined;
|
|
23
|
+
/** Botón que repite la última búsqueda. Por defecto «Reintentar». */
|
|
24
|
+
retryLabel?: string | undefined;
|
|
25
|
+
/** Se suma a `dx-filter-options`. */
|
|
26
|
+
className?: string | undefined;
|
|
27
|
+
}
|
|
28
|
+
export interface FilterSearchSingleProps extends FilterSearchBase {
|
|
29
|
+
/** Un valor (por defecto): elegir cierra el Popover que la envuelve. */
|
|
30
|
+
multiple?: false | undefined;
|
|
31
|
+
value: string | null;
|
|
32
|
+
/** El id elegido y su opción (con el texto, para el chip). */
|
|
33
|
+
onValueChange: (value: string, option: FilterOption | undefined) => void;
|
|
34
|
+
onClear?: undefined;
|
|
35
|
+
clearLabel?: undefined;
|
|
36
|
+
}
|
|
37
|
+
export interface FilterSearchMultipleProps extends FilterSearchBase {
|
|
38
|
+
/** Varios valores: marcar no cierra; con `onClear`, «Quitar filtro». */
|
|
39
|
+
multiple: true;
|
|
40
|
+
value: readonly string[];
|
|
41
|
+
/** Los ids elegidos y sus opciones (con el texto, para el chip), en el mismo orden. */
|
|
42
|
+
onValueChange: (value: string[], options: FilterOption[]) => void;
|
|
43
|
+
onClear?: (() => void) | undefined;
|
|
44
|
+
clearLabel?: string | undefined;
|
|
45
|
+
}
|
|
46
|
+
export type FilterSearchProps = FilterSearchSingleProps | FilterSearchMultipleProps;
|
|
47
|
+
/**
|
|
48
|
+
* Búsqueda de un registro (Cliente, Proveedor, Vendedor) entre cientos o miles, para ir dentro de un PopoverContent. Usa
|
|
49
|
+
* FilterOptions por dentro (mismo teclado, combobox, opciones, uno o varios valores y «Quitar filtro»), siempre con el campo
|
|
50
|
+
* para buscar. Busca con `loadOptions` 300 ms después de dejar de escribir, cancela la anterior (AbortSignal) e ignora las
|
|
51
|
+
* respuestas viejas. Con menos de `minQueryLength` letras: lo elegido, `defaultOptions` o el aviso.
|
|
52
|
+
*/
|
|
53
|
+
export declare function FilterSearch(props: FilterSearchProps): import("react").JSX.Element;
|
|
54
|
+
export {};
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
+
import { useEffect, useRef, useState } from 'react';
|
|
4
|
+
import { Button } from '../button/index.js';
|
|
5
|
+
import { FilterOptions } from './FilterOptions.js';
|
|
6
|
+
/** Espera después de la última tecla antes de buscar, en ms. */
|
|
7
|
+
const DEBOUNCE_MS = 300;
|
|
8
|
+
/**
|
|
9
|
+
* Búsqueda de un registro (Cliente, Proveedor, Vendedor) entre cientos o miles, para ir dentro de un PopoverContent. Usa
|
|
10
|
+
* FilterOptions por dentro (mismo teclado, combobox, opciones, uno o varios valores y «Quitar filtro»), siempre con el campo
|
|
11
|
+
* para buscar. Busca con `loadOptions` 300 ms después de dejar de escribir, cancela la anterior (AbortSignal) e ignora las
|
|
12
|
+
* respuestas viejas. Con menos de `minQueryLength` letras: lo elegido, `defaultOptions` o el aviso.
|
|
13
|
+
*/
|
|
14
|
+
export function FilterSearch(props) {
|
|
15
|
+
const { loadOptions, 'aria-label': ariaLabel, selectedOptions = [], defaultOptions = [], minQueryLength = 2, searchLabel = 'Buscar', minQueryText, emptyText = 'No hay coincidencias', errorText = 'No se pudo buscar', retryLabel = 'Reintentar', className, } = props;
|
|
16
|
+
const [query, setQuery] = useState('');
|
|
17
|
+
const [results, setResults] = useState({ kind: 'idle' });
|
|
18
|
+
const [searching, setSearching] = useState(false);
|
|
19
|
+
const timer = useRef(undefined);
|
|
20
|
+
const controller = useRef(null);
|
|
21
|
+
const seq = useRef(0);
|
|
22
|
+
/** Las opciones que llegaron de las búsquedas, por id: con lo elegido y las por defecto, dan el texto al elegir. */
|
|
23
|
+
const known = useRef(new Map());
|
|
24
|
+
const cancel = () => {
|
|
25
|
+
clearTimeout(timer.current);
|
|
26
|
+
controller.current?.abort();
|
|
27
|
+
controller.current = null;
|
|
28
|
+
};
|
|
29
|
+
useEffect(() => cancel, []);
|
|
30
|
+
/** Busca ya: cancela la anterior y usa la respuesta solo si sigue siendo la última. */
|
|
31
|
+
const search = (text) => {
|
|
32
|
+
cancel();
|
|
33
|
+
const id = ++seq.current;
|
|
34
|
+
const ac = new AbortController();
|
|
35
|
+
controller.current = ac;
|
|
36
|
+
setSearching(true);
|
|
37
|
+
loadOptions(text, ac.signal).then((options) => {
|
|
38
|
+
if (id !== seq.current || ac.signal.aborted)
|
|
39
|
+
return;
|
|
40
|
+
for (const o of options)
|
|
41
|
+
known.current.set(o.value, o);
|
|
42
|
+
setResults({ kind: 'done', query: text, options });
|
|
43
|
+
setSearching(false);
|
|
44
|
+
}, () => {
|
|
45
|
+
if (id !== seq.current || ac.signal.aborted)
|
|
46
|
+
return;
|
|
47
|
+
setResults({ kind: 'error', query: text });
|
|
48
|
+
setSearching(false);
|
|
49
|
+
});
|
|
50
|
+
};
|
|
51
|
+
const long = (text) => text.trim().length >= minQueryLength;
|
|
52
|
+
const onQueryChange = (text) => {
|
|
53
|
+
setQuery(text);
|
|
54
|
+
if (!long(text)) {
|
|
55
|
+
// Con menos letras no busca: se cancela lo pendiente y se vuelve a lo elegido y las por defecto.
|
|
56
|
+
cancel();
|
|
57
|
+
seq.current++;
|
|
58
|
+
setSearching(false);
|
|
59
|
+
setResults({ kind: 'idle' });
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
clearTimeout(timer.current);
|
|
63
|
+
// Desde que el texto llega al mínimo ya se ve el estado de búsqueda (los resultados previos con aria-busy, o Skeleton),
|
|
64
|
+
// también durante la espera: la lista no queda vacía y sin aviso.
|
|
65
|
+
setSearching(true);
|
|
66
|
+
timer.current = setTimeout(() => { search(text.trim()); }, DEBOUNCE_MS);
|
|
67
|
+
};
|
|
68
|
+
// Con minQueryLength 0, busca apenas se abre (sin texto), fuera del render del efecto.
|
|
69
|
+
useEffect(() => {
|
|
70
|
+
if (minQueryLength <= 0)
|
|
71
|
+
timer.current = setTimeout(() => { search(''); }, 0);
|
|
72
|
+
// Solo al montar: después busca cada cambio del texto.
|
|
73
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
74
|
+
}, []);
|
|
75
|
+
// Lo que se ve: sin buscar, lo elegido y después las por defecto (sin repetir); buscando, los resultados.
|
|
76
|
+
const idle = results.kind === 'idle' && !searching;
|
|
77
|
+
const resting = [...selectedOptions, ...defaultOptions.filter((d) => !selectedOptions.some((s) => s.value === d.value))];
|
|
78
|
+
const previous = results.kind === 'done' ? results.options : [];
|
|
79
|
+
const shown = results.kind === 'idle' ? (long(query) ? [] : resting) : results.kind === 'done' ? previous : [];
|
|
80
|
+
// Buscando sin resultados a la vista: Skeleton. Con resultados previos: quedan, con aria-busy.
|
|
81
|
+
const skeleton = searching && shown.length === 0;
|
|
82
|
+
let status = null;
|
|
83
|
+
if (results.kind === 'error' && !searching) {
|
|
84
|
+
status = (_jsxs("span", { className: "dx-filter-options__notice", children: [_jsx("span", { children: errorText }), _jsx(Button, { variant: "ghost", size: "xs", onClick: () => { search(results.query); }, children: retryLabel })] }));
|
|
85
|
+
}
|
|
86
|
+
else if (results.kind === 'done' && !searching && results.options.length === 0) {
|
|
87
|
+
status = emptyText;
|
|
88
|
+
}
|
|
89
|
+
else if (idle && !long(query) && resting.length === 0) {
|
|
90
|
+
status = minQueryText ?? 'Escribí al menos ' + String(minQueryLength) + ' letras para buscar';
|
|
91
|
+
}
|
|
92
|
+
const common = {
|
|
93
|
+
'aria-label': ariaLabel, options: shown, searchable: true, searchLabel, query, onQueryChange, filter: false,
|
|
94
|
+
loading: skeleton, busy: searching, status, className,
|
|
95
|
+
};
|
|
96
|
+
/** Al elegir: el texto de cada id, de los resultados que llegaron, lo elegido o las por defecto. */
|
|
97
|
+
const lookup = () => new Map([...known.current, ...[...defaultOptions, ...selectedOptions].map((o) => [o.value, o])]);
|
|
98
|
+
const optionsOf = (ids) => { const map = lookup(); return ids.flatMap((id) => { const o = map.get(id); return o ? [o] : []; }); };
|
|
99
|
+
return props.multiple ? (_jsx(FilterOptions, { ...common, multiple: true, value: props.value, onValueChange: (next) => { props.onValueChange(next, optionsOf(next)); }, onClear: props.onClear, clearLabel: props.clearLabel })) : (_jsx(FilterOptions, { ...common, value: props.value, onValueChange: (next) => { props.onValueChange(next, lookup().get(next)); } }));
|
|
100
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { type ComponentPropsWithRef, type ReactNode } from 'react';
|
|
2
|
+
export interface FilterToggleProps extends Omit<ComponentPropsWithRef<'button'>, 'children' | 'aria-pressed'> {
|
|
3
|
+
/** Nombre del filtro de sí o no (p. ej. «Con saldo»). */
|
|
4
|
+
label: ReactNode;
|
|
5
|
+
/** Prendido (controlado). Sin `pressed`, el botón maneja su propio estado. */
|
|
6
|
+
pressed?: boolean | undefined;
|
|
7
|
+
/** Prendido al montar (no controlado). Por defecto `false`. */
|
|
8
|
+
defaultPressed?: boolean | undefined;
|
|
9
|
+
onPressedChange?: ((pressed: boolean) => void) | undefined;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Filtro de sí o no en la barra: un Button secondary sm con `aria-pressed`, con el aspecto de FilterButton y sin flecha.
|
|
13
|
+
* Apagado, el signo más antes de la etiqueta; prendido, como FilterButton con `active` (etiqueta en `--dx-fg`, peso 500 y el
|
|
14
|
+
* punto). El estado lo anuncia `aria-pressed`.
|
|
15
|
+
*/
|
|
16
|
+
export declare function FilterToggle({ label, pressed, defaultPressed, onPressedChange, onClick, className, ...rest }: FilterToggleProps): import("react").JSX.Element;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
+
import { useState } from 'react';
|
|
4
|
+
import { Button } from '../button/index.js';
|
|
5
|
+
const cx = (own, extra) => (extra ? own + ' ' + extra : own);
|
|
6
|
+
/** Signo más de 14px: el trazo de Plus de lucide (ISC), en línea porque @dubix/ui no depende de lucide-react. */
|
|
7
|
+
const Plus = () => (_jsxs("svg", { viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", focusable: "false", children: [_jsx("path", { d: "M5 12h14" }), _jsx("path", { d: "M12 5v14" })] }));
|
|
8
|
+
/**
|
|
9
|
+
* Filtro de sí o no en la barra: un Button secondary sm con `aria-pressed`, con el aspecto de FilterButton y sin flecha.
|
|
10
|
+
* Apagado, el signo más antes de la etiqueta; prendido, como FilterButton con `active` (etiqueta en `--dx-fg`, peso 500 y el
|
|
11
|
+
* punto). El estado lo anuncia `aria-pressed`.
|
|
12
|
+
*/
|
|
13
|
+
export function FilterToggle({ label, pressed, defaultPressed = false, onPressedChange, onClick, className, ...rest }) {
|
|
14
|
+
const [own, setOwn] = useState(defaultPressed);
|
|
15
|
+
const on = pressed ?? own;
|
|
16
|
+
return (_jsxs(Button, { ...rest, variant: "secondary", size: "sm", className: cx('dx-filter-btn', className), "data-active": on ? 'true' : undefined, "aria-pressed": on, iconStart: on ? undefined : _jsx(Plus, {}), onClick: (event) => {
|
|
17
|
+
onClick?.(event);
|
|
18
|
+
if (event.defaultPrevented)
|
|
19
|
+
return;
|
|
20
|
+
if (pressed === undefined)
|
|
21
|
+
setOwn(!on);
|
|
22
|
+
onPressedChange?.(!on);
|
|
23
|
+
}, children: [_jsx("span", { className: "dx-filter-btn__label", children: label }), on && _jsx("span", { className: "dx-filter-btn__dot", "aria-hidden": "true" })] }));
|
|
24
|
+
}
|