danielgm-ui 0.2.0 → 0.4.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.
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2020-2026 Paweł Kuna
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2020-2026 Paweł Kuna
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/dist/combobox.js CHANGED
@@ -11,7 +11,7 @@ import { CheckIcon, ChevronIcon } from './internal/icons.js';
11
11
  import { cx, hasContent } from './utils.js';
12
12
  import { ScrollHints } from './internal/scroll-hints.js';
13
13
  import { useFieldOpen } from './internal/field-open.js';
14
- import { OverlayLayerProvider, useOverlayLayer } from './internal/overlay-layer.js';
14
+ import { OverlayLayerProvider, OverlayScrollBoundary, useOverlayLayer, } from './internal/overlay-layer.js';
15
15
  /** Selección única de un catálogo; no permite enviar texto libre como valor. */
16
16
  export const Combobox = forwardRef(function Combobox({ label, options, value, defaultValue = '', onValueChange, placeholder, searchPlaceholder, emptyMessage, description, error, name, required, disabled, clearable = false, locale = 'en', id, className, wrapperClassName, }, ref) {
17
17
  const [selected, change] = useControllable(value, defaultValue, onValueChange);
@@ -39,16 +39,16 @@ export const Combobox = forwardRef(function Combobox({ label, options, value, de
39
39
  event.preventDefault();
40
40
  setInvalid(true);
41
41
  trigger.current?.focus({ preventScroll: true });
42
- }, children: [_jsx("option", { value: "" }), options.map((option) => (_jsx("option", { value: option.value, disabled: option.disabled, children: option.label }, option.value)))] }), _jsx(OverlayLayerProvider, { depth: depth, children: _jsxs(Popover.Root, { open: open, onOpenChange: setOpen, children: [_jsxs(Popover.Trigger, { ref: trigger, id: controlId, disabled: disabled, "aria-labelledby": `${controlId}-label ${controlId}-value`, "aria-describedby": describedBy, "aria-invalid": hasContent(message) || undefined, className: cx('dgm-input', 'dgm-combobox-trigger', className), children: [_jsxs("span", { className: "dgm-custom-value", id: `${controlId}-value`, children: [current?.icon && (_jsx("span", { className: "dgm-option-icon", "aria-hidden": "true", children: current.icon })), current?.label ?? placeholder ?? (es ? 'Seleccionar…' : 'Select…')] }), _jsx("span", { className: "dgm-custom-chevron", children: _jsx(ChevronIcon, {}) })] }), _jsx(Popover.Portal, { children: _jsx(Popover.Content, { className: "dgm-combobox-panel", style: layerStyle, sideOffset: 6, collisionPadding: 12, "aria-labelledby": `${controlId}-label`, onInteractOutside: (event) => {
43
- if (preventTriggerLabelDismiss(event, trigger.current))
44
- return;
45
- interactedOutside.current = true;
46
- }, onCloseAutoFocus: (event) => {
47
- event.preventDefault();
48
- if (!interactedOutside.current)
49
- restoreFocus(trigger.current);
50
- interactedOutside.current = false;
51
- }, children: _jsxs(Command, { defaultValue: selected, className: "dgm-command", label: es ? 'Opciones' : 'Options', loop: true, children: [_jsx(Command.Input, { className: "dgm-command-input", "aria-label": searchPlaceholder ?? (es ? 'Buscar opciones' : 'Search options'), placeholder: searchPlaceholder ?? (es ? 'Buscar…' : 'Search…') }), _jsx(ScrollHints, { children: _jsxs(Command.List, { className: "dgm-command-list", children: [_jsx(Command.Empty, { className: "dgm-command-empty", children: emptyMessage ?? (es ? 'Sin resultados.' : 'No results.') }), options.map((option) => (_jsxs(Command.Item, { value: option.value, keywords: [option.label, ...(option.keywords ?? [])], disabled: disabled || option.disabled, onSelect: () => choose(option.value), className: "dgm-command-item", children: [option.icon && (_jsx("span", { className: "dgm-option-icon", "aria-hidden": "true", children: option.icon })), _jsx("span", { children: option.label }), option.value === selected && (_jsx("span", { className: "dgm-command-check", "aria-hidden": "true", children: _jsx(CheckIcon, {}) }))] }, option.value)))] }) })] }) }) })] }) }), clearable && selected && (_jsx("button", { type: "button", className: "dgm-text-action", disabled: disabled, onClick: () => {
42
+ }, children: [_jsx("option", { value: "" }), options.map((option) => (_jsx("option", { value: option.value, disabled: option.disabled, children: option.label }, option.value)))] }), _jsx(OverlayLayerProvider, { depth: depth, children: _jsxs(Popover.Root, { open: open, onOpenChange: setOpen, children: [_jsxs(Popover.Trigger, { ref: trigger, id: controlId, disabled: disabled, "aria-labelledby": `${controlId}-label ${controlId}-value`, "aria-describedby": describedBy, "aria-invalid": hasContent(message) || undefined, className: cx('dgm-input', 'dgm-combobox-trigger', className), children: [_jsxs("span", { className: "dgm-custom-value", id: `${controlId}-value`, children: [current?.icon && (_jsx("span", { className: "dgm-option-icon", "aria-hidden": "true", children: current.icon })), current?.label ?? placeholder ?? (es ? 'Seleccionar…' : 'Select…')] }), _jsx("span", { className: "dgm-custom-chevron", children: _jsx(ChevronIcon, {}) })] }), _jsx(Popover.Portal, { children: _jsx(OverlayScrollBoundary, { children: _jsx(Popover.Content, { className: "dgm-combobox-panel", style: layerStyle, sideOffset: 6, collisionPadding: 12, "aria-labelledby": `${controlId}-label`, onInteractOutside: (event) => {
43
+ if (preventTriggerLabelDismiss(event, trigger.current))
44
+ return;
45
+ interactedOutside.current = true;
46
+ }, onCloseAutoFocus: (event) => {
47
+ event.preventDefault();
48
+ if (!interactedOutside.current)
49
+ restoreFocus(trigger.current);
50
+ interactedOutside.current = false;
51
+ }, children: _jsxs(Command, { defaultValue: selected, className: "dgm-command", label: es ? 'Opciones' : 'Options', loop: true, children: [_jsx(Command.Input, { className: "dgm-command-input", "aria-label": searchPlaceholder ?? (es ? 'Buscar opciones' : 'Search options'), placeholder: searchPlaceholder ?? (es ? 'Buscar…' : 'Search…') }), _jsx(ScrollHints, { children: _jsxs(Command.List, { className: "dgm-command-list", children: [_jsx(Command.Empty, { className: "dgm-command-empty", children: emptyMessage ?? (es ? 'Sin resultados.' : 'No results.') }), options.map((option) => (_jsxs(Command.Item, { value: option.value, keywords: [option.label, ...(option.keywords ?? [])], disabled: disabled || option.disabled, onSelect: () => choose(option.value), className: "dgm-command-item", children: [option.icon && (_jsx("span", { className: "dgm-option-icon", "aria-hidden": "true", children: option.icon })), _jsx("span", { children: option.label }), option.value === selected && (_jsx("span", { className: "dgm-command-check", "aria-hidden": "true", children: _jsx(CheckIcon, {}) }))] }, option.value)))] }) })] }) }) }) })] }) }), clearable && selected && (_jsx("button", { type: "button", className: "dgm-text-action", disabled: disabled, onClick: () => {
52
52
  choose('');
53
53
  trigger.current?.focus({ preventScroll: true });
54
54
  }, children: es ? 'Borrar selección' : 'Clear selection' })), hasContent(description) && (_jsx("span", { className: "dgm-description", id: `${controlId}-description`, children: description })), hasContent(message) && (_jsx("span", { className: "dgm-error", id: `${controlId}-error`, children: message }))] }));
