@dubix/ui 0.2.0 → 0.3.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.
@@ -0,0 +1,233 @@
1
+ 'use client';
2
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
+ import { Children, Fragment, cloneElement, createContext, isValidElement, useContext, useEffect, useEffectEvent, useId, useLayoutEffect, useRef, useState, } from 'react';
4
+ import { Slot } from 'radix-ui';
5
+ import { Tooltip, TooltipProvider } from '../tooltip/index.js';
6
+ // 'use client' a propósito: Sidebar guarda estado (contraída, grupos abiertos) y lo comparte por contexto, escucha el atajo
7
+ // «[» y los ítems usan el Slot de Radix para asChild y el Tooltip. Es un componente cliente (README, «Componentes cliente»).
8
+ // tsc conserva la directiva porque es la primera sentencia del archivo.
9
+ const cx = (own, extra) => (extra ? own + ' ' + extra : own);
10
+ const hasNode = (node) => node != null && typeof node !== 'boolean' && node !== '';
11
+ /** Un ref callback que asigna el nodo a varios refs (el propio del componente y el de la app). */
12
+ function mergeRefs(...refs) {
13
+ return (node) => {
14
+ for (const ref of refs) {
15
+ if (typeof ref === 'function')
16
+ ref(node);
17
+ else if (ref)
18
+ ref.current = node;
19
+ }
20
+ };
21
+ }
22
+ /** El atajo de la barra: «[» alterna contraída y expandida. */
23
+ const SHORTCUT = '[';
24
+ /** Campos donde «[» se escribe: el atajo no actúa con el foco ahí. */
25
+ const EDITABLE = 'input, textarea, select, [contenteditable]:not([contenteditable="false"])';
26
+ /** Lo que deja de verse con la barra contraída y puede tener el foco: los subítems y la línea de la organización. */
27
+ const HIDDEN_COLLAPSED = '.dx-sidebar__sub, .dx-sidebar__meta';
28
+ /**
29
+ * Los tooltips de los ítems, del grupo y del usuario son del riel: con la barra expandida el texto ya se ve. El Tooltip
30
+ * queda montado siempre (si se agregara al contraer, React volvería a montar el enlace y se perdería el foco); expandida,
31
+ * el foco y el puntero llaman a preventDefault y el disparador de Radix no lo abre (composeEventHandlers lo respeta).
32
+ */
33
+ function railTooltipHandlers(collapsed, onFocus, onPointerMove) {
34
+ return {
35
+ onFocus: (event) => { onFocus?.(event); if (!collapsed)
36
+ event.preventDefault(); },
37
+ onPointerMove: (event) => { onPointerMove?.(event); if (!collapsed)
38
+ event.preventDefault(); },
39
+ };
40
+ }
41
+ /** Estado controlado o no controlado, con el mismo contrato que los componentes de Radix (value, defaultValue, onChange). */
42
+ function useControllable(value, defaultValue, onChange) {
43
+ const [inner, setInner] = useState(defaultValue);
44
+ const controlled = value !== undefined;
45
+ const current = controlled ? value : inner;
46
+ const set = (next) => {
47
+ if (!controlled)
48
+ setInner(next);
49
+ if (next !== current)
50
+ onChange?.(next);
51
+ };
52
+ return [current, set];
53
+ }
54
+ const SidebarContext = createContext(null);
55
+ /** Estado de la barra que la contiene (por ejemplo, para un botón «Contraer» del encabezado). Fuera de Sidebar, error claro. */
56
+ export function useSidebar() {
57
+ const ctx = useContext(SidebarContext);
58
+ if (!ctx)
59
+ throw new Error('useSidebar: tiene que usarse dentro de <Sidebar>.');
60
+ return ctx;
61
+ }
62
+ /**
63
+ * Barra lateral D2.1: un `<aside>` (nombrarlo con `aria-label`) con encabezado, navegación y pie; contraída, el riel de
64
+ * 64px con tooltips. `className` se suma a `dx-sidebar`; `ref` y el resto de las props van al `<aside>`.
65
+ */
66
+ export function Sidebar({ collapsed, defaultCollapsed = false, onCollapsedChange, collapseShortcut = true, className, children, ref, ...rest }) {
67
+ const [isCollapsed, setInner] = useControllable(collapsed, defaultCollapsed, onCollapsedChange);
68
+ const navId = useId();
69
+ const aside = useRef(null);
70
+ const collapseButton = useRef(null);
71
+ /** Lo que tenía el foco adentro de la barra cuando se pidió el cambio. */
72
+ const focused = useRef(null);
73
+ const setCollapsed = (next) => {
74
+ const active = document.activeElement;
75
+ focused.current = active && aside.current?.contains(active) ? active : null;
76
+ setInner(next);
77
+ };
78
+ // El foco no se pierde: si lo tenía algo que ya no se ve (un subítem, la organización) o que se reemplazó (el logo),
79
+ // pasa al botón de contraer. Antes de pintar, para que el navegador no lo mande al <body>.
80
+ useLayoutEffect(() => {
81
+ const el = focused.current;
82
+ focused.current = null;
83
+ if (el && (!el.isConnected || (isCollapsed && el.closest(HIDDEN_COLLAPSED))))
84
+ collapseButton.current?.focus();
85
+ }, [isCollapsed]);
86
+ const onShortcut = useEffectEvent((event) => {
87
+ if (event.key !== SHORTCUT || event.defaultPrevented || event.repeat || event.isComposing)
88
+ return;
89
+ // AltGr (Ctrl+Alt en Windows) es como se escribe «[» en algunos teclados: no cuenta como modificador.
90
+ if (event.metaKey || ((event.ctrlKey || event.altKey) && !event.getModifierState('AltGraph')))
91
+ return;
92
+ if (event.target instanceof Element && event.target.closest(EDITABLE))
93
+ return;
94
+ setCollapsed(!isCollapsed);
95
+ });
96
+ useEffect(() => {
97
+ if (!collapseShortcut)
98
+ return;
99
+ const listener = (event) => { onShortcut(event); };
100
+ document.addEventListener('keydown', listener);
101
+ return () => { document.removeEventListener('keydown', listener); };
102
+ }, [collapseShortcut]);
103
+ return (_jsx(SidebarContext, { value: { collapsed: isCollapsed, setCollapsed, navId, shortcut: collapseShortcut, collapseButton }, children: _jsx("aside", { ...rest, ref: mergeRefs(aside, ref), className: cx('dx-sidebar', className), "data-collapsed": isCollapsed ? 'true' : 'false', children: _jsx(TooltipProvider, { children: children }) }) }));
104
+ }
105
+ /** El estado contraído de la barra que lo contiene; fuera de una barra, expandida. */
106
+ const useCollapsed = () => useContext(SidebarContext)?.collapsed ?? false;
107
+ /**
108
+ * Encabezado: una fila de 32px con el logo y las acciones, y la línea de la organización debajo. Contraída: el logo del
109
+ * riel (`logoCollapsed`, si lo hay) y las acciones, una debajo de la otra, centradas.
110
+ */
111
+ export function SidebarHeader({ logo, logoCollapsed, actions, meta, className, ...rest }) {
112
+ const shown = useCollapsed() && hasNode(logoCollapsed) ? logoCollapsed : logo;
113
+ return (_jsxs("div", { ...rest, className: cx('dx-sidebar__header', className), children: [_jsxs("div", { className: "dx-sidebar__bar", children: [hasNode(shown) && _jsx("div", { className: "dx-sidebar__logo", children: shown }), hasNode(actions) && _jsx("div", { className: "dx-sidebar__actions", children: actions })] }), hasNode(meta) && _jsx("p", { className: "dx-sidebar__meta", children: meta })] }));
114
+ }
115
+ /** Botón de ícono de 32×32 del encabezado. `type="button"` por defecto; `ref` y props al `<button>` (sirve de disparador de Tooltip). */
116
+ export function SidebarHeaderButton({ className, children, type = 'button', ...rest }) {
117
+ return (_jsx("button", { ...rest, type: type, className: cx('dx-sidebar__action', className), children: _jsx("span", { className: "dx-sidebar__action-icon", "aria-hidden": "true", children: children }) }));
118
+ }
119
+ /**
120
+ * Botón «Contraer barra lateral» / «Expandir barra lateral» del encabezado (el último de `actions`), con su tooltip y el
121
+ * atajo: `aria-expanded` (true con la barra expandida), `aria-controls` al `<nav>` y `aria-keyshortcuts="["`. Con el
122
+ * atajo apagado, sin `aria-keyshortcuts` ni atajo en el tooltip. Tiene que ir dentro de `Sidebar`.
123
+ */
124
+ export function SidebarCollapseButton({ onClick, ref, ...rest }) {
125
+ const ctx = useContext(SidebarContext);
126
+ if (!ctx)
127
+ throw new Error('SidebarCollapseButton: tiene que usarse dentro de <Sidebar>.');
128
+ const { collapsed, setCollapsed, navId, shortcut, collapseButton } = ctx;
129
+ const label = collapsed ? 'Expandir barra lateral' : 'Contraer barra lateral';
130
+ return (_jsx(Tooltip, { content: label, shortcut: shortcut ? SHORTCUT : undefined, side: "right", children: _jsx(SidebarHeaderButton, { ...rest, ref: mergeRefs(collapseButton, ref), "aria-label": label, "aria-expanded": !collapsed, "aria-controls": navId, "aria-keyshortcuts": shortcut ? SHORTCUT : undefined, onClick: (event) => { onClick?.(event); if (!event.defaultPrevented)
131
+ setCollapsed(!collapsed); }, children: _jsxs("svg", { className: "dx-sidebar__glyph", viewBox: "0 0 24 24", "aria-hidden": "true", focusable: "false", children: [_jsx("rect", { x: "3", y: "3", width: "18", height: "18", rx: "2" }), _jsx("path", { d: "M9 3v18" })] }) }) }));
132
+ }
133
+ /** `<nav>` con scroll propio y la lista de ítems. Con más de una navegación en la página, nombrarla con `aria-label`. */
134
+ export function SidebarNav({ className, children, ...rest }) {
135
+ const navId = useContext(SidebarContext)?.navId;
136
+ return (_jsx("nav", { ...rest, id: navId, className: cx('dx-sidebar__nav', className), children: _jsx("ul", { className: "dx-sidebar__list", children: children }) }));
137
+ }
138
+ /**
139
+ * Ícono, texto y contador de un ítem. El número visible va con aria-hidden y los lectores reciben «, 3 pendientes» (o
140
+ * «, 3» sin countLabel) en un texto oculto: así el nombre del enlace es «Inbox, 3 pendientes» y no «Inbox3».
141
+ */
142
+ function linkContent({ icon, count, countLabel, children }) {
143
+ const hasCount = hasNode(count);
144
+ return (_jsxs(_Fragment, { children: [hasNode(icon) && _jsx("span", { className: "dx-sidebar__icon", "aria-hidden": "true", children: icon }), _jsx("span", { className: "dx-sidebar__label", children: children }), hasCount && _jsxs(_Fragment, { children: [_jsx("span", { className: "dx-sidebar__count", "aria-hidden": "true", children: count }), _jsxs("span", { className: "dx-sidebar__sr", children: [", ", countLabel || count] })] })] }));
145
+ }
146
+ function SidebarLink({ asChild, current, className, children, parts, ...rest }) {
147
+ const props = { ...rest, className, 'aria-current': current ? 'page' : rest['aria-current'] };
148
+ if (asChild) {
149
+ if (!isValidElement(children))
150
+ throw new Error('Sidebar: con asChild, children tiene que ser un único elemento (p. ej. <Link>).');
151
+ return _jsx(Slot.Root, { ...props, children: cloneElement(children, undefined, linkContent({ ...parts, children: children.props.children })) });
152
+ }
153
+ return _jsx("a", { ...props, children: linkContent({ ...parts, children }) });
154
+ }
155
+ /** Texto del tooltip del riel: el nombre y, si hay, el contador atenuado. */
156
+ function railTip(label, count) {
157
+ return hasNode(count) ? _jsxs(_Fragment, { children: [label, _jsx("span", { className: "dx-sidebar__tip-count", children: count })] }) : label;
158
+ }
159
+ /**
160
+ * Ítem de primer nivel: un `<li>` con el enlace. `className`, `ref` y props van al `<a>` (o al hijo con asChild).
161
+ * Contraída, solo el ícono, con un tooltip a la derecha con el nombre y el contador.
162
+ */
163
+ export function SidebarItem({ icon, count, countLabel, className, onFocus, onPointerMove, ...rest }) {
164
+ const collapsed = useCollapsed();
165
+ const label = rest.asChild && isValidElement(rest.children) ? rest.children.props.children : rest.children;
166
+ return (_jsx("li", { className: "dx-sidebar__entry", children: _jsx(Tooltip, { content: railTip(label, count), side: "right", children: _jsx(SidebarLink, { ...rest, ...railTooltipHandlers(collapsed, onFocus, onPointerMove), className: cx('dx-sidebar__item', className), parts: { icon, count, countLabel } }) }) }));
167
+ }
168
+ /** Subítem de un grupo (sin ícono). `className`, `ref` y props van al `<a>` (o al hijo con asChild). */
169
+ export function SidebarSubItem({ count, countLabel, className, ...rest }) {
170
+ return (_jsx("li", { className: "dx-sidebar__entry", children: _jsx(SidebarLink, { ...rest, className: cx('dx-sidebar__item', className), "data-level": "sub", parts: { count, countLabel } }) }));
171
+ }
172
+ function TitledList({ label, className, children, own, ...rest }) {
173
+ const id = useId();
174
+ return (_jsxs("li", { ...rest, className: cx(own, className), children: [_jsx("span", { className: "dx-sidebar__title", id: id, children: label }), _jsx("ul", { className: "dx-sidebar__list", "aria-labelledby": id, children: children })] }));
175
+ }
176
+ /** Sección de primer nivel con título (p. ej. «Favoritos»): sus hijos son `SidebarItem`. */
177
+ export function SidebarSection(props) {
178
+ return _jsx(TitledList, { ...props, own: "dx-sidebar__section" });
179
+ }
180
+ /** Subgrupo con título dentro de un `SidebarGroup` (p. ej. «Cuenta»): sus hijos son `SidebarSubItem`. */
181
+ export function SidebarSubGroup(props) {
182
+ return _jsx(TitledList, { ...props, own: "dx-sidebar__subgroup" });
183
+ }
184
+ /* ------------------------------------------------------------------------------------------------------------------ Grupo */
185
+ /** true si entre los hijos (directos, en fragmentos o en subgrupos) hay un SidebarSubItem actual. */
186
+ function containsCurrent(children) {
187
+ return Children.toArray(children).some((child) => {
188
+ if (!isValidElement(child))
189
+ return false;
190
+ if (child.type === SidebarSubItem)
191
+ return child.props.current === true;
192
+ if (child.type === Fragment || child.type === SidebarSubGroup)
193
+ return containsCurrent(child.props.children);
194
+ return false;
195
+ });
196
+ }
197
+ /**
198
+ * Grupo desplegable: un `<button>` con `aria-expanded` y `aria-controls`, y la lista de subítems. Cerrado y con la página
199
+ * actual adentro, el botón lleva la marca de actual (`aria-current="true"`). `className`, `ref` y props van al `<button>`.
200
+ * Contraída, el grupo se ve cerrado (solo el ícono, con tooltip) y el clic expande la barra y lo abre.
201
+ */
202
+ export function SidebarGroup({ label, icon, open, defaultOpen = false, onOpenChange, current, className, children, onClick, onFocus, onPointerMove, ...rest }) {
203
+ const [isOpen, setOpen] = useControllable(open, defaultOpen, onOpenChange);
204
+ const ctx = useContext(SidebarContext);
205
+ const collapsed = ctx?.collapsed ?? false;
206
+ const id = useId();
207
+ const expanded = isOpen && !collapsed;
208
+ const marked = !expanded && (current ?? containsCurrent(children));
209
+ return (_jsxs("li", { className: "dx-sidebar__entry", children: [_jsx(Tooltip, { content: label, side: "right", children: _jsxs("button", { type: "button", ...rest, ...railTooltipHandlers(collapsed, onFocus, onPointerMove), className: cx('dx-sidebar__item', className), "data-level": "group", "aria-expanded": expanded, "aria-controls": id, "aria-current": marked ? 'true' : rest['aria-current'], onClick: (event) => {
210
+ onClick?.(event);
211
+ if (event.defaultPrevented)
212
+ return;
213
+ if (collapsed) {
214
+ ctx?.setCollapsed(false);
215
+ setOpen(true);
216
+ }
217
+ else
218
+ setOpen(!isOpen);
219
+ }, children: [hasNode(icon) && _jsx("span", { className: "dx-sidebar__icon", "aria-hidden": "true", children: icon }), _jsx("span", { className: "dx-sidebar__label", children: label }), _jsx("svg", { className: "dx-sidebar__chevron", viewBox: "0 0 24 24", "aria-hidden": "true", focusable: "false", children: _jsx("path", { d: "m9 18 6-6-6-6" }) })] }) }), _jsx("ul", { className: "dx-sidebar__sub", id: id, hidden: !expanded, children: children })] }));
220
+ }
221
+ /** Pie con una regla arriba (p. ej. el botón del usuario). */
222
+ export function SidebarFooter({ className, ...rest }) {
223
+ return _jsx("div", { ...rest, className: cx('dx-sidebar__footer', className) });
224
+ }
225
+ /**
226
+ * Botón del usuario del pie: avatar, nombre y rol, y las flechas de un menú. Pensado como disparador de un menú
227
+ * (`DropdownMenu.Trigger asChild`): `ref` y props van al `<button>`. `type="button"` por defecto. Contraída, solo el
228
+ * avatar, con el nombre en un tooltip y el mismo nombre accesible.
229
+ */
230
+ export function SidebarUserButton({ name, roleLabel, avatar, className, type = 'button', onFocus, onPointerMove, ...rest }) {
231
+ const collapsed = useCollapsed();
232
+ return (_jsx(Tooltip, { content: name, side: "right", children: _jsxs("button", { ...rest, ...railTooltipHandlers(collapsed, onFocus, onPointerMove), type: type, className: cx('dx-sidebar__user', className), children: [hasNode(avatar) && _jsx("span", { className: "dx-sidebar__user-avatar", "aria-hidden": "true", children: avatar }), _jsxs("span", { className: "dx-sidebar__user-text", children: [_jsx("span", { className: "dx-sidebar__user-name", children: name }), roleLabel ? _jsxs(_Fragment, { children: [_jsx("span", { className: "dx-sidebar__user-role", "aria-hidden": "true", children: roleLabel }), _jsxs("span", { className: "dx-sidebar__sr", children: [", ", roleLabel] })] }) : null] }), _jsxs("svg", { className: "dx-sidebar__user-arrows", viewBox: "0 0 24 24", "aria-hidden": "true", focusable: "false", children: [_jsx("path", { d: "m7 15 5 5 5-5" }), _jsx("path", { d: "m7 9 5-5 5 5" })] })] }) }));
233
+ }
@@ -0,0 +1,2 @@
1
+ export { Sidebar, SidebarCollapseButton, SidebarFooter, SidebarGroup, SidebarHeader, SidebarHeaderButton, SidebarItem, SidebarNav, SidebarSection, SidebarSubGroup, SidebarSubItem, SidebarUserButton, useSidebar, } from './Sidebar.js';
2
+ export type { SidebarCollapseButtonProps, SidebarContextValue, SidebarFooterProps, SidebarGroupProps, SidebarHeaderButtonProps, SidebarHeaderProps, SidebarItemProps, SidebarNavProps, SidebarProps, SidebarSectionProps, SidebarSubGroupProps, SidebarSubItemProps, SidebarUserButtonProps, } from './Sidebar.js';
@@ -0,0 +1 @@
1
+ export { Sidebar, SidebarCollapseButton, SidebarFooter, SidebarGroup, SidebarHeader, SidebarHeaderButton, SidebarItem, SidebarNav, SidebarSection, SidebarSubGroup, SidebarSubItem, SidebarUserButton, useSidebar, } from './Sidebar.js';