@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,61 @@
|
|
|
1
|
+
import { type AriaAttributes, type ReactNode, type Ref } from 'react';
|
|
2
|
+
/** Estado de la casilla: marcada, sin marcar o indeterminada (p. ej. «seleccionar todas» con algunas filas elegidas). */
|
|
3
|
+
export type CheckboxChecked = boolean | 'indeterminate';
|
|
4
|
+
interface CheckboxBaseProps {
|
|
5
|
+
/** Estado (controlado). Sin `checked`, la casilla maneja su propio estado. */
|
|
6
|
+
checked?: CheckboxChecked | undefined;
|
|
7
|
+
/** Estado al montar (no controlado). Por defecto `false`. */
|
|
8
|
+
defaultChecked?: CheckboxChecked | undefined;
|
|
9
|
+
/** Se llama con el estado nuevo: un clic en una indeterminada la marca (`true`). */
|
|
10
|
+
onCheckedChange?: ((checked: CheckboxChecked) => void) | undefined;
|
|
11
|
+
/** Texto chico debajo de la etiqueta; describe la casilla (`aria-describedby`). */
|
|
12
|
+
description?: ReactNode;
|
|
13
|
+
disabled?: boolean | undefined;
|
|
14
|
+
/** Dentro de un `<form>`: la casilla tiene que estar marcada para enviarlo (validación nativa). */
|
|
15
|
+
required?: boolean | undefined;
|
|
16
|
+
/** Nombre del campo en el formulario: el valor viaja en el `<input type="checkbox">` oculto de Radix. */
|
|
17
|
+
name?: string | undefined;
|
|
18
|
+
/** Valor que se envía marcada. Por defecto `on`, como el checkbox nativo. */
|
|
19
|
+
value?: string | undefined;
|
|
20
|
+
/** id del `<form>` al que pertenece, si no está adentro. */
|
|
21
|
+
form?: string | undefined;
|
|
22
|
+
/** Van a la casilla (`<button role="checkbox">`). */
|
|
23
|
+
id?: string | undefined;
|
|
24
|
+
'aria-describedby'?: string | undefined;
|
|
25
|
+
/** Con error: borde y halo `--dx-danger-mark`, como Input. */
|
|
26
|
+
'aria-invalid'?: AriaAttributes['aria-invalid'];
|
|
27
|
+
/** Se suma a `dx-checkbox`, en el contenedor. */
|
|
28
|
+
className?: string | undefined;
|
|
29
|
+
/** La casilla (`<button role="checkbox">`). */
|
|
30
|
+
ref?: Ref<HTMLButtonElement> | undefined;
|
|
31
|
+
}
|
|
32
|
+
/** Con `label`, la etiqueta visible la nombra; sin `label`, hace falta `aria-label` o `aria-labelledby` (p. ej. en una fila de tabla). */
|
|
33
|
+
type CheckboxNameProps = {
|
|
34
|
+
label: ReactNode;
|
|
35
|
+
'aria-label'?: string | undefined;
|
|
36
|
+
'aria-labelledby'?: string | undefined;
|
|
37
|
+
} | {
|
|
38
|
+
label?: undefined;
|
|
39
|
+
'aria-label': string;
|
|
40
|
+
'aria-labelledby'?: string | undefined;
|
|
41
|
+
} | {
|
|
42
|
+
label?: undefined;
|
|
43
|
+
'aria-label'?: string | undefined;
|
|
44
|
+
'aria-labelledby': string;
|
|
45
|
+
};
|
|
46
|
+
export type CheckboxProps = CheckboxBaseProps & CheckboxNameProps;
|
|
47
|
+
/**
|
|
48
|
+
* Interno (no está en el index de la entrada): la caja de Checkbox solo para ver, con `aria-hidden`, para una opción que ya
|
|
49
|
+
* es interactiva (las listas de varios valores de FilterOptions, donde no se anidan botones). Mismas clases y glifos.
|
|
50
|
+
*/
|
|
51
|
+
export declare function CheckboxMark({ checked }: {
|
|
52
|
+
checked: CheckboxChecked;
|
|
53
|
+
}): import("react").JSX.Element;
|
|
54
|
+
/**
|
|
55
|
+
* Casilla de verificación sobre Checkbox de Radix: `<button role="checkbox">` de 16px con `aria-checked` (`mixed` en
|
|
56
|
+
* indeterminado), Espacio la cambia, y dentro de un `<form>` Radix agrega un `<input type="checkbox">` oculto con `name`,
|
|
57
|
+
* `value` y `required`. Etiqueta opcional al lado (`<label for>`: el clic en la etiqueta también la cambia) y descripción
|
|
58
|
+
* debajo. El área de clic es de 24 × 24 aunque la caja mida 16.
|
|
59
|
+
*/
|
|
60
|
+
export declare function Checkbox({ checked, defaultChecked, onCheckedChange, label, description, disabled, required, name, value, form, id, className, ref, 'aria-describedby': describedby, ...aria }: CheckboxProps): import("react").JSX.Element;
|
|
61
|
+
export {};
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
+
import { useId, useState } from 'react';
|
|
4
|
+
import { Checkbox as CheckboxPrimitive } from 'radix-ui';
|
|
5
|
+
// Glifos de 12px: los trazos de Check y Minus de lucide (ISC) en su viewBox de 24, en línea porque @dubix/ui no depende de
|
|
6
|
+
// lucide-react. Trazo de 3 (1,5px a 12px; el 2 de lucide queda en 1px). El color es currentColor (--dx-on-primary).
|
|
7
|
+
const Check = () => (_jsx("svg", { className: "dx-checkbox__glyph", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "3", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", focusable: "false", children: _jsx("path", { d: "M20 6 9 17l-5-5" }) }));
|
|
8
|
+
const Minus = () => (_jsx("svg", { className: "dx-checkbox__glyph", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "3", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", focusable: "false", children: _jsx("path", { d: "M5 12h14" }) }));
|
|
9
|
+
const cx = (own, extra) => (extra ? own + ' ' + extra : own);
|
|
10
|
+
/**
|
|
11
|
+
* Interno (no está en el index de la entrada): la caja de Checkbox solo para ver, con `aria-hidden`, para una opción que ya
|
|
12
|
+
* es interactiva (las listas de varios valores de FilterOptions, donde no se anidan botones). Mismas clases y glifos.
|
|
13
|
+
*/
|
|
14
|
+
export function CheckboxMark({ checked }) {
|
|
15
|
+
const state = checked === 'indeterminate' ? 'indeterminate' : checked ? 'checked' : 'unchecked';
|
|
16
|
+
return (_jsx("span", { className: "dx-checkbox", "aria-hidden": "true", children: _jsx("span", { className: "dx-checkbox__box", "data-state": state, children: checked !== false && _jsx("span", { className: "dx-checkbox__indicator", "data-state": state, children: checked === 'indeterminate' ? _jsx(Minus, {}) : _jsx(Check, {}) }) }) }));
|
|
17
|
+
}
|
|
18
|
+
const isBlank = (node) => node == null || typeof node === 'boolean' || node === '';
|
|
19
|
+
/**
|
|
20
|
+
* Casilla de verificación sobre Checkbox de Radix: `<button role="checkbox">` de 16px con `aria-checked` (`mixed` en
|
|
21
|
+
* indeterminado), Espacio la cambia, y dentro de un `<form>` Radix agrega un `<input type="checkbox">` oculto con `name`,
|
|
22
|
+
* `value` y `required`. Etiqueta opcional al lado (`<label for>`: el clic en la etiqueta también la cambia) y descripción
|
|
23
|
+
* debajo. El área de clic es de 24 × 24 aunque la caja mida 16.
|
|
24
|
+
*/
|
|
25
|
+
export function Checkbox({ checked, defaultChecked = false, onCheckedChange, label, description, disabled, required, name, value, form, id, className, ref, 'aria-describedby': describedby, ...aria }) {
|
|
26
|
+
// Checkbox siempre le pasa el estado a Radix (controlado): así sabe qué glifo dibujar, también en el servidor.
|
|
27
|
+
const [own, setOwn] = useState(defaultChecked);
|
|
28
|
+
const current = checked ?? own;
|
|
29
|
+
const change = (next) => {
|
|
30
|
+
if (checked === undefined)
|
|
31
|
+
setOwn(next);
|
|
32
|
+
onCheckedChange?.(next);
|
|
33
|
+
};
|
|
34
|
+
const ownId = useId();
|
|
35
|
+
const descriptionId = useId();
|
|
36
|
+
const boxId = id ?? ownId;
|
|
37
|
+
const hasLabel = !isBlank(label);
|
|
38
|
+
const hasDescription = !isBlank(description);
|
|
39
|
+
const ids = [...(hasDescription ? [descriptionId] : []), ...(describedby ? [describedby] : [])];
|
|
40
|
+
return (_jsxs("span", { className: cx('dx-checkbox', className), children: [_jsx(CheckboxPrimitive.Root, { ...aria, ref: ref, id: boxId, className: "dx-checkbox__box", checked: current, onCheckedChange: change, "aria-describedby": ids.length ? ids.join(' ') : undefined, ...(disabled === undefined ? {} : { disabled }), ...(required === undefined ? {} : { required }), ...(name === undefined ? {} : { name }), ...(value === undefined ? {} : { value }), ...(form === undefined ? {} : { form }), children: _jsx(CheckboxPrimitive.Indicator, { className: "dx-checkbox__indicator", children: current === 'indeterminate' ? _jsx(Minus, {}) : _jsx(Check, {}) }) }), (hasLabel || hasDescription) && (_jsxs("span", { className: "dx-checkbox__text", children: [hasLabel && _jsx("label", { className: "dx-checkbox__label", htmlFor: boxId, children: label }), hasDescription && _jsx("span", { className: "dx-checkbox__description", id: descriptionId, children: description })] }))] }));
|
|
41
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { Checkbox } from './Checkbox.js';
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { type ComponentPropsWithRef, type ReactNode, type RefObject } from 'react';
|
|
2
|
+
export interface AppliedFiltersProps extends Omit<ComponentPropsWithRef<'div'>, 'role' | 'children'> {
|
|
3
|
+
/** Los FilterChip, uno por filtro aplicado. Sin chips, AppliedFilters no dibuja nada. */
|
|
4
|
+
children?: ReactNode;
|
|
5
|
+
/** Nombre del grupo. Por defecto «Filtros aplicados». */
|
|
6
|
+
'aria-label'?: string | undefined;
|
|
7
|
+
/** Con `onClear`, al final va un Button ghost xs para quitar todos los filtros. */
|
|
8
|
+
onClear?: (() => void) | undefined;
|
|
9
|
+
/** Texto del botón de `onClear`. Por defecto «Limpiar filtros». */
|
|
10
|
+
clearLabel?: string | undefined;
|
|
11
|
+
/**
|
|
12
|
+
* Adónde va el foco cuando se quita el último chip con el teclado o el mouse, o después de «Limpiar filtros» (p. ej. el
|
|
13
|
+
* buscador de la barra). AppliedFilters tiene que seguir montado (sin chips no dibuja nada) para poder moverlo.
|
|
14
|
+
*/
|
|
15
|
+
returnFocusRef?: RefObject<HTMLElement | null> | undefined;
|
|
16
|
+
}
|
|
17
|
+
export interface FilterChipProps extends Omit<ComponentPropsWithRef<'button'>, 'children' | 'value'> {
|
|
18
|
+
/** El campo (p. ej. «Etiqueta»). Sin `value` ni `values`, es todo el texto del chip (p. ej. «Solo con saldo»). */
|
|
19
|
+
label: string;
|
|
20
|
+
/** Un valor (p. ej. «Mes actual»). */
|
|
21
|
+
value?: string | undefined;
|
|
22
|
+
/** Varios valores, separados por coma. Si son más que `maxValues`: «Mayorista, Distribuidor y 2 más». */
|
|
23
|
+
values?: readonly string[] | undefined;
|
|
24
|
+
/** Cuántos valores se muestran antes de «y N más». Por defecto 2. */
|
|
25
|
+
maxValues?: number | undefined;
|
|
26
|
+
/** Con `onRemove`, la × para quitar el filtro (`aria-label` «Quitar filtro: {label}»). Sin `onRemove` no hay × (filtro obligatorio). */
|
|
27
|
+
onRemove?: (() => void) | undefined;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Fila de filtros aplicados (`role="group"`, «Filtros aplicados»): los chips en una fila que envuelve y, con `onClear`,
|
|
31
|
+
* «Limpiar filtros». Sin chips no dibuja nada. Al quitar un chip, el foco pasa a la × del chip siguiente; si no hay, a la del
|
|
32
|
+
* anterior; si no queda ninguno, a `returnFocusRef`. Lo mismo si desaparece el chip que tenía el foco o que abrió el popover
|
|
33
|
+
* donde estaba (p. ej. al vaciar su lista). Sin márgenes propios.
|
|
34
|
+
*/
|
|
35
|
+
export declare function AppliedFilters({ children, 'aria-label': ariaLabel, onClear, clearLabel, returnFocusRef, className, ref, ...rest }: AppliedFiltersProps): import("react").JSX.Element | null;
|
|
36
|
+
/**
|
|
37
|
+
* Un filtro aplicado: «Campo: valor ×». Un chip por filtro, aunque tenga varios valores. El cuerpo puede ser hijo de
|
|
38
|
+
* PopoverTrigger para abrir ese filtro: recibe `ref`, eventos y atributos, y es un `<button>`; si nadie lo hace clicable
|
|
39
|
+
* (sin `onClick`), es texto. Si el valor se corta o dice «y N más», un Tooltip muestra el texto completo (mouse y foco).
|
|
40
|
+
*/
|
|
41
|
+
export declare function FilterChip({ label, value, values, maxValues, onRemove, className, ref, onClick, type, ...rest }: FilterChipProps): import("react").JSX.Element;
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
|
|
3
|
+
import { Children, createContext, useContext, useLayoutEffect, useRef, useState, } from 'react';
|
|
4
|
+
import { Button } from '../button/index.js';
|
|
5
|
+
import { Tooltip } from '../tooltip/index.js';
|
|
6
|
+
import { summarizeValues } from './format.js';
|
|
7
|
+
const Ctx = createContext(null);
|
|
8
|
+
const cx = (own, extra) => (extra ? own + ' ' + extra : own);
|
|
9
|
+
/** Asigna `el` a la ref propia y a la del consumidor (objeto o función). */
|
|
10
|
+
function assign(own, ref, el) {
|
|
11
|
+
own.current = el;
|
|
12
|
+
if (typeof ref === 'function')
|
|
13
|
+
ref(el);
|
|
14
|
+
else if (ref)
|
|
15
|
+
ref.current = el;
|
|
16
|
+
}
|
|
17
|
+
/** Lo que recibe el foco en un chip: la ×; si no tiene, el cuerpo cuando es focalizable. */
|
|
18
|
+
function focusTarget(chip) {
|
|
19
|
+
const remove = chip.querySelector('.dx-filter-chip__remove');
|
|
20
|
+
if (remove)
|
|
21
|
+
return remove;
|
|
22
|
+
const body = chip.querySelector('.dx-filter-chip__body');
|
|
23
|
+
return body && body.tabIndex >= 0 ? body : null;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Fila de filtros aplicados (`role="group"`, «Filtros aplicados»): los chips en una fila que envuelve y, con `onClear`,
|
|
27
|
+
* «Limpiar filtros». Sin chips no dibuja nada. Al quitar un chip, el foco pasa a la × del chip siguiente; si no hay, a la del
|
|
28
|
+
* anterior; si no queda ninguno, a `returnFocusRef`. Lo mismo si desaparece el chip que tenía el foco o que abrió el popover
|
|
29
|
+
* donde estaba (p. ej. al vaciar su lista). Sin márgenes propios.
|
|
30
|
+
*/
|
|
31
|
+
export function AppliedFilters({ children, 'aria-label': ariaLabel = 'Filtros aplicados', onClear, clearLabel = 'Limpiar filtros', returnFocusRef, className, ref, ...rest }) {
|
|
32
|
+
const root = useRef(null);
|
|
33
|
+
const pending = useRef(null);
|
|
34
|
+
/** El último chip que tuvo el foco (también si después el foco pasó a su popover). */
|
|
35
|
+
const lastFocused = useRef(null);
|
|
36
|
+
// Después de cada render: si lo que se quitó ya no está y el foco se perdió (quedó en el body), lo lleva al lugar que
|
|
37
|
+
// corresponde. Si la pantalla todavía no lo quitó, espera; si el foco ya está en otro lado, no lo toca. Lo mismo si
|
|
38
|
+
// desaparece el último chip que tuvo el foco sin pasar por su × (p. ej. vaciando su lista desde su popover).
|
|
39
|
+
useLayoutEffect(() => {
|
|
40
|
+
const last = lastFocused.current;
|
|
41
|
+
if (!pending.current && last && !last.el.isConnected)
|
|
42
|
+
pending.current = last;
|
|
43
|
+
const p = pending.current;
|
|
44
|
+
if (!p || p.el.isConnected)
|
|
45
|
+
return;
|
|
46
|
+
pending.current = null;
|
|
47
|
+
lastFocused.current = null;
|
|
48
|
+
const doc = p.el.ownerDocument;
|
|
49
|
+
const active = doc.activeElement;
|
|
50
|
+
if (active && active !== doc.body && active.isConnected)
|
|
51
|
+
return;
|
|
52
|
+
const chips = root.current ? Array.from(root.current.querySelectorAll('.dx-filter-chip')) : [];
|
|
53
|
+
const order = p.index === null ? [] : [...chips.slice(p.index), ...chips.slice(0, p.index).reverse()];
|
|
54
|
+
for (const chip of order) {
|
|
55
|
+
const target = focusTarget(chip);
|
|
56
|
+
if (target) {
|
|
57
|
+
target.focus();
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
const fallback = returnFocusRef?.current ?? (chips.map(focusTarget).find((t) => t !== null) ?? null);
|
|
62
|
+
fallback?.focus();
|
|
63
|
+
});
|
|
64
|
+
const placeOf = (chip) => {
|
|
65
|
+
const chips = root.current ? Array.from(root.current.querySelectorAll('.dx-filter-chip')) : [];
|
|
66
|
+
return { el: chip, index: Math.max(chips.indexOf(chip), 0) };
|
|
67
|
+
};
|
|
68
|
+
const removing = (chip) => { pending.current = placeOf(chip); };
|
|
69
|
+
// focusin nativo y no onFocus de React: los eventos de React suben también desde los portales (el popover de un chip), y
|
|
70
|
+
// acá solo cuenta el foco en los chips de la fila.
|
|
71
|
+
const attach = (el) => {
|
|
72
|
+
assign(root, ref, el);
|
|
73
|
+
if (!el)
|
|
74
|
+
return undefined;
|
|
75
|
+
const onFocusIn = (event) => {
|
|
76
|
+
const chip = event.target instanceof Element ? event.target.closest('.dx-filter-chip') : null;
|
|
77
|
+
lastFocused.current = chip ? placeOf(chip) : null;
|
|
78
|
+
};
|
|
79
|
+
el.addEventListener('focusin', onFocusIn);
|
|
80
|
+
return () => { el.removeEventListener('focusin', onFocusIn); assign(root, ref, null); };
|
|
81
|
+
};
|
|
82
|
+
const empty = Children.toArray(children).length === 0;
|
|
83
|
+
if (empty)
|
|
84
|
+
return null;
|
|
85
|
+
return (_jsx(Ctx, { value: { removing }, children: _jsxs("div", { ...rest, ref: attach, role: "group", "aria-label": ariaLabel, className: cx('dx-applied-filters', className), children: [children, onClear && (_jsx(Button, { variant: "ghost", size: "xs", className: "dx-applied-filters__clear", onClick: (event) => { pending.current = { el: event.currentTarget, index: null }; onClear(); }, children: clearLabel }))] }) }));
|
|
86
|
+
}
|
|
87
|
+
/** × de 14px: el trazo de X de lucide (ISC), en línea porque @dubix/ui no depende de lucide-react. */
|
|
88
|
+
const Cross = () => (_jsxs("svg", { viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", focusable: "false", children: [_jsx("path", { d: "M18 6 6 18" }), _jsx("path", { d: "m6 6 12 12" })] }));
|
|
89
|
+
/**
|
|
90
|
+
* Un filtro aplicado: «Campo: valor ×». Un chip por filtro, aunque tenga varios valores. El cuerpo puede ser hijo de
|
|
91
|
+
* PopoverTrigger para abrir ese filtro: recibe `ref`, eventos y atributos, y es un `<button>`; si nadie lo hace clicable
|
|
92
|
+
* (sin `onClick`), es texto. Si el valor se corta o dice «y N más», un Tooltip muestra el texto completo (mouse y foco).
|
|
93
|
+
*/
|
|
94
|
+
export function FilterChip({ label, value, values, maxValues = 2, onRemove, className, ref, onClick, type, ...rest }) {
|
|
95
|
+
const ctx = useContext(Ctx);
|
|
96
|
+
const chip = useRef(null);
|
|
97
|
+
const text = useRef(null);
|
|
98
|
+
const [cut, setCut] = useState(false);
|
|
99
|
+
const all = values ? [...values] : value !== undefined && value !== '' ? [value] : [];
|
|
100
|
+
const max = Math.max(1, Math.floor(maxValues));
|
|
101
|
+
const extra = Math.max(all.length - max, 0);
|
|
102
|
+
const shown = summarizeValues(all, max);
|
|
103
|
+
const full = all.length ? label + ': ' + all.join(', ') : label;
|
|
104
|
+
// ¿El texto se corta con puntos suspensivos? Se mide al montar, cuando cambia el texto y cuando cambia el tamaño. Se observa
|
|
105
|
+
// el chip, que no se vuelve a montar: el cuerpo sí (al sumar o sacar el Tooltip), así que el texto se lee en cada aviso.
|
|
106
|
+
useLayoutEffect(() => {
|
|
107
|
+
const el = chip.current;
|
|
108
|
+
if (!el || typeof ResizeObserver === 'undefined')
|
|
109
|
+
return;
|
|
110
|
+
const observer = new ResizeObserver(() => {
|
|
111
|
+
const t = text.current;
|
|
112
|
+
setCut(t !== null && t.scrollWidth > t.clientWidth);
|
|
113
|
+
});
|
|
114
|
+
observer.observe(el);
|
|
115
|
+
return () => { observer.disconnect(); };
|
|
116
|
+
}, [shown, label]);
|
|
117
|
+
const needsTooltip = extra > 0 || cut;
|
|
118
|
+
const clickable = onClick !== undefined;
|
|
119
|
+
const content = all.length ? (_jsxs(_Fragment, { children: [_jsx("span", { className: "dx-filter-chip__label", children: label + ':' }), ' ', _jsx("span", { className: "dx-filter-chip__value", ref: text, children: shown })] })) : (_jsx("span", { className: "dx-filter-chip__value", ref: text, children: label }));
|
|
120
|
+
const body = clickable ? (_jsx("button", { ...rest, ref: ref, type: type ?? 'button', className: "dx-filter-chip__body", onClick: onClick, children: content })) : (_jsx("span", { ...rest, ref: ref, className: "dx-filter-chip__body", tabIndex: needsTooltip ? 0 : undefined, children: content }));
|
|
121
|
+
return (_jsxs("span", { ref: chip, className: cx('dx-filter-chip', className), children: [_jsx(Tooltip, { content: full, disabled: !needsTooltip, children: body }), onRemove && (_jsx("button", { type: "button", className: "dx-filter-chip__remove", "aria-label": 'Quitar filtro: ' + label, onClick: () => { if (chip.current)
|
|
122
|
+
ctx?.removing(chip.current); onRemove(); }, children: _jsx(Cross, {}) }))] }));
|
|
123
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { type FilterAmountRangeValue } from './format.js';
|
|
2
|
+
export interface FilterAmountRangeProps {
|
|
3
|
+
/** `{ min?, max? }` o `null`. */
|
|
4
|
+
value: FilterAmountRangeValue;
|
|
5
|
+
onValueChange: (value: FilterAmountRangeValue) => void;
|
|
6
|
+
/** Nombre del grupo de campos (p. ej. «Importe»). Obligatorio. */
|
|
7
|
+
'aria-label': string;
|
|
8
|
+
/** Acepta importes negativos. Por defecto `false`. */
|
|
9
|
+
allowNegative?: boolean | undefined;
|
|
10
|
+
/** Etiquetas de los campos. Por defecto «Desde» y «Hasta». */
|
|
11
|
+
fromLabel?: string | undefined;
|
|
12
|
+
toLabel?: string | undefined;
|
|
13
|
+
/** Error cuando Hasta es menor que Desde. Por defecto «El importe final es menor que el inicial». */
|
|
14
|
+
rangeErrorText?: string | undefined;
|
|
15
|
+
/** Error cuando el texto no es un importe. Por defecto «Ingresá un importe válido». */
|
|
16
|
+
invalidText?: string | undefined;
|
|
17
|
+
/** Error con un negativo sin `allowNegative`. Por defecto «Ingresá un importe positivo». */
|
|
18
|
+
negativeText?: string | undefined;
|
|
19
|
+
/** Se suma a `dx-filter-amount`. */
|
|
20
|
+
className?: string | undefined;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Filtro de rango de importe, para ir dentro de un PopoverContent: Desde y Hasta (Input con «$» adelante, inputMode
|
|
24
|
+
* decimal), en formato es-AR. Aplica medio segundo después de dejar de escribir, al salir del campo o con Enter; al salir, el
|
|
25
|
+
* número queda formateado (1234,5 → 1.234,50). Con un error no aplica; vaciar los dos deja `null`. Sin «Aplicar».
|
|
26
|
+
*/
|
|
27
|
+
export declare function FilterAmountRange({ value, onValueChange, 'aria-label': ariaLabel, allowNegative, fromLabel, toLabel, rangeErrorText, invalidText, negativeText, className, }: FilterAmountRangeProps): import("react").JSX.Element;
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
+
import { useEffect, useRef, useState } from 'react';
|
|
4
|
+
import { Field } from '../field/index.js';
|
|
5
|
+
import { Input } from '../input/index.js';
|
|
6
|
+
import { formatAmount, parseAmount } from './format.js';
|
|
7
|
+
/** Espera después de la última tecla antes de aplicar, en ms. */
|
|
8
|
+
const DEBOUNCE_MS = 500;
|
|
9
|
+
const cx = (own, extra) => (extra ? own + ' ' + extra : own);
|
|
10
|
+
const textOf = (n) => (n === undefined || !Number.isFinite(n) ? '' : formatAmount(n));
|
|
11
|
+
/**
|
|
12
|
+
* Filtro de rango de importe, para ir dentro de un PopoverContent: Desde y Hasta (Input con «$» adelante, inputMode
|
|
13
|
+
* decimal), en formato es-AR. Aplica medio segundo después de dejar de escribir, al salir del campo o con Enter; al salir, el
|
|
14
|
+
* número queda formateado (1234,5 → 1.234,50). Con un error no aplica; vaciar los dos deja `null`. Sin «Aplicar».
|
|
15
|
+
*/
|
|
16
|
+
export function FilterAmountRange({ value, onValueChange, 'aria-label': ariaLabel, allowNegative = false, fromLabel = 'Desde', toLabel = 'Hasta', rangeErrorText = 'El importe final es menor que el inicial', invalidText = 'Ingresá un importe válido', negativeText = 'Ingresá un importe positivo', className, }) {
|
|
17
|
+
/** Un campo: vacío (undefined), un importe, o el error que corresponde. */
|
|
18
|
+
const read = (text) => {
|
|
19
|
+
if (text.trim() === '')
|
|
20
|
+
return {};
|
|
21
|
+
const n = parseAmount(text);
|
|
22
|
+
if (n === null)
|
|
23
|
+
return { error: invalidText };
|
|
24
|
+
if (n < 0 && !allowNegative)
|
|
25
|
+
return { error: negativeText };
|
|
26
|
+
return { n };
|
|
27
|
+
};
|
|
28
|
+
/** Los dos textos: los errores de cada campo y, si no hay, el valor que corresponde. */
|
|
29
|
+
const validate = (minT, maxT) => {
|
|
30
|
+
const a = read(minT);
|
|
31
|
+
const b = read(maxT);
|
|
32
|
+
const errors = { min: a.error, max: b.error };
|
|
33
|
+
if (!a.error && !b.error && a.n !== undefined && b.n !== undefined && b.n < a.n)
|
|
34
|
+
errors.max = rangeErrorText;
|
|
35
|
+
const result = a.n === undefined && b.n === undefined ? null : { ...(a.n === undefined ? {} : { min: a.n }), ...(b.n === undefined ? {} : { max: b.n }) };
|
|
36
|
+
return { errors, result };
|
|
37
|
+
};
|
|
38
|
+
const [minText, setMinText] = useState(textOf(value?.min));
|
|
39
|
+
const [maxText, setMaxText] = useState(textOf(value?.max));
|
|
40
|
+
// Con el valor con que se monta ya se ven sus errores (p. ej. Hasta menor que Desde, o un negativo sin allowNegative).
|
|
41
|
+
const [errors, setErrors] = useState(() => validate(textOf(value?.min), textOf(value?.max)).errors);
|
|
42
|
+
const timer = useRef(undefined);
|
|
43
|
+
const applied = useRef(JSON.stringify(value));
|
|
44
|
+
useEffect(() => () => { clearTimeout(timer.current); }, []);
|
|
45
|
+
const apply = (minT, maxT) => {
|
|
46
|
+
clearTimeout(timer.current);
|
|
47
|
+
const { errors: next, result } = validate(minT, maxT);
|
|
48
|
+
setErrors(next);
|
|
49
|
+
if (next.min || next.max)
|
|
50
|
+
return;
|
|
51
|
+
const key = JSON.stringify(result);
|
|
52
|
+
if (key === applied.current)
|
|
53
|
+
return;
|
|
54
|
+
applied.current = key;
|
|
55
|
+
onValueChange(result);
|
|
56
|
+
};
|
|
57
|
+
/** Deja el texto del campo formateado (1234,5 → 1.234,50) si es un importe; si no, como está. */
|
|
58
|
+
const tidy = (text, set) => {
|
|
59
|
+
const n = text.trim() === '' ? null : parseAmount(text);
|
|
60
|
+
if (n !== null)
|
|
61
|
+
set(formatAmount(n));
|
|
62
|
+
};
|
|
63
|
+
/** Los dos textos, con el del campo `which` reemplazado por `text`. */
|
|
64
|
+
const both = (which, text) => (which === 'min' ? [text, maxText] : [minText, text]);
|
|
65
|
+
const setText = (which) => (which === 'min' ? setMinText : setMaxText);
|
|
66
|
+
/** Cada tecla: guarda el texto y aplica después de DEBOUNCE_MS sin escribir. */
|
|
67
|
+
const onType = (which, event) => {
|
|
68
|
+
const next = event.target.value;
|
|
69
|
+
setText(which)(next);
|
|
70
|
+
clearTimeout(timer.current);
|
|
71
|
+
timer.current = setTimeout(() => { apply(...both(which, next)); }, DEBOUNCE_MS);
|
|
72
|
+
};
|
|
73
|
+
/** Al salir del campo o con Enter: formatea y aplica ya. */
|
|
74
|
+
const commit = (which, text) => {
|
|
75
|
+
tidy(text, setText(which));
|
|
76
|
+
apply(...both(which, text));
|
|
77
|
+
};
|
|
78
|
+
const onEnter = (which, event) => {
|
|
79
|
+
if (event.key !== 'Enter')
|
|
80
|
+
return;
|
|
81
|
+
event.preventDefault();
|
|
82
|
+
commit(which, event.currentTarget.value);
|
|
83
|
+
};
|
|
84
|
+
const currency = _jsx("span", { className: "dx-filter-amount__currency", children: "$" });
|
|
85
|
+
return (_jsxs("div", { role: "group", "aria-label": ariaLabel, className: cx('dx-filter-amount', className), children: [_jsx(Field, { label: fromLabel, error: errors.min, children: _jsx(Input, { type: "text", inputMode: "decimal", autoComplete: "off", iconStart: currency, value: minText, onChange: (event) => { onType('min', event); }, onBlur: (event) => { commit('min', event.currentTarget.value); }, onKeyDown: (event) => { onEnter('min', event); } }) }), _jsx(Field, { label: toLabel, error: errors.max, children: _jsx(Input, { type: "text", inputMode: "decimal", autoComplete: "off", iconStart: currency, value: maxText, onChange: (event) => { onType('max', event); }, onBlur: (event) => { commit('max', event.currentTarget.value); }, onKeyDown: (event) => { onEnter('max', event); } }) })] }));
|
|
86
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { ComponentPropsWithRef, ReactNode } from 'react';
|
|
2
|
+
export interface FilterBarProps extends Omit<ComponentPropsWithRef<'div'>, 'role' | 'aria-label' | 'children'> {
|
|
3
|
+
/** Nombre de la región de búsqueda (p. ej. «Filtros de comprobantes de venta»). Obligatorio: `role="search"` va con nombre. */
|
|
4
|
+
'aria-label': string;
|
|
5
|
+
/** El buscador: un SearchInput (con su propio `aria-label`). Ancho `--dx-size-search`; en angosto, todo el ancho. */
|
|
6
|
+
search?: ReactNode;
|
|
7
|
+
/** Los filtros a la vista (FilterButton dentro de PopoverTrigger, FilterToggle) y, si hay, el botón «Filtrar». */
|
|
8
|
+
children?: ReactNode;
|
|
9
|
+
/**
|
|
10
|
+
* Cantidad de resultados (p. ej. «128 comprobantes»), a la derecha, en una región `aria-live="polite"`. Pasarla siempre que
|
|
11
|
+
* la pantalla la muestre, también vacía (`''`) mientras carga: así la región existe antes de que cambie y se anuncia.
|
|
12
|
+
*/
|
|
13
|
+
count?: ReactNode;
|
|
14
|
+
/** Controles extra a la derecha, después de la cantidad (p. ej. un menú «Vista»). */
|
|
15
|
+
end?: ReactNode;
|
|
16
|
+
}
|
|
17
|
+
export interface FilterButtonProps extends Omit<ComponentPropsWithRef<'button'>, 'children'> {
|
|
18
|
+
/** Nombre del filtro (p. ej. «Fecha»). El valor no se muestra acá: se ve en la fila de filtros aplicados. */
|
|
19
|
+
label: ReactNode;
|
|
20
|
+
/** El filtro tiene valor: la etiqueta pasa a `--dx-fg` con peso 500, aparece el punto y se anuncia «filtro aplicado». */
|
|
21
|
+
active?: boolean | undefined;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Barra de filtros de un listado: el buscador, los filtros a la vista y, a la derecha, la cantidad y controles extra, en una
|
|
25
|
+
* fila que envuelve. `role="search"` con nombre. Sin márgenes propios: los pone la pantalla.
|
|
26
|
+
*/
|
|
27
|
+
export declare function FilterBar({ 'aria-label': ariaLabel, search, children, count, end, className, ...rest }: FilterBarProps): import("react").JSX.Element;
|
|
28
|
+
/**
|
|
29
|
+
* Botón que abre un filtro, hijo de PopoverTrigger: un único `<button>` (un Button secondary sm) que recibe `ref`, eventos y
|
|
30
|
+
* los atributos de Radix (`aria-expanded`, `data-state`…). Etiqueta y flecha; con `active`, el punto y el texto oculto.
|
|
31
|
+
*/
|
|
32
|
+
export declare function FilterButton({ label, active, className, ...rest }: FilterButtonProps): import("react").JSX.Element;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
|
|
2
|
+
import { Button } from '../button/index.js';
|
|
3
|
+
const cx = (own, extra) => (extra ? own + ' ' + extra : own);
|
|
4
|
+
const has = (node) => node != null && typeof node !== 'boolean' && node !== '';
|
|
5
|
+
/** Flecha hacia abajo de 14px: el trazo de ChevronDown de lucide (ISC), en línea porque @dubix/ui no depende de lucide-react. */
|
|
6
|
+
const Chevron = () => (_jsx("svg", { viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", focusable: "false", children: _jsx("path", { d: "m6 9 6 6 6-6" }) }));
|
|
7
|
+
/**
|
|
8
|
+
* Barra de filtros de un listado: el buscador, los filtros a la vista y, a la derecha, la cantidad y controles extra, en una
|
|
9
|
+
* fila que envuelve. `role="search"` con nombre. Sin márgenes propios: los pone la pantalla.
|
|
10
|
+
*/
|
|
11
|
+
export function FilterBar({ 'aria-label': ariaLabel, search, children, count, end, className, ...rest }) {
|
|
12
|
+
const showEnd = count !== undefined || has(end);
|
|
13
|
+
return (_jsx("div", { ...rest, role: "search", "aria-label": ariaLabel, className: cx('dx-filter-bar', className), children: _jsxs("div", { className: "dx-filter-bar__row", children: [has(search) && _jsx("div", { className: "dx-filter-bar__search", children: search }), children, showEnd && (_jsxs("div", { className: "dx-filter-bar__end", children: [count !== undefined && _jsx("span", { className: "dx-filter-bar__count", "aria-live": "polite", children: count }), has(end) && end] }))] }) }));
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Botón que abre un filtro, hijo de PopoverTrigger: un único `<button>` (un Button secondary sm) que recibe `ref`, eventos y
|
|
17
|
+
* los atributos de Radix (`aria-expanded`, `data-state`…). Etiqueta y flecha; con `active`, el punto y el texto oculto.
|
|
18
|
+
*/
|
|
19
|
+
export function FilterButton({ label, active = false, className, ...rest }) {
|
|
20
|
+
return (_jsxs(Button, { ...rest, variant: "secondary", size: "sm", className: cx('dx-filter-btn', className), "data-active": active ? 'true' : undefined, iconEnd: _jsx(Chevron, {}), children: [_jsx("span", { className: "dx-filter-btn__label", children: label }), active && (_jsxs(_Fragment, { children: [_jsx("span", { className: "dx-filter-btn__dot", "aria-hidden": "true" }), _jsx("span", { className: "dx-filter-btn__sr", children: ", filtro aplicado" })] }))] }));
|
|
21
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { type ReactNode } from 'react';
|
|
2
|
+
/** Una opción de la lista. */
|
|
3
|
+
export interface FilterOption {
|
|
4
|
+
value: string;
|
|
5
|
+
/** Texto de la opción; también es lo que se busca. */
|
|
6
|
+
label: string;
|
|
7
|
+
/** Texto chico debajo, en `--dx-fg-3` (describe la opción). */
|
|
8
|
+
description?: string | undefined;
|
|
9
|
+
/** Título del grupo: las opciones con el mismo `group` van juntas, en el orden en que aparece cada grupo. */
|
|
10
|
+
group?: string | undefined;
|
|
11
|
+
/** Apagada: no se puede elegir y el teclado la saltea. */
|
|
12
|
+
disabled?: boolean | undefined;
|
|
13
|
+
/** Un valor: elegirla marca pero no cierra el Popover (p. ej. «Entre fechas» de FilterPeriod, que abre más campos). */
|
|
14
|
+
keepOpen?: boolean | undefined;
|
|
15
|
+
/** Texto corto a la derecha, en `--dx-fg-3` con cifras tabulares (p. ej. el saldo «$ 12.345,00»). Describe la opción. */
|
|
16
|
+
meta?: string | undefined;
|
|
17
|
+
}
|
|
18
|
+
interface FilterOptionsBase {
|
|
19
|
+
options: readonly FilterOption[];
|
|
20
|
+
/** Nombre de la lista para lectores de pantalla (p. ej. «Estado»). Obligatorio. */
|
|
21
|
+
'aria-label': string;
|
|
22
|
+
/** Campo para buscar arriba. Por defecto, con más de 8 opciones; `true` o `false` lo fuerzan. */
|
|
23
|
+
searchable?: boolean | undefined;
|
|
24
|
+
/** Nombre y placeholder del campo para buscar. Por defecto «Buscar». */
|
|
25
|
+
searchLabel?: string | undefined;
|
|
26
|
+
/** Texto cuando la búsqueda no encuentra nada. Por defecto «No hay coincidencias». */
|
|
27
|
+
emptyText?: string | undefined;
|
|
28
|
+
/** Cargando: filas de Skeleton en lugar de las opciones, y `aria-busy` en la lista. */
|
|
29
|
+
loading?: boolean | undefined;
|
|
30
|
+
/** Ocupada: `aria-busy` en la lista, pero las opciones quedan a la vista (p. ej. mientras llegan resultados nuevos). */
|
|
31
|
+
busy?: boolean | undefined;
|
|
32
|
+
/** Texto del campo para buscar (controlado), con `onQueryChange`. Sin `query`, la lista guarda el suyo. */
|
|
33
|
+
query?: string | undefined;
|
|
34
|
+
onQueryChange?: ((query: string) => void) | undefined;
|
|
35
|
+
/** Filtra las opciones con el texto buscado. Por defecto `true`; `false` muestra `options` tal cual (la busca la app). */
|
|
36
|
+
filter?: boolean | undefined;
|
|
37
|
+
/**
|
|
38
|
+
* Lo que va en la región de estado, en lugar del aviso automático («No hay coincidencias»): un aviso propio, o un error con
|
|
39
|
+
* su acción. `null` la deja vacía. Sin `status`, el aviso automático.
|
|
40
|
+
*/
|
|
41
|
+
status?: ReactNode;
|
|
42
|
+
/** Se suma a `dx-filter-options`. */
|
|
43
|
+
className?: string | undefined;
|
|
44
|
+
}
|
|
45
|
+
export interface FilterOptionsSingleProps extends FilterOptionsBase {
|
|
46
|
+
/** Un valor (por defecto). Elegir cierra el Popover que la envuelve; elegir la marcada no la desmarca. */
|
|
47
|
+
multiple?: false | undefined;
|
|
48
|
+
value: string | null;
|
|
49
|
+
onValueChange: (value: string) => void;
|
|
50
|
+
onClear?: undefined;
|
|
51
|
+
clearLabel?: undefined;
|
|
52
|
+
}
|
|
53
|
+
export interface FilterOptionsMultipleProps extends FilterOptionsBase {
|
|
54
|
+
/** Varios valores: cada opción con la caja de Checkbox; marcar o desmarcar aplica al instante y el Popover queda abierto. */
|
|
55
|
+
multiple: true;
|
|
56
|
+
value: readonly string[];
|
|
57
|
+
onValueChange: (value: string[]) => void;
|
|
58
|
+
/** Con al menos una marcada, abajo va «Quitar filtro», que llama a `onClear` (la pantalla vacía la selección). */
|
|
59
|
+
onClear?: (() => void) | undefined;
|
|
60
|
+
/** Texto del botón de `onClear`. Por defecto «Quitar filtro». */
|
|
61
|
+
clearLabel?: string | undefined;
|
|
62
|
+
}
|
|
63
|
+
export type FilterOptionsProps = FilterOptionsSingleProps | FilterOptionsMultipleProps;
|
|
64
|
+
/**
|
|
65
|
+
* Lista de opciones de un filtro, para ir dentro de un PopoverContent (lo que abre un FilterButton o un FilterChip). Todo se
|
|
66
|
+
* aplica al elegir, sin «Aplicar». Un valor: elegir marca y cierra el Popover (el foco vuelve a lo que lo abrió). Varios
|
|
67
|
+
* valores: cada opción con la caja de Checkbox, marcar no cierra y, con `onClear`, «Quitar filtro» abajo. Con búsqueda, un
|
|
68
|
+
* combobox con la lista (`aria-activedescendant`); sin búsqueda, un listbox con el foco en las opciones (patrones de APG).
|
|
69
|
+
*/
|
|
70
|
+
export declare function FilterOptions(props: FilterOptionsProps): import("react").JSX.Element;
|
|
71
|
+
export {};
|