@@ -11,7 +11,7 @@ import { useControllable } from './internal/state.js';
11
11
  import { restoreFocus } from './internal/focus.js';
12
12
  import { preventTriggerLabelDismiss } from './internal/trigger-label.js';
13
13
  import { useFieldOpen } from './internal/field-open.js';
14
- import { OverlayLayerProvider, useOverlayLayer } from './internal/overlay-layer.js';
14
+ import { OverlayLayerProvider, OverlayScrollBoundary, useOverlayLayer, } from './internal/overlay-layer.js';
15
15
  import { cx, hasContent } from './utils.js';
16
16
  /** Conserva la orientación de DayPicker y unifica sus controles con el resto de iconos. */
17
17
  function CalendarChevron({ orientation = 'down', size = 18, className, style, }) {
@@ -112,22 +112,22 @@ function CalendarField({ props, from, to, range, onSelect, }) {
112
112
  event.preventDefault();
113
113
  setInvalid(true);
114
114
  trigger.current?.focus({ preventScroll: true });
115
- } })), _jsx(OverlayLayerProvider, { depth: depth, children: _jsxs(Popover.Root, { open: open, onOpenChange: setOpen, children: [_jsxs(Popover.Trigger, { ref: trigger, id: controlId, disabled: disabled, className: cx('dgm-input', 'dgm-date-trigger', className), "aria-labelledby": `${controlId}-label ${controlId}-value`, "aria-describedby": describedBy, "aria-invalid": hasContent(message) || undefined, children: [_jsx("span", { id: `${controlId}-value`, children: display }), _jsx(CalendarIcon, {})] }), _jsx(Popover.Portal, { children: _jsx(Popover.Content, { className: "dgm-calendar-panel", style: layerStyle, sideOffset: 6, collisionPadding: 12, "aria-labelledby": `${controlId}-label`, onInteractOutside: (event) => {
116
- if (preventTriggerLabelDismiss(event, trigger.current))
117
- return;
118
- interactedOutside.current = true;
119
- }, onCloseAutoFocus: (event) => {
120
- event.preventDefault();
121
- if (!interactedOutside.current)
122
- restoreFocus(trigger.current);
123
- interactedOutside.current = false;
124
- }, children: range ? (_jsx(DayPicker, { ...shared, mode: "range", excludeDisabled: true, selected: first ? { from: first, to: last } : undefined, onSelect: (selection, day) => {
125
- // El primer clic inicia un intervalo; el segundo lo completa, incluso en el mismo día.
126
- if (!first || last)
127
- choose(toDay(day));
128
- else
129
- choose(selection?.from ? toDay(selection.from) : undefined, selection?.to ? toDay(selection.to) : undefined);
130
- } })) : (_jsx(DayPicker, { ...shared, mode: "single", selected: first, onSelect: (selection) => choose(selection ? toDay(selection) : undefined) })) }) })] }) }), clearable && first && (_jsx("button", { type: "button", className: "dgm-text-action", disabled: disabled, onClick: () => {
115
+ } })), _jsx(OverlayLayerProvider, { depth: depth, children: _jsxs(Popover.Root, { open: open, onOpenChange: setOpen, children: [_jsxs(Popover.Trigger, { ref: trigger, id: controlId, disabled: disabled, className: cx('dgm-input', 'dgm-date-trigger', className), "aria-labelledby": `${controlId}-label ${controlId}-value`, "aria-describedby": describedBy, "aria-invalid": hasContent(message) || undefined, children: [_jsx("span", { id: `${controlId}-value`, children: display }), _jsx(CalendarIcon, {})] }), _jsx(Popover.Portal, { children: _jsx(OverlayScrollBoundary, { children: _jsx(Popover.Content, { className: "dgm-calendar-panel", style: layerStyle, sideOffset: 6, collisionPadding: 12, "aria-labelledby": `${controlId}-label`, onInteractOutside: (event) => {
116
+ if (preventTriggerLabelDismiss(event, trigger.current))
117
+ return;
118
+ interactedOutside.current = true;
119
+ }, onCloseAutoFocus: (event) => {
120
+ event.preventDefault();
121
+ if (!interactedOutside.current)
122
+ restoreFocus(trigger.current);
123
+ interactedOutside.current = false;
124
+ }, children: range ? (_jsx(DayPicker, { ...shared, mode: "range", excludeDisabled: true, selected: first ? { from: first, to: last } : undefined, onSelect: (selection, day) => {
125
+ // El primer clic inicia un intervalo; el segundo lo completa, incluso en el mismo día.
126
+ if (!first || last)
127
+ choose(toDay(day));
128
+ else
129
+ choose(selection?.from ? toDay(selection.from) : undefined, selection?.to ? toDay(selection.to) : undefined);
130
+ } })) : (_jsx(DayPicker, { ...shared, mode: "single", selected: first, onSelect: (selection) => choose(selection ? toDay(selection) : undefined) })) }) }) })] }) }), clearable && first && (_jsx("button", { type: "button", className: "dgm-text-action", disabled: disabled, onClick: () => {
131
131
  choose();
132
132
  trigger.current?.focus({ preventScroll: true });
133
133
  }, children: isSpanish ? 'Borrar fecha' : 'Clear date' })), hasContent(description) && (_jsx("span", { className: "dgm-description", id: `${controlId}-description`, children: description })), hasContent(message) && (_jsx("span", { className: "dgm-error", id: `${controlId}-error`, children: message }))] }));
