@dubix/ui 0.4.0 → 0.6.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 +348 -13
- package/dist/drawer/Drawer.d.ts +44 -0
- package/dist/drawer/Drawer.js +81 -0
- package/dist/drawer/index.d.ts +2 -0
- package/dist/drawer/index.js +1 -0
- package/dist/pagination/Pagination.d.ts +29 -0
- package/dist/pagination/Pagination.js +47 -0
- package/dist/pagination/index.d.ts +2 -0
- package/dist/pagination/index.js +1 -0
- package/dist/search-input/SearchInput.d.ts +19 -0
- package/dist/search-input/SearchInput.js +57 -0
- package/dist/search-input/index.d.ts +2 -0
- package/dist/search-input/index.js +1 -0
- package/dist/select/Select.d.ts +50 -0
- package/dist/select/Select.js +87 -0
- package/dist/select/index.d.ts +2 -0
- package/dist/select/index.js +1 -0
- package/dist/styles.css +679 -1
- package/dist/toast/Toast.d.ts +33 -0
- package/dist/toast/Toast.js +50 -0
- package/dist/toast/index.d.ts +2 -0
- package/dist/toast/index.js +1 -0
- package/package.json +21 -1
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { type ReactElement, type ReactNode } from 'react';
|
|
2
|
+
/** Ancho del panel: `detail` 440px (detalle de un registro) o `context` 360px (contexto al costado de una tarea). */
|
|
3
|
+
export type DrawerWidth = 'detail' | 'context';
|
|
4
|
+
export interface DrawerProps {
|
|
5
|
+
children: ReactNode;
|
|
6
|
+
/** Abierto (controlado). Sin `open`, el drawer maneja su propio estado. */
|
|
7
|
+
open?: boolean | undefined;
|
|
8
|
+
/** Abierto al montar (no controlado). */
|
|
9
|
+
defaultOpen?: boolean | undefined;
|
|
10
|
+
/** Se llama al abrir (disparador) y al cerrar (Esc, ×, clic en el velo). */
|
|
11
|
+
onOpenChange?: ((open: boolean) => void) | undefined;
|
|
12
|
+
}
|
|
13
|
+
export interface DrawerTriggerProps {
|
|
14
|
+
/** Un único elemento focalizable (un `<button>`, un Button): recibe el clic, `aria-haspopup`, `aria-expanded` y `data-state`. */
|
|
15
|
+
children: ReactElement;
|
|
16
|
+
}
|
|
17
|
+
export interface DrawerContentProps {
|
|
18
|
+
/** Título del panel; lo nombra (`aria-labelledby`) y recibe el foco al abrir. */
|
|
19
|
+
title: ReactNode;
|
|
20
|
+
/** Bajada opcional debajo del título; describe al panel (`aria-describedby`). */
|
|
21
|
+
subtitle?: ReactNode | undefined;
|
|
22
|
+
/** Por defecto `detail` (440px). */
|
|
23
|
+
width?: DrawerWidth | undefined;
|
|
24
|
+
/** Pie fijo abajo (p. ej. las acciones). Sin `footer` no se renderiza. */
|
|
25
|
+
footer?: ReactNode | undefined;
|
|
26
|
+
/** Nombre del botón de cerrar (×). Por defecto «Cerrar». */
|
|
27
|
+
closeLabel?: string | undefined;
|
|
28
|
+
/** El cuerpo, con scroll propio. */
|
|
29
|
+
children?: ReactNode;
|
|
30
|
+
/** Se suma a `dx-drawer` (el panel). */
|
|
31
|
+
className?: string | undefined;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Raíz del drawer (Radix Dialog, modal). Controlado (`open` + `onOpenChange`) o no (`defaultOpen`). Guarda quién tenía el
|
|
35
|
+
* foco al abrir, para devolvérselo al cerrar, y el ancestro de tema donde se monta el panel.
|
|
36
|
+
*/
|
|
37
|
+
export declare function Drawer({ children, open, defaultOpen, onOpenChange }: DrawerProps): import("react").JSX.Element;
|
|
38
|
+
/** Disparador: le pasa los eventos y los atributos de Radix a su único hijo (`asChild`), sin agregar nada alrededor. */
|
|
39
|
+
export declare function DrawerTrigger({ children }: DrawerTriggerProps): import("react").JSX.Element;
|
|
40
|
+
/**
|
|
41
|
+
* El panel, en un portal, sobre un velo: `role="dialog"` y `aria-modal`, nombrado por el título. Al abrir el foco va al
|
|
42
|
+
* título; Tab queda adentro; Esc, la × y el clic en el velo cierran; el resto de la página queda inerte y sin scroll.
|
|
43
|
+
*/
|
|
44
|
+
export declare function DrawerContent({ title, subtitle, width, footer, closeLabel, children, className }: DrawerContentProps): import("react").JSX.Element;
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
+
import { createContext, useContext, useLayoutEffect, useRef, useState } from 'react';
|
|
4
|
+
import { Dialog } from 'radix-ui';
|
|
5
|
+
import { IconButton } from '../icon-button/IconButton.js';
|
|
6
|
+
/** El drawer se monta en el ancestro más cercano que fija el tema, para heredar sus variables (claro u oscuro). */
|
|
7
|
+
const THEME_ROOT = '.dx-app, .dark, [data-theme="dark"]';
|
|
8
|
+
/** Elemento con el foco al abrir. A él vuelve el foco al cerrar, aunque el drawer se haya abierto sin DrawerTrigger. */
|
|
9
|
+
const focused = () => {
|
|
10
|
+
if (typeof document === 'undefined')
|
|
11
|
+
return null;
|
|
12
|
+
const el = document.activeElement;
|
|
13
|
+
return el instanceof HTMLElement && el !== document.body ? el : null;
|
|
14
|
+
};
|
|
15
|
+
/** Ancestro de tema; `<html>` o `<body>` no cuentan (ahí basta el body, que es el de Radix). */
|
|
16
|
+
const themeRoot = (el) => {
|
|
17
|
+
const root = el?.closest(THEME_ROOT) ?? null;
|
|
18
|
+
return root === document.documentElement || root === document.body ? null : root;
|
|
19
|
+
};
|
|
20
|
+
const Ctx = createContext(null);
|
|
21
|
+
const useDrawer = (part) => {
|
|
22
|
+
const ctx = useContext(Ctx);
|
|
23
|
+
if (!ctx)
|
|
24
|
+
throw new Error(part + ' tiene que ir dentro de <Drawer>.');
|
|
25
|
+
return ctx;
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* Raíz del drawer (Radix Dialog, modal). Controlado (`open` + `onOpenChange`) o no (`defaultOpen`). Guarda quién tenía el
|
|
29
|
+
* foco al abrir, para devolvérselo al cerrar, y el ancestro de tema donde se monta el panel.
|
|
30
|
+
*/
|
|
31
|
+
export function Drawer({ children, open, defaultOpen = false, onOpenChange }) {
|
|
32
|
+
const trigger = useRef(null); // Radix lo tipa como botón; en la práctica es el hijo, sea cual sea
|
|
33
|
+
const [ownOpen, setOwnOpen] = useState(defaultOpen);
|
|
34
|
+
const isOpen = open ?? ownOpen;
|
|
35
|
+
// El foco se toma en el render que abre (estado derivado de `isOpen`), antes de que Radix lo mueva adentro.
|
|
36
|
+
const [origin, setOrigin] = useState(() => (isOpen ? focused() : null));
|
|
37
|
+
const [wasOpen, setWasOpen] = useState(isOpen);
|
|
38
|
+
if (isOpen !== wasOpen) {
|
|
39
|
+
setWasOpen(isOpen);
|
|
40
|
+
if (isOpen)
|
|
41
|
+
setOrigin(focused());
|
|
42
|
+
}
|
|
43
|
+
const [container, setContainer] = useState(null);
|
|
44
|
+
// Antes de pintar y con el disparador ya en el DOM: así también un drawer abierto de entrada va al tema correcto.
|
|
45
|
+
useLayoutEffect(() => { if (isOpen)
|
|
46
|
+
setContainer(themeRoot(origin ?? trigger.current)); }, [isOpen, origin]);
|
|
47
|
+
const setOpen = (next) => {
|
|
48
|
+
if (open === undefined)
|
|
49
|
+
setOwnOpen(next);
|
|
50
|
+
onOpenChange?.(next);
|
|
51
|
+
};
|
|
52
|
+
const restoreFocus = () => {
|
|
53
|
+
const target = origin?.isConnected ? origin : trigger.current;
|
|
54
|
+
target?.focus();
|
|
55
|
+
};
|
|
56
|
+
return (_jsx(Dialog.Root, { open: isOpen, onOpenChange: setOpen, children: _jsx(Ctx, { value: { trigger, container, restoreFocus }, children: children }) }));
|
|
57
|
+
}
|
|
58
|
+
/** Disparador: le pasa los eventos y los atributos de Radix a su único hijo (`asChild`), sin agregar nada alrededor. */
|
|
59
|
+
export function DrawerTrigger({ children }) {
|
|
60
|
+
const { trigger } = useDrawer('DrawerTrigger');
|
|
61
|
+
return _jsx(Dialog.Trigger, { asChild: true, ref: trigger, children: children });
|
|
62
|
+
}
|
|
63
|
+
const CloseIcon = () => (_jsx("svg", { viewBox: "0 0 16 16", width: "16", height: "16", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", focusable: "false", children: _jsx("path", { d: "M4.5 4.5l7 7M11.5 4.5l-7 7" }) }));
|
|
64
|
+
/**
|
|
65
|
+
* El panel, en un portal, sobre un velo: `role="dialog"` y `aria-modal`, nombrado por el título. Al abrir el foco va al
|
|
66
|
+
* título; Tab queda adentro; Esc, la × y el clic en el velo cierran; el resto de la página queda inerte y sin scroll.
|
|
67
|
+
*/
|
|
68
|
+
export function DrawerContent({ title, subtitle, width = 'detail', footer, closeLabel = 'Cerrar', children, className }) {
|
|
69
|
+
const { container, restoreFocus } = useDrawer('DrawerContent');
|
|
70
|
+
const titleRef = useRef(null);
|
|
71
|
+
const hasSubtitle = subtitle !== undefined && subtitle !== null;
|
|
72
|
+
return (_jsxs(Dialog.Portal, { container: container, children: [_jsx(Dialog.Overlay, { className: "dx-drawer__overlay" }), _jsxs(Dialog.Content, { className: className ? `dx-drawer ${className}` : 'dx-drawer', "data-width": width, "aria-modal": "true", ...(hasSubtitle ? {} : { 'aria-describedby': undefined }), onOpenAutoFocus: (event) => {
|
|
73
|
+
// Radix enfocaría el primer control (la ×); el foco va al título, para que el lector empiece por el nombre.
|
|
74
|
+
event.preventDefault();
|
|
75
|
+
titleRef.current?.focus();
|
|
76
|
+
}, onCloseAutoFocus: (event) => {
|
|
77
|
+
// Radix solo conoce su Trigger; el drawer también se abre desde la pantalla (p. ej. una fila de tabla).
|
|
78
|
+
event.preventDefault();
|
|
79
|
+
restoreFocus();
|
|
80
|
+
}, children: [_jsxs("div", { className: "dx-drawer__header", children: [_jsxs("div", { className: "dx-drawer__top", children: [_jsx(Dialog.Title, { ref: titleRef, tabIndex: -1, className: "dx-drawer__title", children: title }), _jsx(Dialog.Close, { asChild: true, children: _jsx(IconButton, { label: closeLabel, icon: _jsx(CloseIcon, {}), tooltipSide: "bottom" }) })] }), hasSubtitle && _jsx(Dialog.Description, { className: "dx-drawer__subtitle", children: subtitle })] }), _jsx("div", { className: "dx-drawer__body", children: children }), footer !== undefined && footer !== null && _jsx("div", { className: "dx-drawer__footer", children: footer })] })] }));
|
|
81
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { Drawer, DrawerContent, DrawerTrigger } from './Drawer.js';
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { ComponentPropsWithRef } from 'react';
|
|
2
|
+
/** Un lugar de la fila de páginas: un número de página (1-based) o el «…» de las que faltan. */
|
|
3
|
+
export type PaginationItem = number | 'ellipsis';
|
|
4
|
+
/** `onChange` de HTML queda fuera para no confundirlo con `onPageChange`; los hijos los arma el componente. */
|
|
5
|
+
export interface PaginationProps extends Omit<ComponentPropsWithRef<'nav'>, 'children' | 'onChange'> {
|
|
6
|
+
/** Página actual, 1-based. Fuera de rango se dibuja acotada a 1…pageCount (sin llamar a `onPageChange`). */
|
|
7
|
+
page: number;
|
|
8
|
+
/** Filas por página (mayor que 0). */
|
|
9
|
+
pageSize: number;
|
|
10
|
+
/** Total de filas del servidor. Con 0 no se renderiza nada: la pantalla muestra su EmptyState. */
|
|
11
|
+
total: number;
|
|
12
|
+
/** Recibe la página pedida (1-based). No se llama en la página actual ni en Anterior/Siguiente en los bordes. */
|
|
13
|
+
onPageChange: (page: number) => void;
|
|
14
|
+
/** Qué se cuenta, en plural («empresas»): va al final del rango («51–75 de 312 empresas»). */
|
|
15
|
+
itemLabel?: string | undefined;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Las páginas a mostrar: siempre la primera y la última, la actual y una a cada lado, y «…» donde faltan; nunca más de 7
|
|
19
|
+
* lugares (con 7 páginas o menos, todas). `page` fuera de rango se acota. Con 10 páginas: en la 1 → 1 2 3 4 5 … 10; en la
|
|
20
|
+
* 5 → 1 … 4 5 6 … 10; en la 10 → 1 … 6 7 8 9 10.
|
|
21
|
+
*/
|
|
22
|
+
export declare function paginationRange(page: number, pageCount: number): PaginationItem[];
|
|
23
|
+
/**
|
|
24
|
+
* Pie de una tabla con paginación del servidor: el rango («51–75 de 312 empresas») a la izquierda y Anterior, las páginas y
|
|
25
|
+
* Siguiente a la derecha, en una fila de 44px. En un contenedor de menos de 480px las páginas se reemplazan por «3 de 13».
|
|
26
|
+
* No guarda estado: la página la tiene la pantalla. `className` se suma a `dx-pagination`; `ref` y el resto de las props
|
|
27
|
+
* van al `<nav>`.
|
|
28
|
+
*/
|
|
29
|
+
export declare function Pagination({ page, pageSize, total, onPageChange, itemLabel, className, 'aria-label': ariaLabel, ...rest }: PaginationProps): import("react").JSX.Element | null;
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
import { Button } from '../button/index.js';
|
|
3
|
+
/** Cantidad máxima de lugares en la fila de páginas (números y «…»). */
|
|
4
|
+
const MAX_ITEMS = 7;
|
|
5
|
+
const numberFormat = new Intl.NumberFormat('es-AR');
|
|
6
|
+
const fmt = (n) => numberFormat.format(n);
|
|
7
|
+
const clamp = (n, min, max) => Math.min(Math.max(n, min), max);
|
|
8
|
+
/**
|
|
9
|
+
* Las páginas a mostrar: siempre la primera y la última, la actual y una a cada lado, y «…» donde faltan; nunca más de 7
|
|
10
|
+
* lugares (con 7 páginas o menos, todas). `page` fuera de rango se acota. Con 10 páginas: en la 1 → 1 2 3 4 5 … 10; en la
|
|
11
|
+
* 5 → 1 … 4 5 6 … 10; en la 10 → 1 … 6 7 8 9 10.
|
|
12
|
+
*/
|
|
13
|
+
export function paginationRange(page, pageCount) {
|
|
14
|
+
const count = Number.isFinite(pageCount) ? Math.max(0, Math.floor(pageCount)) : 0;
|
|
15
|
+
if (count <= MAX_ITEMS)
|
|
16
|
+
return Array.from({ length: count }, (_, i) => i + 1);
|
|
17
|
+
const current = clamp(Number.isFinite(page) ? Math.trunc(page) : 1, 1, count);
|
|
18
|
+
const run = (from, length) => Array.from({ length }, (_, i) => from + i);
|
|
19
|
+
// Los 5 lugares de un extremo cubren la actual con su vecina hasta la 4 (o la cuarta desde el final).
|
|
20
|
+
if (current <= 4)
|
|
21
|
+
return [...run(1, 5), 'ellipsis', count];
|
|
22
|
+
if (current >= count - 3)
|
|
23
|
+
return [1, 'ellipsis', ...run(count - 4, 5)];
|
|
24
|
+
return [1, 'ellipsis', current - 1, current, current + 1, 'ellipsis', count];
|
|
25
|
+
}
|
|
26
|
+
const Chevron = ({ d }) => (_jsx("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: d }) }));
|
|
27
|
+
/**
|
|
28
|
+
* Pie de una tabla con paginación del servidor: el rango («51–75 de 312 empresas») a la izquierda y Anterior, las páginas y
|
|
29
|
+
* Siguiente a la derecha, en una fila de 44px. En un contenedor de menos de 480px las páginas se reemplazan por «3 de 13».
|
|
30
|
+
* No guarda estado: la página la tiene la pantalla. `className` se suma a `dx-pagination`; `ref` y el resto de las props
|
|
31
|
+
* van al `<nav>`.
|
|
32
|
+
*/
|
|
33
|
+
export function Pagination({ page, pageSize, total, onPageChange, itemLabel, className, 'aria-label': ariaLabel = 'Paginación', ...rest }) {
|
|
34
|
+
// TypeScript no lo frena (es un number); un error claro en vez de un rango con NaN o Infinity.
|
|
35
|
+
if (!(pageSize > 0) || !Number.isFinite(pageSize))
|
|
36
|
+
throw new Error('Pagination: pageSize tiene que ser un número mayor que 0 (recibió ' + String(pageSize) + ').');
|
|
37
|
+
if (!(total > 0))
|
|
38
|
+
return null;
|
|
39
|
+
const pageCount = Math.ceil(total / pageSize);
|
|
40
|
+
const current = clamp(Number.isFinite(page) ? Math.trunc(page) : 1, 1, pageCount);
|
|
41
|
+
const from = (current - 1) * pageSize + 1;
|
|
42
|
+
const to = Math.min(current * pageSize, total);
|
|
43
|
+
const go = (target) => () => { onPageChange(target); };
|
|
44
|
+
const first = current === 1;
|
|
45
|
+
const last = current === pageCount;
|
|
46
|
+
return (_jsxs("nav", { ...rest, "aria-label": ariaLabel, className: className ? `dx-pagination ${className}` : 'dx-pagination', children: [_jsxs("p", { className: "dx-pagination__range", "aria-live": "polite", "aria-atomic": "true", children: [fmt(from), "\u2013", fmt(to), " de ", fmt(total), itemLabel ? ' ' + itemLabel : null] }), pageCount > 1 && (_jsxs("div", { className: "dx-pagination__controls", children: [_jsx(Button, { variant: "ghost", size: "sm", className: "dx-pagination__step", "data-step": "prev", iconStart: _jsx(Chevron, { d: "m15 18-6-6 6-6" }), "aria-disabled": first ? true : undefined, onClick: first ? undefined : go(current - 1), children: _jsx("span", { className: "dx-pagination__label", children: "Anterior" }) }), _jsx("span", { className: "dx-pagination__pages", children: paginationRange(current, pageCount).map((item, i) => item === 'ellipsis' ? (_jsx("span", { className: "dx-pagination__ellipsis", "aria-hidden": "true", children: "\u2026" }, i < 3 ? 'ellipsis-start' : 'ellipsis-end')) : (_jsx(Button, { variant: "ghost", size: "sm", className: "dx-pagination__page", "aria-label": 'Página ' + String(item), "aria-current": item === current ? 'page' : undefined, onClick: item === current ? undefined : go(item), children: fmt(item) }, item))) }), _jsxs("span", { className: "dx-pagination__status", children: [fmt(current), " de ", fmt(pageCount)] }), _jsx(Button, { variant: "ghost", size: "sm", className: "dx-pagination__step", "data-step": "next", iconEnd: _jsx(Chevron, { d: "m9 18 6-6-6-6" }), "aria-disabled": last ? true : undefined, onClick: last ? undefined : go(current + 1), children: _jsx("span", { className: "dx-pagination__label", children: "Siguiente" }) })] }))] }));
|
|
47
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { Pagination, paginationRange } from './Pagination.js';
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { type ComponentPropsWithRef } from 'react';
|
|
2
|
+
export interface SearchInputProps extends Omit<ComponentPropsWithRef<'input'>, 'size' | 'type' | 'value' | 'defaultValue' | 'children'> {
|
|
3
|
+
/** Texto, controlado. Va con `onValueChange`. */
|
|
4
|
+
value?: string | undefined;
|
|
5
|
+
/** Texto inicial, no controlado. */
|
|
6
|
+
defaultValue?: string | undefined;
|
|
7
|
+
/** Cada cambio del texto: al escribir, al limpiar con el botón y con Esc (con `''`). */
|
|
8
|
+
onValueChange?: ((value: string) => void) | undefined;
|
|
9
|
+
/** Después de limpiar (botón o Esc), una vez. */
|
|
10
|
+
onClear?: (() => void) | undefined;
|
|
11
|
+
/** Nombre accesible y tooltip del botón para limpiar. Por defecto «Limpiar búsqueda». */
|
|
12
|
+
clearLabel?: string | undefined;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Campo de búsqueda (Search md del DS v1): un Input `type="search"` con el ícono de búsqueda al principio, fondo
|
|
16
|
+
* `--dx-bg-sunken` y, cuando hay texto, un IconButton para limpiar al final. Las props van al `<input>` (también `ref`);
|
|
17
|
+
* `className`, al contenedor `.dx-search-input`. Sin debounce: lo hace la pantalla.
|
|
18
|
+
*/
|
|
19
|
+
export declare function SearchInput({ value, defaultValue, onValueChange, onClear, clearLabel, onChange, onKeyDown, className, ref, ...rest }: SearchInputProps): import("react").JSX.Element;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
+
import { useRef, useState } from 'react';
|
|
4
|
+
import { IconButton } from '../icon-button/index.js';
|
|
5
|
+
import { Input } from '../input/index.js';
|
|
6
|
+
/** Un ref callback que asigna el nodo al ref propio y al de la app. */
|
|
7
|
+
function mergeRefs(...refs) {
|
|
8
|
+
return (node) => {
|
|
9
|
+
for (const ref of refs) {
|
|
10
|
+
if (typeof ref === 'function')
|
|
11
|
+
ref(node);
|
|
12
|
+
else if (ref)
|
|
13
|
+
ref.current = node;
|
|
14
|
+
}
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
const SearchIcon = () => (_jsxs("svg", { viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", focusable: "false", children: [_jsx("circle", { cx: "7", cy: "7", r: "4.75" }), _jsx("path", { d: "M10.5 10.5 13.75 13.75" })] }));
|
|
18
|
+
const ClearIcon = () => (_jsx("svg", { viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", focusable: "false", children: _jsx("path", { d: "M4.5 4.5l7 7M11.5 4.5l-7 7" }) }));
|
|
19
|
+
/** Que el botón no le saque el foco al campo con el mouse: el clic limpia igual y el foco no parpadea. */
|
|
20
|
+
const keepFocus = (event) => { event.preventDefault(); };
|
|
21
|
+
/**
|
|
22
|
+
* Campo de búsqueda (Search md del DS v1): un Input `type="search"` con el ícono de búsqueda al principio, fondo
|
|
23
|
+
* `--dx-bg-sunken` y, cuando hay texto, un IconButton para limpiar al final. Las props van al `<input>` (también `ref`);
|
|
24
|
+
* `className`, al contenedor `.dx-search-input`. Sin debounce: lo hace la pantalla.
|
|
25
|
+
*/
|
|
26
|
+
export function SearchInput({ value, defaultValue = '', onValueChange, onClear, clearLabel = 'Limpiar búsqueda', onChange, onKeyDown, className, ref, ...rest }) {
|
|
27
|
+
const [uncontrolled, setUncontrolled] = useState(defaultValue);
|
|
28
|
+
const input = useRef(null);
|
|
29
|
+
const controlled = value !== undefined;
|
|
30
|
+
const text = controlled ? value : uncontrolled;
|
|
31
|
+
const canClear = text !== '' && !rest.disabled && !rest.readOnly;
|
|
32
|
+
const update = (next) => {
|
|
33
|
+
if (!controlled)
|
|
34
|
+
setUncontrolled(next);
|
|
35
|
+
onValueChange?.(next);
|
|
36
|
+
};
|
|
37
|
+
const clear = () => {
|
|
38
|
+
update('');
|
|
39
|
+
onClear?.();
|
|
40
|
+
input.current?.focus();
|
|
41
|
+
};
|
|
42
|
+
const handleChange = (event) => {
|
|
43
|
+
onChange?.(event);
|
|
44
|
+
update(event.target.value);
|
|
45
|
+
};
|
|
46
|
+
// Esc con texto limpia y no se propaga (no cierra un diálogo que lo contenga); sin texto, sigue de largo. Un onKeyDown
|
|
47
|
+
// de la app que llame a preventDefault se queda con el Esc.
|
|
48
|
+
const handleKeyDown = (event) => {
|
|
49
|
+
onKeyDown?.(event);
|
|
50
|
+
if (event.key !== 'Escape' || !canClear || event.defaultPrevented)
|
|
51
|
+
return;
|
|
52
|
+
event.preventDefault();
|
|
53
|
+
event.stopPropagation();
|
|
54
|
+
clear();
|
|
55
|
+
};
|
|
56
|
+
return (_jsxs("div", { className: className ? `dx-search-input ${className}` : 'dx-search-input', children: [_jsx(Input, { ...rest, ref: mergeRefs(input, ref), type: "search", value: text, onChange: handleChange, onKeyDown: handleKeyDown, iconStart: _jsx(SearchIcon, {}), className: "dx-search-input__field" }), canClear && (_jsx(IconButton, { label: clearLabel, icon: _jsx(ClearIcon, {}), variant: "ghost", size: "xs", className: "dx-search-input__clear", onMouseDown: keepFocus, onClick: clear }))] }));
|
|
57
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { SearchInput } from './SearchInput.js';
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { type AriaAttributes, type ComponentPropsWithRef, type ReactNode, type Ref } from 'react';
|
|
2
|
+
import { Select as SelectPrimitive } from 'radix-ui';
|
|
3
|
+
export interface SelectProps {
|
|
4
|
+
/** Las opciones: SelectItem, y si hace falta SelectGroup (con SelectLabel) y SelectSeparator. */
|
|
5
|
+
children: ReactNode;
|
|
6
|
+
/** La opción elegida (controlado). Radix no acepta `""` en un ítem: «Todos» usa un valor propio (p. ej. `"todos"`). */
|
|
7
|
+
value?: string | undefined;
|
|
8
|
+
/** La opción elegida al montar (no controlado). */
|
|
9
|
+
defaultValue?: string | undefined;
|
|
10
|
+
onValueChange?: ((value: string) => void) | undefined;
|
|
11
|
+
/** Texto del disparador sin opción elegida (en el color del placeholder de Input). */
|
|
12
|
+
placeholder?: ReactNode;
|
|
13
|
+
/** Nombre del campo en el formulario: el valor viaja en el `<select>` nativo oculto de Radix. */
|
|
14
|
+
name?: string | undefined;
|
|
15
|
+
required?: boolean | undefined;
|
|
16
|
+
disabled?: boolean | undefined;
|
|
17
|
+
/** id del `<form>` al que pertenece, si no está adentro. */
|
|
18
|
+
form?: string | undefined;
|
|
19
|
+
/** Van al disparador: así Select funciona como hijo único de Field. */
|
|
20
|
+
id?: string | undefined;
|
|
21
|
+
'aria-label'?: string | undefined;
|
|
22
|
+
'aria-labelledby'?: string | undefined;
|
|
23
|
+
'aria-describedby'?: string | undefined;
|
|
24
|
+
'aria-invalid'?: AriaAttributes['aria-invalid'];
|
|
25
|
+
/** Se suma a `dx-select`, en el disparador. */
|
|
26
|
+
className?: string | undefined;
|
|
27
|
+
/** El disparador (`<button role="combobox">`). */
|
|
28
|
+
ref?: Ref<HTMLButtonElement> | undefined;
|
|
29
|
+
}
|
|
30
|
+
export type SelectItemProps = Omit<ComponentPropsWithRef<typeof SelectPrimitive.Item>, 'asChild'>;
|
|
31
|
+
export type SelectGroupProps = Omit<ComponentPropsWithRef<typeof SelectPrimitive.Group>, 'asChild'>;
|
|
32
|
+
export type SelectLabelProps = Omit<ComponentPropsWithRef<typeof SelectPrimitive.Label>, 'asChild'>;
|
|
33
|
+
export type SelectSeparatorProps = Omit<ComponentPropsWithRef<typeof SelectPrimitive.Separator>, 'asChild' | 'children'>;
|
|
34
|
+
/**
|
|
35
|
+
* Lista de opciones con su disparador de 38px (Select de Radix): `role="combobox"` en el disparador, listbox, teclado,
|
|
36
|
+
* búsqueda por letra, foco y el `<select>` nativo oculto para formularios. Controlado (`value` + `onValueChange`) o no
|
|
37
|
+
* (`defaultValue`). id, aria-* y `className` van al disparador; `ref` también.
|
|
38
|
+
*/
|
|
39
|
+
export declare function Select({ children, value, defaultValue, onValueChange, placeholder, name, required, disabled, form, className, ref, ...trigger }: SelectProps): import("react").JSX.Element;
|
|
40
|
+
/**
|
|
41
|
+
* Una opción (`role="option"`): el texto y, si está elegida, la marca a la derecha. `value` no puede ser `""`. `textValue`
|
|
42
|
+
* es el texto de la búsqueda por letra cuando `children` no es texto. `className` se suma a `dx-select__item`.
|
|
43
|
+
*/
|
|
44
|
+
export declare function SelectItem({ children, className, ...rest }: SelectItemProps): import("react").JSX.Element;
|
|
45
|
+
/** Grupo de opciones (`role="group"`), nombrado por su SelectLabel. `className` se suma a `dx-select__group`. */
|
|
46
|
+
export declare function SelectGroup({ className, ...rest }: SelectGroupProps): import("react").JSX.Element;
|
|
47
|
+
/** Título de un grupo (no se elige ni recibe el foco). `className` se suma a `dx-select__label`. */
|
|
48
|
+
export declare function SelectLabel({ className, ...rest }: SelectLabelProps): import("react").JSX.Element;
|
|
49
|
+
/** Divisor de 1px entre grupos. `className` se suma a `dx-select__separator`. */
|
|
50
|
+
export declare function SelectSeparator({ className, ...rest }: SelectSeparatorProps): import("react").JSX.Element;
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
+
import { Children, isValidElement, useCallback, useLayoutEffect, useRef, useState } from 'react';
|
|
4
|
+
import { Select as SelectPrimitive } from 'radix-ui';
|
|
5
|
+
/** Separación del disparador, en px: 4 (`--dx-space-1`). */
|
|
6
|
+
const SIDE_OFFSET = 4;
|
|
7
|
+
/** Distancia mínima al borde de la ventana antes de mover o dar vuelta la lista: 8px (`--dx-space-2`), como DropdownMenu. */
|
|
8
|
+
const COLLISION_PADDING = 8;
|
|
9
|
+
/**
|
|
10
|
+
* Medidas de la lista que dependen de Radix: ancho mínimo el del disparador y alto máximo 360px (`--dx-select-content-max`,
|
|
11
|
+
* en select.css) o lo que quede hasta el borde de la ventana. Van acá porque check:css no admite `var(--radix-*)`. El
|
|
12
|
+
* outline también: Radix pone `outline: none` en línea, y en alto contraste select.css define `--dx-select-content-outline`.
|
|
13
|
+
*/
|
|
14
|
+
const CONTENT_STYLE = {
|
|
15
|
+
minWidth: 'var(--radix-select-trigger-width)',
|
|
16
|
+
maxHeight: 'min(var(--dx-select-content-max), var(--radix-select-content-available-height))',
|
|
17
|
+
outline: 'var(--dx-select-content-outline, none)',
|
|
18
|
+
};
|
|
19
|
+
/** La lista se monta en el ancestro más cercano que fija el tema, para heredar sus variables (claro u oscuro). */
|
|
20
|
+
const THEME_ROOT = '.dx-app, .dark, [data-theme="dark"]';
|
|
21
|
+
const cx = (own, extra) => (extra ? own + ' ' + extra : own);
|
|
22
|
+
/**
|
|
23
|
+
* El contenido de la opción con ese `value`, buscado entre los hijos (y los de cada grupo). Radix lo copia al disparador con
|
|
24
|
+
* un portal recién al hidratar; pasarlo como children de Select.Value hace que el HTML del servidor ya lo traiga. Se busca por
|
|
25
|
+
* la prop `value` y no por el tipo: un SelectItem que llega desde un Server Component es una referencia de cliente.
|
|
26
|
+
*/
|
|
27
|
+
function findItemContent(children, value) {
|
|
28
|
+
let found;
|
|
29
|
+
Children.forEach(children, (child) => {
|
|
30
|
+
if (found !== undefined || !isValidElement(child))
|
|
31
|
+
return;
|
|
32
|
+
found = child.props.value === value ? (child.props.children ?? null) : findItemContent(child.props.children, value);
|
|
33
|
+
});
|
|
34
|
+
return found;
|
|
35
|
+
}
|
|
36
|
+
const Chevron = ({ up = false }) => (_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: up ? 'M4 10l4-4 4 4' : 'M4 6l4 4 4-4' }) }));
|
|
37
|
+
/** Marca de la opción elegida: el mismo check de 16px que DropdownMenuRadioItem. */
|
|
38
|
+
const Check = () => (_jsx("svg", { viewBox: "0 0 16 16", width: "16", height: "16", fill: "none", stroke: "currentColor", strokeWidth: "1.75", strokeLinecap: "round", strokeLinejoin: "round", focusable: "false", children: _jsx("path", { d: "M3.5 8.5l3 3 6-7" }) }));
|
|
39
|
+
/**
|
|
40
|
+
* Lista de opciones con su disparador de 38px (Select de Radix): `role="combobox"` en el disparador, listbox, teclado,
|
|
41
|
+
* búsqueda por letra, foco y el `<select>` nativo oculto para formularios. Controlado (`value` + `onValueChange`) o no
|
|
42
|
+
* (`defaultValue`). id, aria-* y `className` van al disparador; `ref` también.
|
|
43
|
+
*/
|
|
44
|
+
export function Select({ children, value, defaultValue, onValueChange, placeholder, name, required, disabled, form, className, ref, ...trigger }) {
|
|
45
|
+
// Select siempre le pasa el valor a Radix (controlado): así sabe qué texto poner en el disparador, también en el servidor.
|
|
46
|
+
const [own, setOwn] = useState(defaultValue ?? '');
|
|
47
|
+
const current = value ?? own;
|
|
48
|
+
const change = (next) => {
|
|
49
|
+
if (value === undefined)
|
|
50
|
+
setOwn(next);
|
|
51
|
+
onValueChange?.(next);
|
|
52
|
+
};
|
|
53
|
+
const triggerRef = useRef(null);
|
|
54
|
+
const [container, setContainer] = useState(null);
|
|
55
|
+
const locate = () => { setContainer(triggerRef.current?.closest(THEME_ROOT) ?? null); };
|
|
56
|
+
// Al montar, antes de pintar: la lista ya sabe en qué tema montarse.
|
|
57
|
+
useLayoutEffect(locate, []);
|
|
58
|
+
const setTrigger = useCallback((el) => {
|
|
59
|
+
triggerRef.current = el;
|
|
60
|
+
if (typeof ref === 'function')
|
|
61
|
+
ref(el);
|
|
62
|
+
else if (ref)
|
|
63
|
+
ref.current = el;
|
|
64
|
+
}, [ref]);
|
|
65
|
+
const content = current === '' ? undefined : findItemContent(children, current);
|
|
66
|
+
return (_jsxs(SelectPrimitive.Root, { value: current, onValueChange: change, onOpenChange: (open) => { if (open)
|
|
67
|
+
locate(); }, ...(name === undefined ? {} : { name }), ...(required === undefined ? {} : { required }), ...(disabled === undefined ? {} : { disabled }), ...(form === undefined ? {} : { form }), children: [_jsxs(SelectPrimitive.Trigger, { ...trigger, ref: setTrigger, className: cx('dx-select', className), children: [_jsx("span", { className: "dx-select__value", children: _jsx(SelectPrimitive.Value, { placeholder: placeholder, children: content }) }), _jsx(SelectPrimitive.Icon, { className: "dx-select__icon", children: _jsx(Chevron, {}) })] }), _jsx(SelectPrimitive.Portal, { container: container, children: _jsxs(SelectPrimitive.Content, { className: "dx-select__content", position: "popper", side: "bottom", align: "start", sideOffset: SIDE_OFFSET, collisionPadding: COLLISION_PADDING, style: CONTENT_STYLE, children: [_jsx(SelectPrimitive.ScrollUpButton, { className: "dx-select__scroll", children: _jsx(Chevron, { up: true }) }), _jsx(SelectPrimitive.Viewport, { className: "dx-select__viewport", children: children }), _jsx(SelectPrimitive.ScrollDownButton, { className: "dx-select__scroll", children: _jsx(Chevron, {}) })] }) })] }));
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Una opción (`role="option"`): el texto y, si está elegida, la marca a la derecha. `value` no puede ser `""`. `textValue`
|
|
71
|
+
* es el texto de la búsqueda por letra cuando `children` no es texto. `className` se suma a `dx-select__item`.
|
|
72
|
+
*/
|
|
73
|
+
export function SelectItem({ children, className, ...rest }) {
|
|
74
|
+
return (_jsxs(SelectPrimitive.Item, { ...rest, className: cx('dx-select__item', className), children: [_jsx("span", { className: "dx-select__text", children: _jsx(SelectPrimitive.ItemText, { children: children }) }), _jsx("span", { className: "dx-select__mark", "aria-hidden": "true", children: _jsx(SelectPrimitive.ItemIndicator, { children: _jsx(Check, {}) }) })] }));
|
|
75
|
+
}
|
|
76
|
+
/** Grupo de opciones (`role="group"`), nombrado por su SelectLabel. `className` se suma a `dx-select__group`. */
|
|
77
|
+
export function SelectGroup({ className, ...rest }) {
|
|
78
|
+
return _jsx(SelectPrimitive.Group, { ...rest, className: cx('dx-select__group', className) });
|
|
79
|
+
}
|
|
80
|
+
/** Título de un grupo (no se elige ni recibe el foco). `className` se suma a `dx-select__label`. */
|
|
81
|
+
export function SelectLabel({ className, ...rest }) {
|
|
82
|
+
return _jsx(SelectPrimitive.Label, { ...rest, className: cx('dx-select__label', className) });
|
|
83
|
+
}
|
|
84
|
+
/** Divisor de 1px entre grupos. `className` se suma a `dx-select__separator`. */
|
|
85
|
+
export function SelectSeparator({ className, ...rest }) {
|
|
86
|
+
return _jsx(SelectPrimitive.Separator, { ...rest, className: cx('dx-select__separator', className) });
|
|
87
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { Select, SelectGroup, SelectItem, SelectLabel, SelectSeparator } from './Select.js';
|