package/dist/drawer.js CHANGED
@@ -10,9 +10,10 @@ import { cx, hasContent } from './utils.js';
10
10
  /** Atrapa el foco, bloquea el fondo y mantiene la cabecera y las acciones visibles. */
11
11
  export function Drawer({ open, onOpenChange, title, description, children, footer, side = 'right', closeLabel = 'Close drawer', closeOnOverlayClick = true, className, }) {
12
12
  const { depth, style: layerStyle } = useOverlayLayer();
13
+ const scrollContainer = useRef(null);
13
14
  const returnFocus = useRef(null);
14
15
  const descriptionId = useId();
15
- return (_jsx(OverlayLayerProvider, { depth: depth, children: _jsx(Dialog.Root, { open: open, onOpenChange: onOpenChange, children: _jsxs(Dialog.Portal, { children: [_jsx(Dialog.Overlay, { className: "dgm-modal-overlay", style: layerStyle }), _jsxs(Dialog.Content, { style: layerStyle, className: cx('dgm-drawer', `dgm-drawer--${side}`, className), "aria-describedby": hasContent(description) ? descriptionId : undefined, onOpenAutoFocus: () => {
16
+ return (_jsx(OverlayLayerProvider, { depth: depth, scrollContainer: scrollContainer, children: _jsx(Dialog.Root, { open: open, onOpenChange: onOpenChange, children: _jsxs(Dialog.Portal, { children: [_jsx(Dialog.Overlay, { className: "dgm-modal-overlay", style: layerStyle }), _jsxs(Dialog.Content, { ref: scrollContainer, style: layerStyle, className: cx('dgm-drawer', `dgm-drawer--${side}`, className), "aria-describedby": hasContent(description) ? descriptionId : undefined, onOpenAutoFocus: () => {
16
17
  returnFocus.current =
17
18
  document.activeElement instanceof HTMLElement ? document.activeElement : null;
18
19
  }, onCloseAutoFocus: (event) => {
@@ -0,0 +1,24 @@
1
+ /** Recorte local: el navegador decodifica la imagen y exporta el área visible a un Blob. */
2
+ import { type HTMLAttributes, type ReactElement } from 'react';
3
+ /** Opciones del recortador. Las URLs externas requieren CORS para poder exportarse. */
4
+ export interface ImageCropperProps extends Omit<HTMLAttributes<HTMLDivElement>, 'onError'> {
5
+ /** Archivo local, Blob o URL de la imagen; null muestra el estado vacío. */
6
+ src: string | Blob | null;
7
+ /** Recibe el archivo recortado, sin realizar ninguna subida. */
8
+ onCrop: (blob: Blob) => void | Promise<void>;
9
+ /** Relación anchura/altura del recorte. @defaultValue 1 */
10
+ aspectRatio?: number;
11
+ /** Anchura de salida en píxeles. @defaultValue 512 */
12
+ outputWidth?: number;
13
+ /** Formato de salida del canvas. @defaultValue 'image/png' */
14
+ outputType?: 'image/png' | 'image/jpeg' | 'image/webp';
15
+ /** Calidad JPEG/WebP entre 0 y 1. @defaultValue 0.92 */
16
+ quality?: number;
17
+ /** Límite superior del zoom respecto al encuadre inicial. @defaultValue 4 */
18
+ maxZoom?: number;
19
+ /** Idioma de los controles integrados. @defaultValue 'en' */
20
+ locale?: 'es' | 'en';
21
+ disabled?: boolean;
22
+ }
23
+ /** Visor con arrastre, zoom, desplazamiento por teclado y exportación al confirmar. */
24
+ export declare function ImageCropper({ src, onCrop, aspectRatio, outputWidth, outputType, quality, maxZoom, locale, disabled, className, style, ...props }: ImageCropperProps): ReactElement;
@@ -0,0 +1,180 @@
1
+ 'use client';
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ /** Recorte local: el navegador decodifica la imagen y exporta el área visible a un Blob. */
4
+ import { useEffect, useId, useRef, useState, } from 'react';
5
+ import { Button } from './button.js';
6
+ import { Slider } from './slider.js';
7
+ import { clampCropOffset, getCropGeometry } from './internal/image-crop.js';
8
+ import { cx } from './utils.js';
9
+ /** Visor con arrastre, zoom, desplazamiento por teclado y exportación al confirmar. */
10
+ export function ImageCropper({ src, onCrop, aspectRatio = 1, outputWidth = 512, outputType = 'image/png', quality = 0.92, maxZoom = 4, locale = 'en', disabled = false, className, style, ...props }) {
11
+ const [imageUrl, setImageUrl] = useState();
12
+ const [imageSize, setImageSize] = useState();
13
+ const [viewport, setViewport] = useState({ width: 0, height: 0 });
14
+ const [zoom, setZoom] = useState(1);
15
+ const [offset, setOffset] = useState({ x: 0, y: 0 });
16
+ const [dragging, setDragging] = useState(false);
17
+ const [saving, setSaving] = useState(false);
18
+ const [message, setMessage] = useState();
19
+ const stage = useRef(null);
20
+ const image = useRef(null);
21
+ const drag = useRef(undefined);
22
+ const id = useId();
23
+ const es = locale === 'es';
24
+ const ratio = Number.isFinite(aspectRatio) && aspectRatio > 0 ? aspectRatio : 1;
25
+ const zoomLimit = Number.isFinite(maxZoom) ? Math.max(1, maxZoom) : 4;
26
+ const width = Number.isFinite(outputWidth) ? Math.max(1, Math.round(outputWidth)) : 512;
27
+ const geometry = imageSize && viewport.width > 0 && viewport.height > 0
28
+ ? getCropGeometry(imageSize.width, imageSize.height, viewport.width, viewport.height, zoom, offset)
29
+ : undefined;
30
+ useEffect(() => {
31
+ if (!geometry)
32
+ return;
33
+ setOffset((current) => {
34
+ const next = clampCropOffset(current, geometry);
35
+ return next.x === current.x && next.y === current.y ? current : next;
36
+ });
37
+ // La posición se ajusta solo cuando cambian las medidas o el zoom.
38
+ }, [imageSize?.width, imageSize?.height, viewport.width, viewport.height, zoom]);
39
+ useEffect(() => {
40
+ drag.current = undefined;
41
+ setDragging(false);
42
+ setImageSize(undefined);
43
+ setOffset({ x: 0, y: 0 });
44
+ setZoom(1);
45
+ setMessage(undefined);
46
+ if (!src) {
47
+ setImageUrl(undefined);
48
+ return;
49
+ }
50
+ const url = typeof src === 'string' ? src : URL.createObjectURL(src);
51
+ setImageUrl(url);
52
+ return () => {
53
+ if (typeof src !== 'string')
54
+ URL.revokeObjectURL(url);
55
+ };
56
+ }, [src]);
57
+ useEffect(() => {
58
+ if (!disabled)
59
+ return;
60
+ drag.current = undefined;
61
+ setDragging(false);
62
+ }, [disabled]);
63
+ useEffect(() => {
64
+ if (!stage.current)
65
+ return;
66
+ const observer = new ResizeObserver(([entry]) => {
67
+ setViewport({ width: entry.contentRect.width, height: entry.contentRect.height });
68
+ });
69
+ observer.observe(stage.current);
70
+ return () => observer.disconnect();
71
+ }, []);
72
+ function move(next) {
73
+ if (!geometry)
74
+ return;
75
+ setOffset(clampCropOffset(next, geometry));
76
+ }
77
+ async function crop() {
78
+ if (!geometry || !image.current || saving || disabled)
79
+ return;
80
+ setSaving(true);
81
+ setMessage(undefined);
82
+ try {
83
+ const canvas = document.createElement('canvas');
84
+ canvas.width = width;
85
+ canvas.height = Math.max(1, Math.round(width / ratio));
86
+ const context = canvas.getContext('2d');
87
+ if (!context)
88
+ throw new Error('Canvas unavailable');
89
+ context.drawImage(image.current, geometry.x, geometry.y, geometry.width, geometry.height, 0, 0, canvas.width, canvas.height);
90
+ const blob = await new Promise((resolve, reject) => {
91
+ canvas.toBlob((result) => (result ? resolve(result) : reject(new Error('Image export failed'))), outputType, Math.max(0, Math.min(1, quality)));
92
+ });
93
+ await onCrop(blob);
94
+ }
95
+ catch {
96
+ setMessage(es
97
+ ? 'No se pudo recortar la imagen. Comprueba que la URL permita CORS.'
98
+ : 'Could not crop the image. Check that the URL allows CORS.');
99
+ }
100
+ finally {
101
+ setSaving(false);
102
+ }
103
+ }
104
+ const labels = es
105
+ ? {
106
+ region: 'Área de recorte',
107
+ hint: 'Arrastra la imagen o usa las flechas para encuadrarla.',
108
+ zoom: 'Zoom',
109
+ crop: 'Recortar imagen',
110
+ empty: 'Selecciona una imagen para recortar.',
111
+ invalid: 'No se pudo abrir la imagen.',
112
+ }
113
+ : {
114
+ region: 'Crop area',
115
+ hint: 'Drag the image or use the arrow keys to position it.',
116
+ zoom: 'Zoom',
117
+ crop: 'Crop image',
118
+ empty: 'Choose an image to crop.',
119
+ invalid: 'Could not open the image.',
120
+ };
121
+ return (_jsxs("div", { ...props, className: cx('dgm-image-cropper', className), style: style, "data-disabled": disabled || undefined, children: [_jsxs("div", { ref: stage, className: "dgm-image-cropper-stage", style: { '--dgm-crop-ratio': ratio }, role: "group", "aria-label": labels.region, "aria-describedby": `${id}-hint`, tabIndex: imageSize && !disabled ? 0 : -1, "data-dragging": dragging || undefined, onPointerDown: (event) => {
122
+ if (!geometry || disabled || event.button !== 0)
123
+ return;
124
+ event.currentTarget.focus();
125
+ event.currentTarget.setPointerCapture(event.pointerId);
126
+ drag.current = {
127
+ pointerId: event.pointerId,
128
+ x: event.clientX,
129
+ y: event.clientY,
130
+ offsetX: offset.x,
131
+ offsetY: offset.y,
132
+ };
133
+ setDragging(true);
134
+ }, onPointerMove: (event) => {
135
+ if (disabled || !drag.current || drag.current.pointerId !== event.pointerId)
136
+ return;
137
+ move({
138
+ x: drag.current.offsetX + event.clientX - drag.current.x,
139
+ y: drag.current.offsetY + event.clientY - drag.current.y,
140
+ });
141
+ }, onPointerUp: (event) => {
142
+ if (drag.current?.pointerId !== event.pointerId)
143
+ return;
144
+ drag.current = undefined;
145
+ setDragging(false);
146
+ event.currentTarget.releasePointerCapture(event.pointerId);
147
+ }, onPointerCancel: () => {
148
+ drag.current = undefined;
149
+ setDragging(false);
150
+ }, onKeyDown: (event) => {
151
+ if (!geometry || disabled)
152
+ return;
153
+ const step = event.shiftKey ? 1 : 10;
154
+ const delta = {
155
+ ArrowLeft: { x: -step, y: 0 },
156
+ ArrowRight: { x: step, y: 0 },
157
+ ArrowUp: { x: 0, y: -step },
158
+ ArrowDown: { x: 0, y: step },
159
+ }[event.key];
160
+ if (!delta)
161
+ return;
162
+ event.preventDefault();
163
+ move({ x: offset.x + delta.x, y: offset.y + delta.y });
164
+ }, children: [imageUrl ? (_jsx("img", { ref: image, alt: "", crossOrigin: typeof src === 'string' && !src.startsWith('data:') && !src.startsWith('blob:')
165
+ ? 'anonymous'
166
+ : undefined, src: imageUrl, draggable: false, onLoad: (event) => {
167
+ const current = event.currentTarget;
168
+ setImageSize({ width: current.naturalWidth, height: current.naturalHeight });
169
+ setMessage(undefined);
170
+ }, onError: () => {
171
+ setImageSize(undefined);
172
+ setMessage(labels.invalid);
173
+ }, style: geometry
174
+ ? {
175
+ width: imageSize?.width,
176
+ height: imageSize?.height,
177
+ transform: `translate(-50%, -50%) translate(${Math.max(-geometry.maxOffsetX, Math.min(geometry.maxOffsetX, offset.x))}px, ${Math.max(-geometry.maxOffsetY, Math.min(geometry.maxOffsetY, offset.y))}px) scale(${geometry.scale})`,
178
+ }
179
+ : { visibility: 'hidden' } })) : (_jsx("span", { className: "dgm-image-cropper-empty", children: labels.empty })), imageSize && _jsx("span", { className: "dgm-image-cropper-guides", "aria-hidden": "true" })] }), _jsx("p", { id: `${id}-hint`, className: "dgm-description", children: labels.hint }), _jsxs("div", { className: "dgm-image-cropper-controls", children: [_jsx(Slider, { label: labels.zoom, min: 1, max: Math.max(1.01, zoomLimit), step: 0.01, value: zoom, onValueChange: setZoom, formatValue: (value) => `${Math.round(value * 100)}%`, disabled: disabled || !imageSize || zoomLimit === 1 }), _jsx(Button, { onClick: crop, disabled: disabled || !geometry, loading: saving, children: labels.crop })] }), message && (_jsx("p", { className: "dgm-error", role: "alert", children: message }))] }));
180
+ }
package/dist/index.d.ts CHANGED
@@ -30,6 +30,7 @@ export { CheckboxGroup, SwitchGroup, type CheckboxGroupProps, type SwitchGroupPr
30
30
  export { DatePicker, DateRangePicker, type DatePickerProps, type DateRangePickerProps, type DateRangeValue, type DatePickerBaseProps, } from './date-picker.js';
31
31
  export { DataTable, type DataTableProps, type DataColumn, type DataTableSort, } from './data-table.js';
32
32
  export { FileUpload, type FileUploadProps, type FileRejection } from './file-upload.js';
33
+ export { ImageCropper, type ImageCropperProps } from './image-cropper.js';
33
34
  export { CommandPalette, type CommandPaletteProps, type CommandAction } from './command-palette.js';
34
35
  export { Stepper, type StepperProps, type StepItem } from './stepper.js';
35
36
  export { DropdownMenu, type DropdownMenuProps, type DropdownMenuItem } from './dropdown-menu.js';
package/dist/index.js CHANGED
@@ -30,6 +30,7 @@ export { CheckboxGroup, SwitchGroup, } from './choice-group.js';
30
30
  export { DatePicker, DateRangePicker, } from './date-picker.js';
31
31
  export { DataTable, } from './data-table.js';
32
32
  export { FileUpload } from './file-upload.js';
33
+ export { ImageCropper } from './image-cropper.js';
33
34
  export { CommandPalette } from './command-palette.js';
34
35
  export { Stepper } from './stepper.js';
35
36
  export { DropdownMenu } from './dropdown-menu.js';
@@ -0,0 +1,25 @@
1
+ /** Geometría compartida entre el visor y la exportación al canvas. */
2
+ export interface CropGeometry {
3
+ scale: number;
4
+ x: number;
5
+ y: number;
6
+ width: number;
7
+ height: number;
8
+ maxOffsetX: number;
9
+ maxOffsetY: number;
10
+ }
11
+ export declare function clampCropOffset(offset: {
12
+ x: number;
13
+ y: number;
14
+ }, bounds: {
15
+ maxOffsetX: number;
16
+ maxOffsetY: number;
17
+ }): {
18
+ x: number;
19
+ y: number;
20
+ };
21
+ /** El mismo rectángulo gobierna la posición visible y los píxeles exportados. */
22
+ export declare function getCropGeometry(imageWidth: number, imageHeight: number, viewportWidth: number, viewportHeight: number, zoom: number, offset: {
23
+ x: number;
24
+ y: number;
25
+ }): CropGeometry;
@@ -0,0 +1,22 @@
1
+ export function clampCropOffset(offset, bounds) {
2
+ return {
3
+ x: Math.max(-bounds.maxOffsetX, Math.min(bounds.maxOffsetX, offset.x)),
4
+ y: Math.max(-bounds.maxOffsetY, Math.min(bounds.maxOffsetY, offset.y)),
5
+ };
6
+ }
7
+ /** El mismo rectángulo gobierna la posición visible y los píxeles exportados. */
8
+ export function getCropGeometry(imageWidth, imageHeight, viewportWidth, viewportHeight, zoom, offset) {
9
+ const scale = Math.max(viewportWidth / imageWidth, viewportHeight / imageHeight) * zoom;
10
+ const maxOffsetX = Math.max(0, (imageWidth * scale - viewportWidth) / 2);
11
+ const maxOffsetY = Math.max(0, (imageHeight * scale - viewportHeight) / 2);
12
+ const limited = clampCropOffset(offset, { maxOffsetX, maxOffsetY });
13
+ return {
14
+ scale,
15
+ x: (imageWidth * scale - viewportWidth) / (2 * scale) - limited.x / scale,
16
+ y: (imageHeight * scale - viewportHeight) / (2 * scale) - limited.y / scale,
17
+ width: viewportWidth / scale,
18
+ height: viewportHeight / scale,
19
+ maxOffsetX,
20
+ maxOffsetY,
21
+ };
22
+ }
@@ -1,12 +1,23 @@
1
1
  /** La profundidad React atraviesa los portales sin cambiar su destino ni su geometría. */
2
- import { type CSSProperties, type ReactNode } from 'react';
2
+ import { type CSSProperties, type ReactNode, type ReactElement, type RefObject } from 'react';
3
+ /**
4
+ * El bloqueo superior de Radix excluye los portales hermanos de Dialog.Content.
5
+ * Este límite registra el panel y conserva el diálogo como región permitida;
6
+ * no activa el modo modal de Popover, que bloquearía etiquetas y otros controles.
7
+ * forwardProps evita añadir contenedores que alteren la geometría de Popper.
8
+ * La ref llega al DOM para que Presence conserve las animaciones de salida.
9
+ */
10
+ export declare const OverlayScrollBoundary: import("react").ForwardRefExoticComponent<{
11
+ children: ReactElement;
12
+ } & import("react").RefAttributes<HTMLDivElement>>;
3
13
  /** Cada panel pertenece a la siguiente capa del panel que contiene su disparador. */
4
14
  export declare function useOverlayLayer(): {
5
15
  depth: number;
6
16
  style: CSSProperties;
7
17
  };
8
18
  /** Sin contenedor DOM: los portales siguen escapando del overflow y transform del padre. */
9
- export declare function OverlayLayerProvider({ depth, children }: {
19
+ export declare function OverlayLayerProvider({ depth, children, scrollContainer, }: {
10
20
  depth: number;
11
21
  children: ReactNode;
22
+ scrollContainer?: RefObject<HTMLDivElement | null>;
12
23
  }): import("react").JSX.Element;
@@ -1,7 +1,20 @@
1
1
  'use client';
2
2
  import { jsx as _jsx } from "react/jsx-runtime";
3
3
  /** La profundidad React atraviesa los portales sin cambiar su destino ni su geometría. */
4
- import { createContext, useContext } from 'react';
4
+ import { createContext, forwardRef, useContext, } from 'react';
5
+ import { RemoveScroll } from 'react-remove-scroll';
6
+ const OverlayScrollContainer = createContext(undefined);
7
+ /**
8
+ * El bloqueo superior de Radix excluye los portales hermanos de Dialog.Content.
9
+ * Este límite registra el panel y conserva el diálogo como región permitida;
10
+ * no activa el modo modal de Popover, que bloquearía etiquetas y otros controles.
11
+ * forwardProps evita añadir contenedores que alteren la geometría de Popper.
12
+ * La ref llega al DOM para que Presence conserve las animaciones de salida.
13
+ */
14
+ export const OverlayScrollBoundary = forwardRef(function OverlayScrollBoundary({ children }, ref) {
15
+ const container = useContext(OverlayScrollContainer);
16
+ return (_jsx(RemoveScroll, { ref: ref, enabled: !!container, shards: container ? [container] : [], forwardProps: true, allowPinchZoom: true, removeScrollBar: false, children: children }));
17
+ });
5
18
  const OverlayDepth = createContext(-1);
6
19
  /** Cada panel pertenece a la siguiente capa del panel que contiene su disparador. */
7
20
  export function useOverlayLayer() {
@@ -9,6 +22,7 @@ export function useOverlayLayer() {
9
22
  return { depth, style: { '--dgm-layer-depth': depth } };
10
23
  }
11
24
  /** Sin contenedor DOM: los portales siguen escapando del overflow y transform del padre. */
12
- export function OverlayLayerProvider({ depth, children }) {
13
- return _jsx(OverlayDepth.Provider, { value: depth, children: children });
25
+ export function OverlayLayerProvider({ depth, children, scrollContainer, }) {
26
+ const inheritedContainer = useContext(OverlayScrollContainer);
27
+ return (_jsx(OverlayDepth.Provider, { value: depth, children: _jsx(OverlayScrollContainer.Provider, { value: scrollContainer ?? inheritedContainer, children: children }) }));
14
28
  }
package/dist/modal.js CHANGED
@@ -10,9 +10,10 @@ import { cx, hasContent } from './utils.js';
10
10
  /** Portal con cabecera fija y cuerpo desplazable para contenidos largos y pantallas pequeñas. */
11
11
  export function Modal({ open, onOpenChange, title, description, children, footer, closeLabel = 'Close dialog', closeOnOverlayClick = true, className, }) {
12
12
  const { depth, style: layerStyle } = useOverlayLayer();
13
+ const scrollContainer = useRef(null);
13
14
  const returnFocus = useRef(null);
14
15
  const descriptionId = useId();
15
- return (_jsx(OverlayLayerProvider, { depth: depth, children: _jsx(Dialog.Root, { open: open, onOpenChange: onOpenChange, children: _jsxs(Dialog.Portal, { children: [_jsx(Dialog.Overlay, { className: "dgm-modal-overlay", style: layerStyle }), _jsxs(Dialog.Content, { style: layerStyle, className: cx('dgm-modal', className), "aria-describedby": hasContent(description) ? descriptionId : undefined, onOpenAutoFocus: () => {
16
+ return (_jsx(OverlayLayerProvider, { depth: depth, scrollContainer: scrollContainer, children: _jsx(Dialog.Root, { open: open, onOpenChange: onOpenChange, children: _jsxs(Dialog.Portal, { children: [_jsx(Dialog.Overlay, { className: "dgm-modal-overlay", style: layerStyle }), _jsxs(Dialog.Content, { ref: scrollContainer, style: layerStyle, className: cx('dgm-modal', className), "aria-describedby": hasContent(description) ? descriptionId : undefined, onOpenAutoFocus: () => {
16
17
  // Se captura antes de que Radix enfoque el contenido, incluso sin Dialog.Trigger.
17
18
  returnFocus.current =
18
19
  document.activeElement instanceof HTMLElement ? document.activeElement : null;
@@ -4,8 +4,11 @@ import type { ComboboxOption } from './combobox.js';
4
4
  export interface MultiSelectProps {
5
5
  label: ReactNode;
6
6
  options: readonly ComboboxOption[];
7
+ /** IDs seleccionados. Controla esta prop para leer y presentar la selección fuera del selector. */
7
8
  value?: string[];
9
+ /** Selección inicial no controlada; los cambios se comunican mediante onValueChange. */
8
10
  defaultValue?: string[];
11
+ /** Notifica los IDs tras cada cambio, sin imponer cómo se representan externamente. */
9
12
  onValueChange?: (value: string[]) => void;
10
13
  name?: string;
11
14
  required?: boolean;
@@ -7,7 +7,7 @@ import { Button } from './button.js';
7
7
  import { Input } from './fields.js';
8
8
  import { Checkbox } from './toggles.js';
9
9
  import { useControllable } from './internal/state.js';
10
- import { ChevronIcon, CloseIcon } from './internal/icons.js';
10
+ import { ChevronIcon } from './internal/icons.js';
11
11
  import { cx, hasContent } from './utils.js';
12
12
  import { ScrollHints } from './internal/scroll-hints.js';
13
13
  import { useFieldOpen } from './internal/field-open.js';
@@ -56,8 +56,5 @@ export function MultiSelect({ label, options, value, defaultValue = [], onValueC
56
56
  ? [...selected, option.value]
57
57
  : selected.filter((item) => item !== option.value)) }, option.value)))) : (_jsx("p", { role: "status", className: "dgm-description", children: emptyMessage ?? (es ? 'Sin resultados.' : 'No results.') })) }) }), _jsx(Button, { variant: "secondary", fullWidth: true, onClick: () => setOpen(false), children: es ? 'Listo' : 'Done' })] }), children: _jsxs("button", { ref: trigger, type: "button", id: fieldId, disabled: disabled, "aria-describedby": describedBy, "aria-invalid": hasContent(message) || undefined, className: "dgm-input dgm-multi-trigger", children: [_jsx("span", { children: current.length
58
58
  ? `${current.length} ${es ? 'seleccionadas' : 'selected'}`
59
- : (placeholder ?? (es ? 'Seleccionar opciones' : 'Select options')) }), _jsx(ChevronIcon, {})] }) }), current.length > 0 && (_jsx("ul", { className: "dgm-multi-tags", "aria-label": es ? 'Opciones seleccionadas' : 'Selected options', children: current.map((option) => (_jsxs("li", { children: [option.label, _jsx("button", { type: "button", disabled: disabled || option.disabled, "aria-label": `${es ? 'Quitar' : 'Remove'} ${option.label}`, onClick: () => {
60
- update(selected.filter((item) => item !== option.value));
61
- trigger.current?.focus({ preventScroll: true });
62
- }, children: _jsx(CloseIcon, {}) })] }, option.value))) })), hasContent(description) && (_jsx("span", { id: `${fieldId}-description`, className: "dgm-description", children: description })), hasContent(message) && (_jsx("span", { id: `${fieldId}-error`, className: "dgm-error", children: message }))] }));
59
+ : (placeholder ?? (es ? 'Seleccionar opciones' : 'Select options')) }), _jsx(ChevronIcon, {})] }) }), hasContent(description) && (_jsx("span", { id: `${fieldId}-description`, className: "dgm-description", children: description })), hasContent(message) && (_jsx("span", { id: `${fieldId}-error`, className: "dgm-error", children: message }))] }));
63
60
  }
package/dist/popover.js CHANGED
@@ -6,7 +6,7 @@ import * as Primitive from '@radix-ui/react-popover';
6
6
  import { restoreFocus } from './internal/focus.js';
7
7
  import { preventTriggerLabelDismiss } from './internal/trigger-label.js';
8
8
  import { CloseIcon } from './internal/icons.js';
9
- import { OverlayLayerProvider, useOverlayLayer } from './internal/overlay-layer.js';
9
+ import { OverlayLayerProvider, OverlayScrollBoundary, useOverlayLayer, } from './internal/overlay-layer.js';
10
10
  import { cx } from './utils.js';
11
11
  /** El panel no bloquea la página; un clic fuera conserva su destino de foco. */
12
12
  export function Popover({ children, title, content, open, defaultOpen, onOpenChange, side = 'bottom', align = 'start', sideOffset = 8, disabled, closeLabel = 'Close popover', className, }) {
@@ -14,14 +14,14 @@ export function Popover({ children, title, content, open, defaultOpen, onOpenCha
14
14
  const titleId = useId();
15
15
  const trigger = useRef(null);
16
16
  const outside = useRef(false);
17
- return (_jsx(OverlayLayerProvider, { depth: depth, children: _jsxs(Primitive.Root, { open: open, defaultOpen: defaultOpen, onOpenChange: onOpenChange, children: [_jsx(Primitive.Trigger, { asChild: true, ref: trigger, disabled: disabled, children: children }), _jsx(Primitive.Portal, { children: _jsxs(Primitive.Content, { style: layerStyle, side: side, align: align, sideOffset: sideOffset, collisionPadding: 12, "aria-labelledby": titleId, className: cx('dgm-popover', className), onInteractOutside: (event) => {
18
- if (preventTriggerLabelDismiss(event, trigger.current))
19
- return;
20
- outside.current = true;
21
- }, onCloseAutoFocus: (event) => {
22
- event.preventDefault();
23
- if (!outside.current)
24
- restoreFocus(trigger.current);
25
- outside.current = false;
26
- }, children: [_jsx("div", { className: "dgm-popover-heading", id: titleId, children: title }), _jsx(Primitive.Close, { className: "dgm-icon-close", "aria-label": closeLabel, children: _jsx(CloseIcon, {}) }), _jsx("div", { className: "dgm-popover-body", children: content })] }) })] }) }));
17
+ return (_jsx(OverlayLayerProvider, { depth: depth, children: _jsxs(Primitive.Root, { open: open, defaultOpen: defaultOpen, onOpenChange: onOpenChange, children: [_jsx(Primitive.Trigger, { asChild: true, ref: trigger, disabled: disabled, children: children }), _jsx(Primitive.Portal, { children: _jsx(OverlayScrollBoundary, { children: _jsxs(Primitive.Content, { style: layerStyle, side: side, align: align, sideOffset: sideOffset, collisionPadding: 12, "aria-labelledby": titleId, className: cx('dgm-popover', className), onInteractOutside: (event) => {
18
+ if (preventTriggerLabelDismiss(event, trigger.current))
19
+ return;
20
+ outside.current = true;
21
+ }, onCloseAutoFocus: (event) => {
22
+ event.preventDefault();
23
+ if (!outside.current)
24
+ restoreFocus(trigger.current);
25
+ outside.current = false;
26
+ }, children: [_jsx("div", { className: "dgm-popover-heading", id: titleId, children: title }), _jsx(Primitive.Close, { className: "dgm-icon-close", "aria-label": closeLabel, children: _jsx(CloseIcon, {}) }), _jsx("div", { className: "dgm-popover-body", children: content })] }) }) })] }) }));
27
27
  }