@nubitio/ui 1.1.2 → 1.2.1

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/dist/index.mjs CHANGED
@@ -1,7 +1,13 @@
1
- import React, { createContext, forwardRef, useCallback, useContext, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";
1
+ import React, { cloneElement, createContext, forwardRef, isValidElement, useCallback, useContext, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";
2
2
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
3
- import { createPortal } from "react-dom";
3
+ import { Dialog } from "@base-ui/react/dialog";
4
4
  import { useDropzone } from "react-dropzone";
5
+ import { Select } from "@base-ui/react/select";
6
+ import { Button as Button$1, Calendar, CalendarCell, CalendarGrid, CalendarGridBody, CalendarGridHeader, CalendarHeaderCell, CalendarMonthPicker, CalendarYearPicker, ComboBox, ComboBoxStateContext, ComboBoxValue, DateInput, DatePicker as DatePicker$1, DateRangePicker as DateRangePicker$1, DateSegment, Dialog as Dialog$1, Group, Heading, I18nProvider, Input, Label, ListBox, ListBoxItem, Popover as Popover$1, RangeCalendar, Tag, TagGroup, TagList, TimeField } from "react-aria-components";
7
+ import { Menu } from "@base-ui/react/menu";
8
+ import { getLocalTimeZone, parseDate, parseTime, today } from "@internationalized/date";
9
+ import { Popover as Popover$2 } from "@base-ui/react/popover";
10
+ import { Tooltip as Tooltip$1 } from "@base-ui/react/tooltip";
5
11
  //#region packages/ui/Avatar.tsx
6
12
  /**
7
13
  * 8 semantic hues aligned with the Fluent / @nubitio design palette.
@@ -60,32 +66,104 @@ const Avatar = ({ owner = "", size, variant = "md", shape = "circle", alt, class
60
66
  });
61
67
  };
62
68
  //#endregion
69
+ //#region packages/ui/OverlayContainer.tsx
70
+ /** Keeps nested portals within the modal's focus and accessibility boundary. */
71
+ const OverlayContainerContext = createContext(null);
72
+ const useOverlayContainer = () => useContext(OverlayContainerContext);
73
+ //#endregion
74
+ //#region packages/ui/ModalSurface.tsx
75
+ /** Shared modal behavior for centered dialogs and side sheets. */
76
+ function ModalSurface({ open, onClose, children, rootClassName, className, style, scrimClassName, scrimLabel, labelledBy, ariaLabel, role = "dialog", keepMounted = false, restoreFocus = true, closeOnEscape = true, initialFocus, closeOnOutsideClick = true }) {
77
+ const parentContainer = useOverlayContainer();
78
+ const [container, setContainer] = useState(null);
79
+ const returnFocus = useRef(null);
80
+ useLayoutEffect(() => {
81
+ if (!open) return;
82
+ const active = document.activeElement;
83
+ if (active instanceof HTMLElement && !container?.contains(active)) returnFocus.current = active;
84
+ }, [open, container]);
85
+ return /* @__PURE__ */ jsx(Dialog.Root, {
86
+ open,
87
+ disablePointerDismissal: !closeOnOutsideClick,
88
+ onOpenChange: (next, details) => {
89
+ if (!next) {
90
+ if (details.reason === "escape-key" && !closeOnEscape) details.cancel();
91
+ else onClose();
92
+ }
93
+ },
94
+ children: /* @__PURE__ */ jsxs(Dialog.Portal, {
95
+ container: parentContainer ?? void 0,
96
+ keepMounted,
97
+ className: rootClassName,
98
+ "aria-hidden": !open || void 0,
99
+ style: {
100
+ visibility: open ? void 0 : "hidden",
101
+ pointerEvents: open ? void 0 : "none"
102
+ },
103
+ children: [/* @__PURE__ */ jsx(Dialog.Backdrop, {
104
+ forceRender: true,
105
+ className: scrimClassName,
106
+ render: /* @__PURE__ */ jsx("button", {
107
+ type: "button",
108
+ tabIndex: -1,
109
+ "aria-label": scrimLabel
110
+ })
111
+ }), /* @__PURE__ */ jsx(Dialog.Popup, {
112
+ ref: setContainer,
113
+ role,
114
+ "aria-labelledby": labelledBy,
115
+ "aria-label": ariaLabel,
116
+ className,
117
+ style,
118
+ finalFocus: restoreFocus ? () => returnFocus.current ?? true : false,
119
+ initialFocus,
120
+ onKeyDown: (event) => {
121
+ if (event.key === "Escape" && !event.defaultPrevented) {
122
+ event.stopPropagation();
123
+ if (closeOnEscape) onClose();
124
+ }
125
+ },
126
+ children: /* @__PURE__ */ jsx(OverlayContainerContext.Provider, {
127
+ value: container,
128
+ children
129
+ })
130
+ })]
131
+ })
132
+ });
133
+ }
134
+ //#endregion
63
135
  //#region packages/ui/Button.tsx
64
- const cx$5 = (...values) => values.filter(Boolean).join(" ");
65
- const Button = ({ variant = "secondary", size = "md", fullWidth = false, icon, loading = false, className, children, disabled, ...props }) => /* @__PURE__ */ jsxs("button", {
66
- ...props,
67
- type: props.type ?? "button",
68
- disabled: disabled || loading,
69
- "aria-busy": loading || void 0,
70
- className: cx$5("nb-button", `nb-button--${variant}`, size === "sm" && "nb-button--sm", fullWidth && "nb-button--full", className),
71
- children: [loading ? /* @__PURE__ */ jsx("span", {
72
- className: "nb-button-spinner",
73
- "aria-hidden": "true"
74
- }) : icon ? /* @__PURE__ */ jsx("i", {
75
- className: icon,
76
- "aria-hidden": "true"
77
- }) : null, children]
136
+ const cx$2 = (...values) => values.filter(Boolean).join(" ");
137
+ const Button = forwardRef(function Button({ variant = "secondary", size = "md", fullWidth = false, icon, loading = false, className, children, disabled, ...props }, ref) {
138
+ return /* @__PURE__ */ jsxs("button", {
139
+ ...props,
140
+ ref,
141
+ type: props.type ?? "button",
142
+ disabled: disabled || loading,
143
+ "aria-busy": loading || void 0,
144
+ className: cx$2("nb-button", `nb-button--${variant}`, size === "sm" && "nb-button--sm", fullWidth && "nb-button--full", className),
145
+ children: [loading ? /* @__PURE__ */ jsx("span", {
146
+ className: "nb-button-spinner",
147
+ "aria-hidden": "true"
148
+ }) : icon ? /* @__PURE__ */ jsx("i", {
149
+ className: icon,
150
+ "aria-hidden": "true"
151
+ }) : null, children]
152
+ });
78
153
  });
79
- const IconButton = ({ icon, label, variant = "default", className, ...props }) => /* @__PURE__ */ jsx("button", {
80
- ...props,
81
- type: props.type ?? "button",
82
- "aria-label": props["aria-label"] ?? label,
83
- title: props.title ?? label,
84
- className: cx$5("nb-icon-button", variant === "danger" && "nb-icon-button--danger", className),
85
- children: /* @__PURE__ */ jsx("i", {
86
- className: icon,
87
- "aria-hidden": "true"
88
- })
154
+ const IconButton = forwardRef(function IconButton({ icon, label, variant = "default", className, ...props }, ref) {
155
+ return /* @__PURE__ */ jsx("button", {
156
+ ...props,
157
+ ref,
158
+ type: props.type ?? "button",
159
+ "aria-label": props["aria-label"] ?? label,
160
+ title: props.title ?? label,
161
+ className: cx$2("nb-icon-button", variant === "danger" && "nb-icon-button--danger", className),
162
+ children: /* @__PURE__ */ jsx("i", {
163
+ className: icon,
164
+ "aria-hidden": "true"
165
+ })
166
+ });
89
167
  });
90
168
  //#endregion
91
169
  //#region packages/ui/UiStrings.tsx
@@ -98,6 +176,9 @@ const EN_UI_STRINGS = {
98
176
  openCalendar: "Open calendar",
99
177
  selectDate: "Select date",
100
178
  selectDateRange: "Select date range",
179
+ startDate: "Start date",
180
+ endDate: "End date",
181
+ selectTime: "Select time",
101
182
  previousMonth: "Previous month",
102
183
  nextMonth: "Next month",
103
184
  previousYear: "Previous year",
@@ -105,6 +186,16 @@ const EN_UI_STRINGS = {
105
186
  selectMonthAndYear: "Select month and year",
106
187
  selectYear: "Select year",
107
188
  clear: "Clear",
189
+ openOptions: "Open options",
190
+ noOptions: "No options found",
191
+ searching: "Searching…",
192
+ searchFailed: "Could not load options",
193
+ enterSearch: "Type to search",
194
+ loadingMore: "Loading more…",
195
+ loadMore: "Load more",
196
+ retrySearch: "Retry search",
197
+ selectedOptions: "Selected options",
198
+ removeOption: "Remove",
108
199
  today: "Today",
109
200
  cancel: "Cancel",
110
201
  confirm: "Confirm",
@@ -157,6 +248,9 @@ const ES_UI_STRINGS = {
157
248
  openCalendar: "Abrir calendario",
158
249
  selectDate: "Seleccionar fecha",
159
250
  selectDateRange: "Seleccionar rango de fechas",
251
+ startDate: "Fecha inicio",
252
+ endDate: "Fecha fin",
253
+ selectTime: "Seleccionar hora",
160
254
  previousMonth: "Mes anterior",
161
255
  nextMonth: "Mes siguiente",
162
256
  previousYear: "Año anterior",
@@ -164,6 +258,16 @@ const ES_UI_STRINGS = {
164
258
  selectMonthAndYear: "Seleccionar mes y año",
165
259
  selectYear: "Seleccionar año",
166
260
  clear: "Limpiar",
261
+ openOptions: "Abrir opciones",
262
+ noOptions: "No se encontraron opciones",
263
+ searching: "Buscando…",
264
+ searchFailed: "No se pudieron cargar las opciones",
265
+ enterSearch: "Escribe para buscar",
266
+ loadingMore: "Cargando más…",
267
+ loadMore: "Cargar más",
268
+ retrySearch: "Reintentar búsqueda",
269
+ selectedOptions: "Opciones seleccionadas",
270
+ removeOption: "Quitar",
167
271
  today: "Hoy",
168
272
  cancel: "Cancelar",
169
273
  confirm: "Confirmar",
@@ -226,103 +330,61 @@ const formatSize = (value) => {
226
330
  return typeof value === "number" ? `${value}px` : value;
227
331
  };
228
332
  const joinClassNames = (...values) => values.filter(Boolean).join(" ");
229
- const AppDialog = ({ visible, open, title, onClose, children, footer, width, maxWidth, height, fullScreen = false, showCloseButton = true, closeLabel, scrimLabel, closeOnOutsideClick = true, closeOnEscape = true, restoreFocus = true, keepMounted = false, rootClassName, className, headerClassName, titleClassName, bodyClassName, footerClassName, role = "dialog" }) => {
333
+ const AppDialog = ({ visible, open, title, onClose, children, footer, width, maxWidth, height, fullScreen = false, showCloseButton = true, closeLabel, scrimLabel, closeOnOutsideClick = true, closeOnEscape = true, restoreFocus = true, keepMounted = false, initialFocus, rootClassName, className, headerClassName, titleClassName, bodyClassName, footerClassName, role = "dialog" }) => {
230
334
  const strings = useUiStrings();
231
335
  const resolvedCloseLabel = closeLabel ?? strings.close;
232
336
  const resolvedScrimLabel = scrimLabel ?? strings.closeDialog;
233
337
  const isVisible = visible ?? open ?? false;
234
338
  const titleId = useId();
235
- const dialogRef = useRef(null);
236
- const lastFocusedElementRef = useRef(null);
237
- const restoreFocusRef = useRef(restoreFocus);
238
- useEffect(() => {
239
- restoreFocusRef.current = restoreFocus;
240
- }, [restoreFocus]);
241
- useEffect(() => {
242
- if (!isVisible) return;
243
- lastFocusedElementRef.current = document.activeElement;
244
- window.setTimeout(() => {
245
- (dialogRef.current?.querySelector("button:not(:disabled), [href], input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex=\"-1\"])"))?.focus();
246
- });
247
- return () => {
248
- if (restoreFocusRef.current) lastFocusedElementRef.current?.focus?.();
249
- };
250
- }, [isVisible]);
251
- useEffect(() => {
252
- if (!isVisible || !closeOnEscape) return;
253
- const handleKeyDown = (event) => {
254
- if (event.key === "Escape") {
255
- event.preventDefault();
256
- onClose();
257
- }
258
- };
259
- document.addEventListener("keydown", handleKeyDown);
260
- return () => document.removeEventListener("keydown", handleKeyDown);
261
- }, [
262
- closeOnEscape,
339
+ return /* @__PURE__ */ jsxs(ModalSurface, {
340
+ open: isVisible,
263
341
  onClose,
264
- isVisible
265
- ]);
266
- if (!isVisible && !keepMounted) return null;
267
- return createPortal(/* @__PURE__ */ jsxs("div", {
268
- className: joinClassNames("nb-dialog-root", rootClassName),
269
- "aria-hidden": !isVisible,
342
+ rootClassName: joinClassNames("nb-dialog-root", rootClassName),
343
+ className: joinClassNames("nb-dialog", fullScreen && "nb-dialog--fullscreen", className),
344
+ scrimClassName: "nb-dialog__scrim",
345
+ scrimLabel: resolvedScrimLabel,
346
+ labelledBy: titleId,
347
+ role,
348
+ closeOnEscape,
349
+ closeOnOutsideClick,
350
+ restoreFocus,
351
+ keepMounted,
352
+ initialFocus,
270
353
  style: {
271
- pointerEvents: isVisible ? void 0 : "none",
272
- visibility: isVisible ? void 0 : "hidden"
354
+ width: formatSize(width),
355
+ maxWidth: formatSize(maxWidth),
356
+ height: formatSize(height)
273
357
  },
274
- children: [/* @__PURE__ */ jsx("button", {
275
- className: "nb-dialog__scrim",
276
- type: "button",
277
- "aria-label": resolvedScrimLabel,
278
- onClick: closeOnOutsideClick ? onClose : void 0
279
- }), /* @__PURE__ */ jsxs("div", {
280
- className: joinClassNames("nb-dialog", fullScreen && "nb-dialog--fullscreen", className),
281
- role,
282
- "aria-modal": "true",
283
- "aria-labelledby": titleId,
284
- ref: dialogRef,
285
- onKeyDownCapture: (event) => {
286
- if (!closeOnEscape && event.key === "Escape") {
287
- event.preventDefault();
288
- event.stopPropagation();
289
- }
290
- },
291
- style: {
292
- width: formatSize(width),
293
- maxWidth: formatSize(maxWidth),
294
- height: formatSize(height)
295
- },
296
- children: [
297
- /* @__PURE__ */ jsxs("div", {
298
- className: joinClassNames("nb-dialog__header", headerClassName),
299
- children: [/* @__PURE__ */ jsx("h2", {
300
- className: joinClassNames("nb-dialog__title", titleClassName),
301
- id: titleId,
302
- children: title
303
- }), showCloseButton && /* @__PURE__ */ jsx(IconButton, {
304
- className: "nb-dialog__close",
305
- icon: "ph ph-x",
306
- label: resolvedCloseLabel,
307
- onClick: onClose
308
- })]
309
- }),
310
- /* @__PURE__ */ jsx("div", {
311
- className: joinClassNames("nb-dialog__body", bodyClassName),
312
- children
313
- }),
314
- footer && /* @__PURE__ */ jsx("div", {
315
- className: joinClassNames("nb-dialog__footer", footerClassName),
316
- children: footer
317
- })
318
- ]
319
- })]
320
- }), document.body);
358
+ children: [
359
+ /* @__PURE__ */ jsxs("div", {
360
+ className: joinClassNames("nb-dialog__header", headerClassName),
361
+ children: [/* @__PURE__ */ jsx("h2", {
362
+ className: joinClassNames("nb-dialog__title", titleClassName),
363
+ id: titleId,
364
+ children: title
365
+ }), showCloseButton && /* @__PURE__ */ jsx(IconButton, {
366
+ className: "nb-dialog__close",
367
+ icon: "ph ph-x",
368
+ label: resolvedCloseLabel,
369
+ onClick: onClose
370
+ })]
371
+ }),
372
+ /* @__PURE__ */ jsx("div", {
373
+ className: joinClassNames("nb-dialog__body", bodyClassName),
374
+ children
375
+ }),
376
+ footer && /* @__PURE__ */ jsx("div", {
377
+ className: joinClassNames("nb-dialog__footer", footerClassName),
378
+ children: footer
379
+ })
380
+ ]
381
+ });
321
382
  };
322
383
  //#endregion
323
384
  //#region packages/ui/ConfirmDialog.tsx
324
385
  function ConfirmDialog({ open, title, message, onConfirm, onCancel, confirmLabel, cancelLabel, variant = "warning" }) {
325
386
  const strings = useUiStrings();
387
+ const cancelRef = useRef(null);
326
388
  const resolvedConfirmLabel = confirmLabel ?? strings.confirm;
327
389
  const resolvedCancelLabel = cancelLabel ?? strings.cancel;
328
390
  return /* @__PURE__ */ jsx(AppDialog, {
@@ -331,10 +393,11 @@ function ConfirmDialog({ open, title, message, onConfirm, onCancel, confirmLabel
331
393
  onClose: onCancel,
332
394
  maxWidth: 420,
333
395
  role: "alertdialog",
396
+ initialFocus: cancelRef,
334
397
  footer: /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(Button, {
335
398
  variant: "secondary",
336
399
  onClick: onCancel,
337
- autoFocus: true,
400
+ ref: cancelRef,
338
401
  children: resolvedCancelLabel
339
402
  }), /* @__PURE__ */ jsx(Button, {
340
403
  variant: variant === "danger" ? "danger" : "primary",
@@ -420,10 +483,10 @@ const Card = ({ title, description, variant = "auth", className, children }) =>
420
483
  };
421
484
  //#endregion
422
485
  //#region packages/ui/FormControls.tsx
423
- const cx$4 = (...values) => values.filter(Boolean).join(" ");
486
+ const cx$1 = (...values) => values.filter(Boolean).join(" ");
424
487
  const FormField = ({ label, error, helpText, children, className, ...props }) => /* @__PURE__ */ jsxs("label", {
425
488
  ...props,
426
- className: cx$4("nb-form-field", !!error && "nb-form-field--error", className),
489
+ className: cx$1("nb-form-field", !!error && "nb-form-field--error", className),
427
490
  children: [
428
491
  label && /* @__PURE__ */ jsx("span", {
429
492
  className: "nb-form-field__label",
@@ -444,14 +507,14 @@ const TextField = forwardRef(function TextField({ className, invalid, ...props }
444
507
  return /* @__PURE__ */ jsx("input", {
445
508
  ...props,
446
509
  ref,
447
- className: cx$4("nb-input", invalid && "nb-input--invalid", className)
510
+ className: cx$1("nb-input", invalid && "nb-input--invalid", className)
448
511
  });
449
512
  });
450
513
  const SelectField = forwardRef(function SelectField({ className, invalid, children, ...props }, ref) {
451
514
  return /* @__PURE__ */ jsx("select", {
452
515
  ...props,
453
516
  ref,
454
- className: cx$4("nb-input", "nb-select", invalid && "nb-input--invalid", className),
517
+ className: cx$1("nb-input", "nb-select", invalid && "nb-input--invalid", className),
455
518
  children
456
519
  });
457
520
  });
@@ -459,12 +522,12 @@ const TextAreaField = forwardRef(function TextAreaField({ className, invalid, ..
459
522
  return /* @__PURE__ */ jsx("textarea", {
460
523
  ...props,
461
524
  ref,
462
- className: cx$4("nb-input", "nb-textarea", invalid && "nb-input--invalid", className)
525
+ className: cx$1("nb-input", "nb-textarea", invalid && "nb-input--invalid", className)
463
526
  });
464
527
  });
465
528
  //#endregion
466
529
  //#region packages/ui/FileDropzone.tsx
467
- function cx$3(...values) {
530
+ function cx(...values) {
468
531
  return values.filter(Boolean).join(" ");
469
532
  }
470
533
  function buildDropzoneAccept(accept) {
@@ -509,10 +572,10 @@ function FileDropzone({ accept, value = null, image = false, disabled = false, r
509
572
  const placeholderTitle = isDragActive ? labels?.dropPrompt ?? "Drop file here" : image ? labels?.imagePrompt ?? "Drop image here or click to browse" : labels?.prompt ?? "Drop file here or click to browse";
510
573
  const placeholderHint = image ? labels?.imageHint ?? "PNG, JPG, WebP or GIF" : labels?.hint ?? "Select one file";
511
574
  return /* @__PURE__ */ jsxs("div", {
512
- className: cx$3("nb-file-dropzone", image && "nb-file-dropzone--image", invalid && "nb-file-dropzone--invalid", className),
575
+ className: cx("nb-file-dropzone", image && "nb-file-dropzone--image", invalid && "nb-file-dropzone--invalid", className),
513
576
  children: [/* @__PURE__ */ jsxs("div", {
514
- ...getRootProps({ className: cx$3("nb-file-dropzone__zone", isDragActive && "nb-file-dropzone__zone--active", hasContent && "nb-file-dropzone__zone--filled", uploading && "nb-file-dropzone__zone--uploading", !isInteractive && "nb-file-dropzone__zone--disabled") }),
515
- children: [/* @__PURE__ */ jsx("input", { ...getInputProps({
577
+ ...getRootProps({ className: cx("nb-file-dropzone__zone", isDragActive && "nb-file-dropzone__zone--active", hasContent && "nb-file-dropzone__zone--filled", uploading && "nb-file-dropzone__zone--uploading", disabled && "nb-file-dropzone__zone--disabled", readOnly && "nb-file-dropzone__zone--readonly") }),
578
+ children: [!readOnly && /* @__PURE__ */ jsx("input", { ...getInputProps({
516
579
  id: inputId,
517
580
  "aria-label": inputLabel
518
581
  }) }), hasContent ? /* @__PURE__ */ jsxs(Fragment, { children: [
@@ -585,9 +648,9 @@ function FileDropzone({ accept, value = null, image = false, disabled = false, r
585
648
  }),
586
649
  /* @__PURE__ */ jsx("span", {
587
650
  className: "nb-file-dropzone__title",
588
- children: placeholderTitle
651
+ children: readOnly ? labels?.empty ?? (image ? "No image" : "No file") : placeholderTitle
589
652
  }),
590
- /* @__PURE__ */ jsx("span", {
653
+ !readOnly && /* @__PURE__ */ jsx("span", {
591
654
  className: "nb-file-dropzone__hint",
592
655
  children: placeholderHint
593
656
  })
@@ -604,390 +667,550 @@ function FileDropzone({ accept, value = null, image = false, disabled = false, r
604
667
  });
605
668
  }
606
669
  //#endregion
607
- //#region packages/ui/useFloatingPanel.ts
608
- /** Style applied to an anchored panel before its first position is computed. */
609
- const HIDDEN_PANEL_STYLE = {
610
- position: "fixed",
611
- visibility: "hidden",
612
- margin: 0
613
- };
614
- /**
615
- * Fixed-position style for a panel anchored to an element, clamped to the
616
- * viewport with an 8px gutter and flipped above the anchor when it fits
617
- * better there.
618
- */
619
- function computeAnchoredStyle(anchor, options = {}) {
620
- if (!anchor) return HIDDEN_PANEL_STYLE;
621
- const { align = "start", minWidth = 0, matchAnchorWidth = false, offset = 4, flipThreshold = 250, zIndex = 9999 } = options;
622
- const rect = anchor.getBoundingClientRect();
623
- const width = Math.max(matchAnchorWidth ? rect.width : 0, minWidth);
624
- const left = align === "end" ? Math.max(8, Math.min(rect.right - width, window.innerWidth - width - 8)) : Math.max(8, Math.min(rect.left, window.innerWidth - width - 8));
625
- const spaceBelow = window.innerHeight - rect.bottom;
626
- if (spaceBelow < flipThreshold && rect.top > spaceBelow) return {
627
- position: "fixed",
628
- left: `${left}px`,
629
- width: `${width}px`,
630
- bottom: `${window.innerHeight - rect.top + offset}px`,
631
- top: "auto",
632
- margin: 0,
633
- zIndex,
634
- visibility: "visible"
635
- };
636
- return {
637
- position: "fixed",
638
- left: `${left}px`,
639
- width: `${width}px`,
640
- top: `${rect.bottom + offset}px`,
641
- bottom: "auto",
642
- margin: 0,
643
- zIndex,
644
- visibility: "visible"
645
- };
646
- }
647
- function useFloatingPanel(options = {}) {
648
- const [open, setOpenState] = useState(false);
649
- const [panelStyle, setPanelStyle] = useState(HIDDEN_PANEL_STYLE);
650
- const containerRef = useRef(null);
651
- const panelRef = useRef(null);
652
- const optionsRef = useRef(options);
653
- optionsRef.current = options;
654
- const anchored = !!options.computeStyle;
655
- const dismissEvent = options.dismissEvent ?? "pointerdown";
656
- const setOpen = useCallback((next) => {
657
- setOpenState(next);
658
- if (!next) optionsRef.current.onClose?.();
659
- optionsRef.current.onOpenChange?.(next);
660
- }, []);
661
- const applyStyle = useCallback(() => {
662
- const compute = optionsRef.current.computeStyle;
663
- if (!compute) return;
664
- const style = compute(containerRef.current);
665
- if (style) setPanelStyle(style);
666
- }, []);
667
- const openPanel = useCallback(() => {
668
- applyStyle();
669
- setOpen(true);
670
- }, [applyStyle, setOpen]);
671
- const toggle = useCallback(() => open ? setOpen(false) : openPanel(), [
670
+ //#region packages/ui/AppDropdown.tsx
671
+ function AppDropdown({ id: idProp, ariaLabel, label, icon, value, options, onChange, disabled = false, placeholder = "Seleccionar…", variant = "form", className, showFieldLabel = variant === "form", menuMinWidth, error, helpText, menuHeader, menuFooter, onOpenChange }) {
672
+ const generatedId = useId();
673
+ const id = idProp ?? generatedId;
674
+ const container = useOverlayContainer();
675
+ const [open, setOpen] = useState(false);
676
+ const selected = options.find((option) => option.value === value);
677
+ const labelled = !!label && (showFieldLabel || variant === "toolbar");
678
+ const message = error ?? helpText;
679
+ const iconClass = icon?.startsWith("ph ") ? icon : icon?.startsWith("ph-") ? `ph ${icon}` : `ph ph-${icon}`;
680
+ return /* @__PURE__ */ jsx(Select.Root, {
681
+ value,
682
+ onValueChange: (next) => {
683
+ if (next !== null) onChange(next);
684
+ },
685
+ disabled,
672
686
  open,
673
- openPanel,
674
- setOpen
675
- ]);
687
+ onOpenChange: (next) => {
688
+ setOpen(next);
689
+ onOpenChange?.(next);
690
+ },
691
+ modal: false,
692
+ children: /* @__PURE__ */ jsxs("div", {
693
+ className: showFieldLabel && variant !== "toolbar" ? "nb-form-field" : void 0,
694
+ children: [
695
+ showFieldLabel && variant !== "toolbar" && label && /* @__PURE__ */ jsx("label", {
696
+ className: "nb-form-field__label",
697
+ id: `${id}-label`,
698
+ htmlFor: id,
699
+ children: label
700
+ }),
701
+ /* @__PURE__ */ jsxs("div", {
702
+ className: [
703
+ "nb-dropdown",
704
+ `nb-dropdown--${variant}`,
705
+ open && "nb-dropdown--open",
706
+ disabled && "nb-dropdown--disabled",
707
+ className
708
+ ].filter(Boolean).join(" "),
709
+ children: [
710
+ variant === "toolbar" && label && /* @__PURE__ */ jsxs("span", {
711
+ className: "nb-dropdown__toolbar-label",
712
+ id: `${id}-label`,
713
+ children: [icon && /* @__PURE__ */ jsx("i", {
714
+ className: iconClass,
715
+ "aria-hidden": "true"
716
+ }), /* @__PURE__ */ jsx("span", { children: label })]
717
+ }),
718
+ /* @__PURE__ */ jsxs(Select.Trigger, {
719
+ id,
720
+ className: "nb-dropdown__trigger",
721
+ onKeyDownCapture: (event) => {
722
+ if (open && event.key === "Escape") {
723
+ event.preventDefault();
724
+ event.stopPropagation();
725
+ setOpen(false);
726
+ onOpenChange?.(false);
727
+ }
728
+ },
729
+ "aria-label": ariaLabel,
730
+ "aria-labelledby": ariaLabel ? void 0 : labelled ? `${id}-label ${id}-value` : `${id}-value`,
731
+ "aria-describedby": message ? `${id}-message` : void 0,
732
+ "aria-invalid": !!error || void 0,
733
+ children: [/* @__PURE__ */ jsx("span", {
734
+ className: "nb-dropdown__value",
735
+ id: `${id}-value`,
736
+ children: selected?.selectedLabel ?? selected?.label ?? placeholder
737
+ }), /* @__PURE__ */ jsx("i", {
738
+ className: "ph ph-caret-down nb-dropdown__caret",
739
+ "aria-hidden": "true"
740
+ })]
741
+ }),
742
+ /* @__PURE__ */ jsx(Select.Portal, {
743
+ container: container ?? void 0,
744
+ children: /* @__PURE__ */ jsx(Select.Positioner, {
745
+ align: "start",
746
+ sideOffset: 4,
747
+ alignItemWithTrigger: false,
748
+ className: "nb-dropdown-positioner",
749
+ style: { minWidth: menuMinWidth },
750
+ children: /* @__PURE__ */ jsxs(Select.Popup, {
751
+ onKeyDownCapture: (event) => {
752
+ if (event.key === "Escape") {
753
+ event.preventDefault();
754
+ event.stopPropagation();
755
+ setOpen(false);
756
+ onOpenChange?.(false);
757
+ }
758
+ },
759
+ className: `nb-dropdown__menu nb-dropdown__menu--${variant}`,
760
+ children: [
761
+ menuHeader,
762
+ /* @__PURE__ */ jsx(Select.List, {
763
+ className: "nb-dropdown__menu-list",
764
+ children: options.map((option) => /* @__PURE__ */ jsxs(Select.Item, {
765
+ value: option.value,
766
+ label: option.label,
767
+ disabled: option.disabled,
768
+ className: ({ selected }) => `nb-dropdown__option${selected ? " nb-dropdown__option--active" : ""}`,
769
+ children: [/* @__PURE__ */ jsxs(Select.ItemText, {
770
+ className: "nb-dropdown__option-content",
771
+ children: [option.iconText && /* @__PURE__ */ jsx("span", {
772
+ className: "nb-dropdown__option-icon",
773
+ "aria-hidden": "true",
774
+ children: option.iconText
775
+ }), /* @__PURE__ */ jsx("span", { children: option.label })]
776
+ }), /* @__PURE__ */ jsx(Select.ItemIndicator, {
777
+ className: "nb-dropdown__selected",
778
+ "aria-hidden": "true",
779
+ children: /* @__PURE__ */ jsx("i", { className: "ph ph-check" })
780
+ })]
781
+ }, option.value))
782
+ }),
783
+ menuFooter
784
+ ]
785
+ })
786
+ })
787
+ })
788
+ ]
789
+ }),
790
+ message && /* @__PURE__ */ jsx("span", {
791
+ id: `${id}-message`,
792
+ className: error ? "nb-form-field__error" : "nb-form-field__help",
793
+ role: error ? "alert" : void 0,
794
+ children: message
795
+ })
796
+ ]
797
+ })
798
+ });
799
+ }
800
+ //#endregion
801
+ //#region packages/ui/useComboboxOptions.ts
802
+ function mergeOptions(...groups) {
803
+ const map = /* @__PURE__ */ new Map();
804
+ for (const group of groups) for (const option of group) map.set(option.value, option);
805
+ return [...map.values()];
806
+ }
807
+ function useComboboxOptions({ options, selected, loadOptions, open, query, debounceMs, minSearchLength }) {
808
+ const [state, setState] = useState({
809
+ query: "",
810
+ options: [],
811
+ known: [],
812
+ loading: false,
813
+ failed: false
814
+ });
815
+ const [revision, setRevision] = useState(0);
816
+ const generation = useRef(0);
817
+ const request = useRef(null);
818
+ const normalizedQuery = query.trim();
819
+ const eligible = normalizedQuery.length >= minSearchLength;
676
820
  useEffect(() => {
677
- if (!open) return;
678
- const handleOutside = (e) => {
679
- const target = e.target;
680
- if (containerRef.current?.contains(target) || panelRef.current?.contains(target)) return;
681
- setOpen(false);
682
- };
683
- const handleKeyDown = (e) => {
684
- if (e.key !== "Escape") return;
685
- setOpen(false);
686
- optionsRef.current.onEscape?.(e);
687
- };
688
- document.addEventListener(dismissEvent, handleOutside);
689
- document.addEventListener("keydown", handleKeyDown);
821
+ const currentGeneration = ++generation.current;
822
+ request.current?.abort();
823
+ request.current = null;
824
+ if (!loadOptions || !open || !eligible) return;
825
+ const controller = new AbortController();
826
+ request.current = controller;
827
+ const timer = setTimeout(async () => {
828
+ setState((previous) => ({
829
+ loader: loadOptions,
830
+ query: normalizedQuery,
831
+ options: [],
832
+ known: previous.loader === loadOptions ? previous.known : [],
833
+ loading: true,
834
+ failed: false
835
+ }));
836
+ try {
837
+ const page = await loadOptions(normalizedQuery, { signal: controller.signal });
838
+ if (controller.signal.aborted || generation.current !== currentGeneration) return;
839
+ setState((previous) => ({
840
+ loader: loadOptions,
841
+ query: normalizedQuery,
842
+ options: mergeOptions(page.options),
843
+ known: mergeOptions(previous.known, page.options),
844
+ nextCursor: page.nextCursor,
845
+ loading: false,
846
+ failed: false
847
+ }));
848
+ } catch {
849
+ if (controller.signal.aborted || generation.current !== currentGeneration) return;
850
+ setState((previous) => ({
851
+ ...previous,
852
+ loading: false,
853
+ failed: true
854
+ }));
855
+ } finally {
856
+ if (request.current === controller) request.current = null;
857
+ }
858
+ }, Math.max(0, debounceMs));
690
859
  return () => {
691
- document.removeEventListener(dismissEvent, handleOutside);
692
- document.removeEventListener("keydown", handleKeyDown);
860
+ clearTimeout(timer);
861
+ controller.abort();
693
862
  };
694
863
  }, [
695
- dismissEvent,
864
+ loadOptions,
696
865
  open,
697
- setOpen
866
+ normalizedQuery,
867
+ eligible,
868
+ debounceMs,
869
+ revision
698
870
  ]);
699
- useLayoutEffect(() => {
700
- if (!open || !anchored) return;
701
- const update = () => {
702
- const container = containerRef.current;
703
- if (!container) return;
704
- if (optionsRef.current.closeOnViewportExit) {
705
- const rect = container.getBoundingClientRect();
706
- if ((rect.width > 0 || rect.height > 0) && (rect.top >= window.innerHeight || rect.bottom <= 0)) {
707
- setOpen(false);
708
- return;
709
- }
710
- }
711
- applyStyle();
712
- };
713
- update();
714
- window.addEventListener("resize", update);
715
- window.addEventListener("scroll", update, {
716
- capture: true,
717
- passive: true
718
- });
719
- return () => {
720
- window.removeEventListener("resize", update);
721
- window.removeEventListener("scroll", update, { capture: true });
722
- };
871
+ const current = state.loader === loadOptions && state.query === normalizedQuery;
872
+ const loading = !!loadOptions && open && eligible && (!current || state.loading);
873
+ const failed = !!loadOptions && open && current && state.failed;
874
+ const known = mergeOptions(options, state.loader === loadOptions ? state.known : []);
875
+ const pinned = known.filter((option) => selected.includes(option.value));
876
+ const items = loadOptions ? mergeOptions(pinned, current && eligible ? state.options : []) : options;
877
+ const loadMore = useCallback(async () => {
878
+ if (!loadOptions || !open || !current || state.loading || request.current || state.nextCursor == null || !eligible) return;
879
+ const controller = new AbortController();
880
+ const currentGeneration = generation.current;
881
+ request.current = controller;
882
+ setState((previous) => ({
883
+ ...previous,
884
+ loading: true,
885
+ failed: false
886
+ }));
887
+ try {
888
+ const page = await loadOptions(normalizedQuery, {
889
+ signal: controller.signal,
890
+ cursor: state.nextCursor
891
+ });
892
+ if (controller.signal.aborted || currentGeneration !== generation.current) return;
893
+ setState((previous) => ({
894
+ ...previous,
895
+ options: mergeOptions(previous.options, page.options),
896
+ known: mergeOptions(previous.known, page.options),
897
+ nextCursor: page.nextCursor,
898
+ loading: false,
899
+ failed: false
900
+ }));
901
+ } catch {
902
+ if (controller.signal.aborted || currentGeneration !== generation.current) return;
903
+ setState((previous) => ({
904
+ ...previous,
905
+ loading: false,
906
+ failed: true
907
+ }));
908
+ } finally {
909
+ if (request.current === controller) request.current = null;
910
+ }
723
911
  }, [
724
- anchored,
725
- applyStyle,
912
+ loadOptions,
726
913
  open,
727
- setOpen
914
+ current,
915
+ state.loading,
916
+ state.nextCursor,
917
+ eligible,
918
+ normalizedQuery
728
919
  ]);
729
- return {
920
+ useEffect(() => () => {
921
+ request.current?.abort();
922
+ }, [
730
923
  open,
731
- setOpen,
732
- toggle,
733
- openPanel,
734
- containerRef,
735
- panelRef,
736
- panelStyle
924
+ normalizedQuery,
925
+ loadOptions
926
+ ]);
927
+ return {
928
+ items,
929
+ known,
930
+ loading,
931
+ failed,
932
+ eligible,
933
+ hasMore: !!loadOptions && open && eligible && current && state.nextCursor != null,
934
+ loadMore,
935
+ retry: () => setRevision((previous) => previous + 1)
737
936
  };
738
937
  }
739
938
  //#endregion
740
- //#region packages/ui/AppDropdown.tsx
741
- function cx$2(...values) {
742
- return values.filter(Boolean).join(" ");
743
- }
744
- function normalizeIcon$2(icon) {
745
- if (!icon) return void 0;
746
- if (icon.startsWith("ph ")) return icon;
747
- if (icon.startsWith("ph-")) return `ph ${icon}`;
748
- return `ph ph-${icon}`;
749
- }
750
- function AppDropdown({ id: idProp, label, icon, value, options, onChange, disabled = false, placeholder = "Seleccionar…", variant = "form", className, showFieldLabel = variant === "form", menuMinWidth, error, helpText, menuHeader, menuFooter, onOpenChange }) {
751
- const generatedId = useId();
752
- const id = idProp ?? generatedId;
753
- const { open, setOpen: setMenuOpen, openPanel: openMenu, containerRef, panelRef: menuRef, panelStyle: menuStyle } = useFloatingPanel({
754
- onOpenChange,
755
- dismissEvent: "mousedown",
756
- closeOnViewportExit: true,
757
- computeStyle: (container) => {
758
- return computeAnchoredStyle(container?.querySelector(".nb-dropdown__trigger") ?? container, {
759
- matchAnchorWidth: true,
760
- minWidth: menuMinWidth ?? 72
761
- });
762
- }
939
+ //#region packages/ui/Combobox.tsx
940
+ const Combobox = forwardRef(function Combobox(props, ref) {
941
+ return /* @__PURE__ */ jsx(SelectionCombobox, {
942
+ ...props,
943
+ inputRef: ref,
944
+ multiple: false,
945
+ onChange: (value) => props.onChange(typeof value === "string" ? value : null)
763
946
  });
764
- const selected = options.find((option) => option.value === value);
765
- const control = /* @__PURE__ */ jsxs("div", {
766
- ref: containerRef,
767
- className: cx$2("nb-dropdown", `nb-dropdown--${variant}`, open && "nb-dropdown--open", disabled && "nb-dropdown--disabled", className),
768
- role: "group",
769
- "aria-labelledby": label ? `${id}-label` : void 0,
947
+ });
948
+ const MultiSelect = forwardRef(function MultiSelect(props, ref) {
949
+ return /* @__PURE__ */ jsx(SelectionCombobox, {
950
+ ...props,
951
+ inputRef: ref,
952
+ multiple: true,
953
+ onChange: (value) => props.onChange(Array.isArray(value) ? value : [])
954
+ });
955
+ });
956
+ function SelectionCombobox({ options, value, onChange, label, error, helpText, invalid = false, clearable = true, emptyMessage, openLabel, clearLabel, id, name, disabled, readOnly, required, form, className, inputClassName, "aria-describedby": describedBy, loadOptions, debounceMs = 250, minSearchLength = 0, loadingMessage, searchErrorMessage, onOpenChange, multiple, inputRef, selectedLabel, removeLabel, ...inputProps }) {
957
+ const overlayContainer = useOverlayContainer();
958
+ const generatedId = useId();
959
+ const inputId = id ?? generatedId;
960
+ const strings = useUiStrings();
961
+ const [open, setOpen] = useState(false);
962
+ const [query, setQuery] = useState("");
963
+ const selected = Array.isArray(value) ? value : value === null ? [] : [value];
964
+ const remote = useComboboxOptions({
965
+ options,
966
+ selected,
967
+ loadOptions,
968
+ open: open && !disabled && !readOnly,
969
+ query,
970
+ debounceMs,
971
+ minSearchLength
972
+ });
973
+ const message = error ?? helpText;
974
+ const messageId = `${inputId}-message`;
975
+ const description = [describedBy, message ? messageId : void 0].filter(Boolean).join(" ") || void 0;
976
+ const selectedOptions = selected.map((key) => remote.known.find((option) => option.value === key) ?? {
977
+ value: key,
978
+ label: key
979
+ });
980
+ const remoteStatus = remote.failed ? searchErrorMessage ?? strings.searchFailed : remote.loading ? loadingMessage ?? strings.searching : !remote.eligible && loadOptions ? strings.enterSearch : void 0;
981
+ return /* @__PURE__ */ jsxs(ComboBox, {
982
+ ...loadOptions ? { items: remote.items } : { defaultItems: options },
983
+ selectionMode: multiple ? "multiple" : "single",
984
+ value,
985
+ onChange: (keys) => onChange(Array.isArray(keys) ? keys.map(String) : keys === null ? null : String(keys)),
986
+ onInputChange: setQuery,
987
+ onOpenChange: (nextOpen, trigger) => {
988
+ setOpen(nextOpen);
989
+ onOpenChange?.(nextOpen);
990
+ if (!nextOpen || trigger !== "input") setQuery("");
991
+ },
992
+ name,
993
+ form,
994
+ isDisabled: disabled,
995
+ isReadOnly: readOnly,
996
+ isRequired: required,
997
+ isInvalid: invalid || !!error,
998
+ allowsEmptyCollection: true,
999
+ "aria-label": inputProps["aria-label"],
1000
+ "aria-labelledby": inputProps["aria-labelledby"],
1001
+ className: `nb-form-field${className ? ` ${className}` : ""}`,
770
1002
  children: [
771
- variant === "toolbar" && label && /* @__PURE__ */ jsxs("span", {
772
- className: "nb-dropdown__toolbar-label",
773
- id: `${id}-label`,
774
- children: [icon && /* @__PURE__ */ jsx("i", {
775
- className: normalizeIcon$2(icon),
776
- "aria-hidden": "true"
777
- }), /* @__PURE__ */ jsx("span", { children: label })]
1003
+ label && /* @__PURE__ */ jsx(Label, {
1004
+ className: "nb-form-field__label",
1005
+ children: label
778
1006
  }),
779
- /* @__PURE__ */ jsxs("button", {
780
- type: "button",
781
- className: "nb-dropdown__trigger",
782
- "aria-haspopup": "listbox",
783
- "aria-expanded": open,
784
- "aria-labelledby": label ? `${id}-label ${id}-value` : `${id}-value`,
785
- disabled,
786
- onClick: () => open ? setMenuOpen(false) : openMenu(),
787
- children: [/* @__PURE__ */ jsx("span", {
788
- className: "nb-dropdown__value",
789
- id: `${id}-value`,
790
- children: selected?.selectedLabel ?? selected?.label ?? placeholder
791
- }), /* @__PURE__ */ jsx("i", {
792
- className: "ph ph-caret-down nb-dropdown__caret",
793
- "aria-hidden": "true"
794
- })]
1007
+ /* @__PURE__ */ jsxs("div", {
1008
+ className: "nb-combobox",
1009
+ children: [/* @__PURE__ */ jsx(ComboboxInput, {
1010
+ ...inputProps,
1011
+ openOnClick: !disabled && !readOnly,
1012
+ ref: inputRef,
1013
+ id: inputId,
1014
+ className: `nb-input nb-combobox__input${invalid || error ? " nb-input--invalid" : ""}${inputClassName ? ` ${inputClassName}` : ""}`,
1015
+ onKeyDown: (event) => {
1016
+ inputProps.onKeyDown?.(event);
1017
+ if (open && event.key === "Escape") event.stopPropagation();
1018
+ if (!event.defaultPrevented && event.key === "PageDown" && remote.hasMore) {
1019
+ event.preventDefault();
1020
+ remote.loadMore();
1021
+ }
1022
+ },
1023
+ "aria-invalid": inputProps["aria-invalid"] ?? (invalid || !!error || void 0),
1024
+ "aria-describedby": description
1025
+ }), /* @__PURE__ */ jsxs("div", {
1026
+ className: "nb-combobox__actions",
1027
+ children: [clearable && !readOnly && /* @__PURE__ */ jsx(ComboboxClear, {
1028
+ label: clearLabel ?? strings.clear,
1029
+ disabled,
1030
+ multiple
1031
+ }), /* @__PURE__ */ jsx(Button$1, {
1032
+ className: "nb-combobox__action",
1033
+ "aria-label": openLabel ?? strings.openOptions,
1034
+ children: /* @__PURE__ */ jsx("svg", {
1035
+ viewBox: "0 0 24 24",
1036
+ "aria-hidden": "true",
1037
+ focusable: "false",
1038
+ children: /* @__PURE__ */ jsx("path", { d: "m6 9 6 6 6-6" })
1039
+ })
1040
+ })]
1041
+ })]
795
1042
  }),
796
- open && !disabled && createPortal(/* @__PURE__ */ jsxs("div", {
797
- ref: menuRef,
798
- className: cx$2("nb-dropdown__menu", `nb-dropdown__menu--${variant}`),
799
- style: menuStyle,
1043
+ multiple && selectedOptions.length > 0 && /* @__PURE__ */ jsx(ComboBoxValue, { children: () => /* @__PURE__ */ jsx(TagGroup, {
1044
+ "aria-label": selectedLabel ?? strings.selectedOptions,
1045
+ onRemove: disabled || readOnly ? void 0 : (keys) => onChange(selected.filter((key) => !keys.has(key))),
1046
+ className: "nb-combobox-tags",
1047
+ children: /* @__PURE__ */ jsx(TagList, {
1048
+ items: selectedOptions,
1049
+ children: (option) => /* @__PURE__ */ jsxs(Tag, {
1050
+ id: option.value,
1051
+ textValue: option.label,
1052
+ className: "nb-combobox-tags__tag",
1053
+ children: [option.label, !disabled && !readOnly && /* @__PURE__ */ jsx(Button$1, {
1054
+ slot: "remove",
1055
+ className: "nb-combobox-tags__remove",
1056
+ "aria-label": removeLabel?.(option) ?? strings.removeOption,
1057
+ children: /* @__PURE__ */ jsx("svg", {
1058
+ viewBox: "0 0 24 24",
1059
+ "aria-hidden": "true",
1060
+ focusable: "false",
1061
+ children: /* @__PURE__ */ jsx("path", { d: "m6 6 12 12M18 6 6 18" })
1062
+ })
1063
+ })]
1064
+ })
1065
+ })
1066
+ }) }),
1067
+ /* @__PURE__ */ jsxs(Popover$1, {
1068
+ UNSTABLE_portalContainer: overlayContainer ?? void 0,
1069
+ className: "nb-combobox-popup",
1070
+ offset: 4,
1071
+ isNonModal: true,
1072
+ onScroll: (event) => {
1073
+ const panel = event.currentTarget;
1074
+ if (panel.scrollHeight - panel.scrollTop <= panel.clientHeight + 20) remote.loadMore();
1075
+ },
800
1076
  children: [
801
- menuHeader,
802
- /* @__PURE__ */ jsx("ul", {
803
- role: "listbox",
804
- "aria-labelledby": label ? `${id}-label` : void 0,
805
- className: "nb-dropdown__menu-list",
806
- children: options.map((option) => {
807
- const isActive = option.value === value;
808
- return /* @__PURE__ */ jsx("li", {
809
- role: "presentation",
810
- children: /* @__PURE__ */ jsx("button", {
811
- type: "button",
812
- role: "option",
813
- "aria-selected": isActive,
814
- disabled: option.disabled,
815
- className: cx$2("nb-dropdown__option", isActive && "nb-dropdown__option--active"),
816
- onClick: () => {
817
- if (option.disabled) return;
818
- onChange(option.value);
819
- setMenuOpen(false);
820
- },
821
- children: /* @__PURE__ */ jsxs("span", {
822
- className: "nb-dropdown__option-content",
823
- children: [option.iconText && /* @__PURE__ */ jsx("span", {
824
- className: "nb-dropdown__option-icon",
825
- "aria-hidden": "true",
826
- children: option.iconText
827
- }), /* @__PURE__ */ jsx("span", { children: option.label })]
828
- })
829
- })
830
- }, option.value);
1077
+ remoteStatus && /* @__PURE__ */ jsx("div", {
1078
+ className: "nb-combobox-popup__empty",
1079
+ role: remote.failed ? "alert" : "status",
1080
+ children: remoteStatus
1081
+ }),
1082
+ /* @__PURE__ */ jsx(ListBox, {
1083
+ className: "nb-combobox-popup__list",
1084
+ "aria-busy": remote.loading || void 0,
1085
+ renderEmptyState: () => remoteStatus ? null : /* @__PURE__ */ jsx("div", {
1086
+ className: "nb-combobox-popup__empty",
1087
+ children: emptyMessage ?? strings.noOptions
1088
+ }),
1089
+ children: (option) => /* @__PURE__ */ jsx(ListBoxItem, {
1090
+ id: option.value,
1091
+ textValue: option.label,
1092
+ isDisabled: option.disabled,
1093
+ className: "nb-combobox-popup__item",
1094
+ children: ({ isSelected }) => /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("span", {
1095
+ className: "nb-combobox-popup__indicator",
1096
+ "aria-hidden": "true",
1097
+ children: isSelected ? "✓" : ""
1098
+ }), option.content ?? option.label] })
831
1099
  })
832
1100
  }),
833
- menuFooter
1101
+ remote.hasMore && !remote.failed && /* @__PURE__ */ jsx(Button$1, {
1102
+ slot: null,
1103
+ className: "nb-combobox__action",
1104
+ isDisabled: remote.loading,
1105
+ onPress: () => {
1106
+ remote.loadMore();
1107
+ },
1108
+ children: strings.loadMore
1109
+ }),
1110
+ remote.failed && /* @__PURE__ */ jsx(Button$1, {
1111
+ className: "nb-combobox__action",
1112
+ onPress: remote.retry,
1113
+ children: strings.retrySearch
1114
+ })
834
1115
  ]
835
- }), document.body)
836
- ]
837
- });
838
- if (!showFieldLabel || variant === "toolbar") return control;
839
- return /* @__PURE__ */ jsxs("label", {
840
- className: cx$2("nb-form-field", !!error && "nb-form-field--error"),
841
- htmlFor: id,
842
- children: [
843
- label && /* @__PURE__ */ jsx("span", {
844
- className: "nb-form-field__label",
845
- id: `${id}-label`,
846
- children: label
847
1116
  }),
848
- control,
849
- error ? /* @__PURE__ */ jsx("span", {
850
- className: "nb-form-field__error",
851
- role: "alert",
852
- children: error
853
- }) : helpText ? /* @__PURE__ */ jsx("span", {
854
- className: "nb-form-field__help",
855
- children: helpText
856
- }) : null
1117
+ message && /* @__PURE__ */ jsx("span", {
1118
+ id: messageId,
1119
+ className: error ? "nb-form-field__error" : "nb-form-field__help",
1120
+ role: error ? "alert" : void 0,
1121
+ children: message
1122
+ })
857
1123
  ]
858
1124
  });
859
1125
  }
1126
+ /**
1127
+ * Editable combobox input that also opens its list on click. React Aria opens
1128
+ * on typing or ArrowDown by default; users expect a click on a dropdown-style
1129
+ * field to show the options. Keyboard behaviour is unchanged (no open on focus).
1130
+ */
1131
+ const ComboboxInput = forwardRef(function ComboboxInput({ onClick, openOnClick, ...props }, ref) {
1132
+ const state = useContext(ComboBoxStateContext);
1133
+ return /* @__PURE__ */ jsx(Input, {
1134
+ ...props,
1135
+ ref,
1136
+ onClick: (event) => {
1137
+ onClick?.(event);
1138
+ if (!openOnClick || event.defaultPrevented || !state || state.isOpen) return;
1139
+ state.open(null, "manual");
1140
+ }
1141
+ });
1142
+ });
1143
+ function ComboboxClear({ label, disabled, multiple }) {
1144
+ const state = useContext(ComboBoxStateContext);
1145
+ const hasValue = multiple ? Array.isArray(state?.value) && state.value.length > 0 : !!state?.inputValue;
1146
+ if (!state || !hasValue || state.isOpen) return null;
1147
+ return /* @__PURE__ */ jsx(Button$1, {
1148
+ slot: null,
1149
+ isDisabled: disabled,
1150
+ className: "nb-combobox__action nb-combobox__clear",
1151
+ "aria-label": label,
1152
+ onPress: () => {
1153
+ state.setValue(multiple ? [] : null);
1154
+ state.setInputValue("");
1155
+ },
1156
+ children: /* @__PURE__ */ jsx("svg", {
1157
+ viewBox: "0 0 24 24",
1158
+ "aria-hidden": "true",
1159
+ focusable: "false",
1160
+ children: /* @__PURE__ */ jsx("path", { d: "m6 6 12 12M18 6 6 18" })
1161
+ })
1162
+ });
1163
+ }
860
1164
  //#endregion
861
1165
  //#region packages/ui/SearchableAppDropdown.tsx
862
- function normalizeSearch(value) {
863
- return value.trim().toLowerCase();
864
- }
865
- function filterOptions(options, query) {
866
- const needle = normalizeSearch(query);
867
- if (!needle) return options;
868
- return options.filter((option) => {
869
- return [
870
- option.label,
871
- option.selectedLabel,
872
- option.value
873
- ].filter(Boolean).join(" ").toLowerCase().includes(needle);
874
- });
875
- }
876
- function SearchableAppDropdown({ options = [], searchable = true, searchPlaceholder = "Buscar…", onSearch, minSearchLength = 2, emptySearchLabel = "Sin resultados", loadingLabel = "Buscando…", selectedOption = null, value, onChange, placeholder, disabled, ...rest }) {
877
- const searchInputId = useId();
878
- const [open, setOpen] = useState(false);
879
- const [searchQuery, setSearchQuery] = useState("");
880
- const [remoteOptions, setRemoteOptions] = useState([]);
881
- const [loading, setLoading] = useState(false);
882
- const requestIdRef = useRef(0);
883
- const staticSelected = useMemo(() => options.find((option) => option.value === value) ?? selectedOption ?? null, [
884
- options,
885
- selectedOption,
886
- value
887
- ]);
888
- const resolvedOptions = useMemo(() => {
889
- const merged = /* @__PURE__ */ new Map();
890
- for (const option of [...options, ...remoteOptions]) if (option.value) merged.set(option.value, option);
891
- if (staticSelected?.value) merged.set(staticSelected.value, staticSelected);
892
- const base = Array.from(merged.values()).filter((option) => option.value !== "");
893
- if (!searchable) return base;
894
- if (onSearch) return base;
895
- return filterOptions(base, searchQuery);
896
- }, [
897
- onSearch,
898
- options,
899
- remoteOptions,
900
- searchable,
901
- searchQuery,
902
- staticSelected
903
- ]);
904
- const runSearch = useCallback(async (query) => {
905
- if (!onSearch) return;
906
- const trimmed = query.trim();
907
- if (trimmed.length < minSearchLength) {
908
- setRemoteOptions([]);
909
- setLoading(false);
910
- return;
911
- }
912
- const requestId = ++requestIdRef.current;
913
- setLoading(true);
914
- try {
915
- const results = await onSearch(trimmed);
916
- if (requestId !== requestIdRef.current) return;
917
- setRemoteOptions(results.filter((option) => option.value !== ""));
918
- } catch {
919
- if (requestId !== requestIdRef.current) return;
920
- setRemoteOptions([]);
921
- } finally {
922
- if (requestId === requestIdRef.current) setLoading(false);
923
- }
924
- }, [minSearchLength, onSearch]);
925
- useEffect(() => {
926
- if (!open || !onSearch) return;
927
- const timer = window.setTimeout(() => {
928
- runSearch(searchQuery);
929
- }, 250);
930
- return () => window.clearTimeout(timer);
931
- }, [
932
- open,
933
- onSearch,
934
- runSearch,
935
- searchQuery
936
- ]);
937
- useEffect(() => {
938
- if (open) return;
939
- setSearchQuery("");
940
- setRemoteOptions([]);
941
- setLoading(false);
942
- }, [open]);
943
- const menuHeader = searchable ? /* @__PURE__ */ jsxs("div", {
944
- className: "nb-searchable-dropdown__search",
945
- children: [/* @__PURE__ */ jsx("i", {
946
- className: "ph ph-magnifying-glass",
947
- "aria-hidden": "true"
948
- }), /* @__PURE__ */ jsx("input", {
949
- id: searchInputId,
950
- type: "search",
951
- value: searchQuery,
952
- onChange: (event) => setSearchQuery(event.target.value),
953
- placeholder: searchPlaceholder,
954
- autoComplete: "off",
955
- onKeyDown: (event) => event.stopPropagation()
956
- })]
957
- }) : null;
958
- const menuFooter = (() => {
959
- if (!searchable || !onSearch) return null;
960
- if (loading) return /* @__PURE__ */ jsx("div", {
961
- className: "nb-searchable-dropdown__status",
962
- children: loadingLabel
963
- });
964
- if (searchQuery.trim().length < minSearchLength) return /* @__PURE__ */ jsxs("div", {
965
- className: "nb-searchable-dropdown__status",
966
- children: [
967
- "Escribe al menos ",
968
- minSearchLength,
969
- " caracteres"
970
- ]
971
- });
972
- if (resolvedOptions.length === 0) return /* @__PURE__ */ jsx("div", {
973
- className: "nb-searchable-dropdown__status",
974
- children: emptySearchLabel
975
- });
976
- return null;
977
- })();
978
- return /* @__PURE__ */ jsx(AppDropdown, {
1166
+ const toOption = (option) => ({
1167
+ value: option.value,
1168
+ label: option.selectedLabel ?? option.label,
1169
+ disabled: option.disabled,
1170
+ content: /* @__PURE__ */ jsxs("span", {
1171
+ className: "nb-dropdown__option-content",
1172
+ children: [option.iconText && /* @__PURE__ */ jsx("span", {
1173
+ className: "nb-dropdown__option-icon",
1174
+ "aria-hidden": "true",
1175
+ children: option.iconText
1176
+ }), option.label]
1177
+ })
1178
+ });
1179
+ function SearchableAppDropdown({ options = [], searchable = true, searchPlaceholder = "Buscar…", onSearch, minSearchLength = 2, emptySearchLabel = "Sin resultados", loadingLabel = "Buscando…", selectedOption, value, onChange, placeholder, disabled, label, showFieldLabel, variant, icon: _icon, menuMinWidth: _menuMinWidth, menuHeader: _header, menuFooter: _footer, ...rest }) {
1180
+ const loadOptions = useCallback(async (query, { signal }) => {
1181
+ const results = await onSearch(query.trim());
1182
+ if (signal.aborted) throw new DOMException("Search cancelled", "AbortError");
1183
+ return { options: results.map(toOption) };
1184
+ }, [onSearch]);
1185
+ if (!searchable) return /* @__PURE__ */ jsx(AppDropdown, {
979
1186
  ...rest,
1187
+ options,
980
1188
  value,
981
1189
  onChange,
982
1190
  placeholder,
983
1191
  disabled,
984
- options: [{
985
- value: "",
986
- label: placeholder ?? "Seleccionar…"
987
- }, ...resolvedOptions],
988
- menuHeader,
989
- menuFooter,
990
- onOpenChange: setOpen
1192
+ label,
1193
+ showFieldLabel,
1194
+ variant,
1195
+ icon: _icon,
1196
+ menuMinWidth: _menuMinWidth,
1197
+ menuHeader: _header,
1198
+ menuFooter: _footer
1199
+ });
1200
+ const seeds = selectedOption && !options.some((option) => option.value === selectedOption.value) ? [...options, selectedOption] : options;
1201
+ return /* @__PURE__ */ jsx(Combobox, {
1202
+ ...rest,
1203
+ label: showFieldLabel === false ? void 0 : label,
1204
+ "aria-label": showFieldLabel === false && typeof label === "string" ? label : void 0,
1205
+ placeholder: placeholder ?? searchPlaceholder,
1206
+ options: seeds.map(toOption),
1207
+ value: value || null,
1208
+ onChange: (next) => onChange(next ?? ""),
1209
+ disabled,
1210
+ loadOptions: onSearch ? loadOptions : void 0,
1211
+ minSearchLength,
1212
+ emptyMessage: emptySearchLabel,
1213
+ loadingMessage: loadingLabel
991
1214
  });
992
1215
  }
993
1216
  //#endregion
@@ -1050,7 +1273,7 @@ function applyThemeAttributes(theme, themePrefix) {
1050
1273
  themeValues.forEach((value) => root.classList.remove(`${themePrefix}${value}`));
1051
1274
  root.classList.add(`${themePrefix}${theme}`);
1052
1275
  }
1053
- const ThemeProvider = ({ storageKey = "nb-theme", themePrefix = "nb-theme-", basePath = "/themes/", children }) => {
1276
+ const ThemeProvider = ({ storageKey = "nb-theme", themePrefix = "nb-theme-", basePath = "/themes/", visualStyle = "default", children }) => {
1054
1277
  const getPersistedMode = () => {
1055
1278
  const persisted = window.localStorage.getItem(storageKey);
1056
1279
  return persisted && themeModes.includes(persisted) ? persisted : "auto";
@@ -1059,6 +1282,15 @@ const ThemeProvider = ({ storageKey = "nb-theme", themePrefix = "nb-theme-", bas
1059
1282
  const [systemTheme, setSystemTheme] = useState(getSystemTheme);
1060
1283
  const [isLoaded, setIsLoaded] = useState(false);
1061
1284
  const theme = useMemo(() => resolveTheme(mode, systemTheme), [mode, systemTheme]);
1285
+ useEffect(() => {
1286
+ const root = document.documentElement;
1287
+ const previous = root.getAttribute("data-visual-style");
1288
+ root.setAttribute("data-visual-style", visualStyle);
1289
+ return () => {
1290
+ if (previous === null) root.removeAttribute("data-visual-style");
1291
+ else root.setAttribute("data-visual-style", previous);
1292
+ };
1293
+ }, [visualStyle]);
1062
1294
  useEffect(() => {
1063
1295
  applyThemeAttributes(theme, themePrefix);
1064
1296
  setThemeToDOM(`${basePath}${themePrefix}${theme}.css`).then(() => setIsLoaded(true));
@@ -1401,7 +1633,7 @@ const DEFAULT_ICONS = {
1401
1633
  warning: "warning",
1402
1634
  success: "check-circle"
1403
1635
  };
1404
- const EmptyState = ({ icon, variant = "default", title, description, action, size = "md", fill = false, className }) => {
1636
+ const EmptyState = ({ icon, illustration, variant = "default", title, description, action, size = "md", fill = false, className }) => {
1405
1637
  const iconName = icon ?? DEFAULT_ICONS[variant];
1406
1638
  const classes = [
1407
1639
  "nb-empty-state",
@@ -1417,7 +1649,7 @@ const EmptyState = ({ icon, variant = "default", title, description, action, siz
1417
1649
  children: [
1418
1650
  /* @__PURE__ */ jsx("div", {
1419
1651
  className: "nb-empty-state__icon-wrap",
1420
- children: /* @__PURE__ */ jsx("i", {
1652
+ children: illustration ?? /* @__PURE__ */ jsx("i", {
1421
1653
  className: `ph ph-${iconName}`,
1422
1654
  "aria-hidden": "true"
1423
1655
  })
@@ -1498,73 +1730,51 @@ const Toggle = ({ checked, onChange, label, size = "md", disabled = false, "aria
1498
1730
  };
1499
1731
  //#endregion
1500
1732
  //#region packages/ui/ContextMenu.tsx
1501
- const MENU_MIN_WIDTH = 190;
1502
- /**
1503
- * Three-dot overflow context menu.
1504
- * Replaces the legacy `shared/ui/library/card-menu/CardMenu` component.
1505
- *
1506
- * Features over CardMenu:
1507
- * - `danger` variant items
1508
- * - `separator` support
1509
- * - `icon` per item
1510
- * - Custom trigger slot
1511
- * - Left/right alignment
1512
- * - Click-outside + Escape to close
1513
- * - Portalled dropdown (avoids clip inside scrollable tables)
1514
- */
1515
1733
  const ContextMenu = ({ items, visible = true, trigger, triggerLabel = "Opciones", align = "right", className = "" }) => {
1516
- const { open, setOpen, toggle, containerRef, panelRef: menuRef, panelStyle: menuStyle } = useFloatingPanel({
1517
- dismissEvent: "mousedown",
1518
- closeOnViewportExit: true,
1519
- computeStyle: (container) => computeAnchoredStyle(container, {
1520
- align: align === "right" ? "end" : "start",
1521
- minWidth: MENU_MIN_WIDTH,
1522
- flipThreshold: 200,
1523
- zIndex: 1600
1524
- })
1525
- });
1734
+ const container = useOverlayContainer();
1735
+ const triggerRef = useRef(null);
1736
+ const restoreFocus = useRef(false);
1526
1737
  if (!visible) return null;
1527
- const dropdown = open ? /* @__PURE__ */ jsx("ul", {
1528
- ref: menuRef,
1529
- className: "nb-context-menu__dropdown nb-context-menu__dropdown--portaled",
1530
- role: "menu",
1531
- style: menuStyle,
1532
- children: items.map((item, idx) => /* @__PURE__ */ jsxs(React.Fragment, { children: [item.separator && /* @__PURE__ */ jsx("li", {
1533
- role: "none",
1534
- "aria-hidden": "true",
1535
- children: /* @__PURE__ */ jsx("div", { className: "nb-context-menu__separator" })
1536
- }), /* @__PURE__ */ jsx("li", {
1537
- role: "none",
1538
- children: /* @__PURE__ */ jsxs("button", {
1539
- type: "button",
1540
- role: "menuitem",
1541
- disabled: item.disabled,
1542
- "aria-disabled": item.disabled,
1543
- className: `nb-context-menu__item${item.danger ? " nb-context-menu__item--danger" : ""}`,
1544
- onClick: () => {
1545
- setOpen(false);
1546
- item.onClick?.();
1547
- },
1548
- children: [item.icon && /* @__PURE__ */ jsx("i", {
1549
- className: item.icon,
1550
- "aria-hidden": "true"
1551
- }), item.label]
1552
- })
1553
- })] }, idx))
1554
- }) : null;
1555
- return /* @__PURE__ */ jsxs("div", {
1556
- ref: containerRef,
1557
- className: `nb-context-menu${className ? ` ${className}` : ""}`,
1558
- children: [trigger ? /* @__PURE__ */ jsx("span", {
1559
- onClick: toggle,
1560
- children: trigger
1561
- }) : /* @__PURE__ */ jsx(IconButton, {
1562
- icon: "ph ph-dots-three",
1563
- label: triggerLabel,
1564
- "aria-haspopup": "menu",
1565
- "aria-expanded": open,
1566
- onClick: toggle
1567
- }), dropdown && createPortal(dropdown, document.body)]
1738
+ return /* @__PURE__ */ jsx(Menu.Root, {
1739
+ modal: false,
1740
+ onOpenChange: (open, details) => {
1741
+ restoreFocus.current = !open && (details.reason === "item-press" || details.reason === "escape-key");
1742
+ },
1743
+ onOpenChangeComplete: (open) => {
1744
+ if (!open && restoreFocus.current) triggerRef.current?.focus({ preventScroll: true });
1745
+ },
1746
+ children: /* @__PURE__ */ jsxs("div", {
1747
+ className: `nb-context-menu${className ? ` ${className}` : ""}`,
1748
+ children: [/* @__PURE__ */ jsx(Menu.Trigger, {
1749
+ ref: triggerRef,
1750
+ render: isValidElement(trigger) ? trigger : /* @__PURE__ */ jsx(IconButton, {
1751
+ icon: "ph ph-dots-three",
1752
+ label: triggerLabel,
1753
+ children: trigger
1754
+ })
1755
+ }), /* @__PURE__ */ jsx(Menu.Portal, {
1756
+ container: container ?? void 0,
1757
+ children: /* @__PURE__ */ jsx(Menu.Positioner, {
1758
+ align: align === "right" ? "end" : "start",
1759
+ sideOffset: 4,
1760
+ className: "nb-context-menu-positioner",
1761
+ children: /* @__PURE__ */ jsx(Menu.Popup, {
1762
+ finalFocus: triggerRef,
1763
+ className: "nb-context-menu__dropdown",
1764
+ children: items.map((item, index) => /* @__PURE__ */ jsxs(React.Fragment, { children: [item.separator && /* @__PURE__ */ jsx(Menu.Separator, { className: "nb-context-menu__separator" }), /* @__PURE__ */ jsxs(Menu.Item, {
1765
+ disabled: item.disabled,
1766
+ label: item.label,
1767
+ className: `nb-context-menu__item${item.danger ? " nb-context-menu__item--danger" : ""}`,
1768
+ onClick: item.onClick,
1769
+ children: [item.icon && /* @__PURE__ */ jsx("i", {
1770
+ className: item.icon,
1771
+ "aria-hidden": "true"
1772
+ }), item.label]
1773
+ })] }, index))
1774
+ })
1775
+ })
1776
+ })]
1777
+ })
1568
1778
  });
1569
1779
  };
1570
1780
  //#endregion
@@ -1889,6 +2099,7 @@ const CollapsibleSection = ({ label, icon, open, onToggle, children, trailing, c
1889
2099
  className: "nb-collapsible__header",
1890
2100
  children: [/* @__PURE__ */ jsxs("button", {
1891
2101
  type: "button",
2102
+ id: `${bodyId}-trigger`,
1892
2103
  className: "nb-collapsible__trigger",
1893
2104
  "aria-expanded": open,
1894
2105
  "aria-controls": bodyId,
@@ -1915,1124 +2126,699 @@ const CollapsibleSection = ({ label, icon, open, onToggle, children, trailing, c
1915
2126
  id: bodyId,
1916
2127
  className: ["nb-collapsible__body", bodyClassName].filter(Boolean).join(" "),
1917
2128
  role: "region",
1918
- "aria-labelledby": void 0,
2129
+ "aria-labelledby": `${bodyId}-trigger`,
1919
2130
  hidden: !open,
1920
2131
  children
1921
2132
  })]
1922
2133
  });
1923
2134
  };
1924
2135
  //#endregion
1925
- //#region packages/ui/DatePicker.tsx
1926
- const cx$1 = (...values) => values.filter(Boolean).join(" ");
1927
- const ISO_DATE_RE$1 = /^\d{4}-\d{2}-\d{2}$/;
1928
- const getLocale$1 = (override) => override || document.documentElement.lang || navigator.language || "en-US";
1929
- const pad$1 = (value) => String(value).padStart(2, "0");
1930
- const toIsoDate$1 = (date) => `${date.getFullYear()}-${pad$1(date.getMonth() + 1)}-${pad$1(date.getDate())}`;
1931
- const parseIsoDate$1 = (value) => {
1932
- if (!value || !ISO_DATE_RE$1.test(value)) return null;
1933
- const [year, month, day] = value.split("-").map(Number);
1934
- const date = new Date(year, month - 1, day);
1935
- if (date.getFullYear() !== year || date.getMonth() !== month - 1 || date.getDate() !== day) return null;
1936
- return date;
1937
- };
1938
- const startOfMonth$1 = (date) => new Date(date.getFullYear(), date.getMonth(), 1);
1939
- const addMonths$1 = (date, months) => new Date(date.getFullYear(), date.getMonth() + months, 1);
1940
- const formatDisplayDate$1 = (value, locale) => {
1941
- const date = parseIsoDate$1(value);
1942
- if (!date) return "";
1943
- return new Intl.DateTimeFormat(getLocale$1(locale), {
1944
- day: "2-digit",
1945
- month: "2-digit",
1946
- year: "numeric"
1947
- }).format(date);
1948
- };
1949
- const formatMonthLabel$1 = (date, locale) => new Intl.DateTimeFormat(getLocale$1(locale), {
1950
- month: "long",
1951
- year: "numeric"
1952
- }).format(date);
1953
- /**
1954
- * Locale-aware first day of week.
1955
- * Uses Intl.Locale.weekInfo (Chrome 99+, FF 126+, Safari 17+) with fallback heuristic.
1956
- */
1957
- const getFirstDayOfWeek = (locale) => {
1958
- try {
1959
- const info = new Intl.Locale(getLocale$1(locale)).weekInfo;
1960
- if (info && typeof info.firstDay === "number") return info.firstDay === 7 ? 0 : info.firstDay;
1961
- } catch {}
1962
- const country = (getLocale$1(locale).split("-")[1] ?? "").toUpperCase();
1963
- return [
1964
- "US",
1965
- "CA",
1966
- "MX",
1967
- "CN",
1968
- "JP",
1969
- "KR",
1970
- "SA",
1971
- "EG",
1972
- "IL",
1973
- "BR"
1974
- ].includes(country) ? 0 : 1;
1975
- };
1976
- const buildCalendarDays$1 = (month, min, max, locale) => {
1977
- const first = startOfMonth$1(month);
1978
- const firstDayOfWeek = getFirstDayOfWeek(locale);
1979
- const offset = (first.getDay() - firstDayOfWeek + 7) % 7;
1980
- const minDate = parseIsoDate$1(min);
1981
- const maxDate = parseIsoDate$1(max);
1982
- const start = new Date(first);
1983
- start.setDate(first.getDate() - offset);
1984
- return Array.from({ length: 42 }, (_, i) => {
1985
- const date = new Date(start);
1986
- date.setDate(start.getDate() + i);
1987
- return {
2136
+ //#region packages/ui/CalendarContent.tsx
2137
+ /** Shared presentation; React Aria owns navigation, focus and range preview. */
2138
+ function CalendarContent() {
2139
+ const strings = useUiStrings();
2140
+ return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsxs("header", {
2141
+ className: "nb-calendar__header",
2142
+ children: [
2143
+ /* @__PURE__ */ jsx(Button$1, {
2144
+ slot: "previous",
2145
+ className: "nb-date-picker__nav",
2146
+ "aria-label": strings.previousMonth,
2147
+ children: "‹"
2148
+ }),
2149
+ /* @__PURE__ */ jsxs("div", {
2150
+ className: "nb-calendar__selectors",
2151
+ children: [
2152
+ /* @__PURE__ */ jsx(Heading, { className: "nb-calendar__heading" }),
2153
+ /* @__PURE__ */ jsx(CalendarMonthPicker, { children: ({ items, value, onChange, ...props }) => /* @__PURE__ */ jsx("select", {
2154
+ ...props,
2155
+ value,
2156
+ onChange: (event) => onChange(Number(event.target.value)),
2157
+ children: items.map((item) => /* @__PURE__ */ jsx("option", {
2158
+ value: item.id,
2159
+ children: item.formatted
2160
+ }, item.id))
2161
+ }) }),
2162
+ /* @__PURE__ */ jsx(CalendarYearPicker, { children: ({ items, value, onChange, ...props }) => /* @__PURE__ */ jsx("select", {
2163
+ ...props,
2164
+ value,
2165
+ onChange: (event) => onChange(Number(event.target.value)),
2166
+ children: items.map((item) => /* @__PURE__ */ jsx("option", {
2167
+ value: item.id,
2168
+ children: item.formatted
2169
+ }, item.id))
2170
+ }) })
2171
+ ]
2172
+ }),
2173
+ /* @__PURE__ */ jsx(Button$1, {
2174
+ slot: "next",
2175
+ className: "nb-date-picker__nav",
2176
+ "aria-label": strings.nextMonth,
2177
+ children: "›"
2178
+ })
2179
+ ]
2180
+ }), /* @__PURE__ */ jsxs(CalendarGrid, {
2181
+ className: "nb-calendar__grid",
2182
+ children: [/* @__PURE__ */ jsx(CalendarGridHeader, { children: (day) => /* @__PURE__ */ jsx(CalendarHeaderCell, {
2183
+ className: "nb-calendar__weekday",
2184
+ children: day
2185
+ }) }), /* @__PURE__ */ jsx(CalendarGridBody, { children: (date) => /* @__PURE__ */ jsx(CalendarCell, {
1988
2186
  date,
1989
- iso: toIsoDate$1(date),
1990
- inCurrentMonth: date.getMonth() === month.getMonth(),
1991
- disabled: Boolean(minDate && date < minDate || maxDate && date > maxDate)
1992
- };
1993
- });
1994
- };
1995
- const isIsoDateDisabled = (iso, min, max) => {
1996
- const date = parseIsoDate$1(iso);
1997
- if (!date) return true;
1998
- const minDate = parseIsoDate$1(min);
1999
- const maxDate = parseIsoDate$1(max);
2000
- return Boolean(minDate && date < minDate || maxDate && date > maxDate);
2001
- };
2002
- const weekDayLabels = (locale) => {
2003
- const firstDayOfWeek = getFirstDayOfWeek(locale);
2004
- const anchor = new Date(2026, 5, 7);
2005
- const formatter = new Intl.DateTimeFormat(getLocale$1(locale), { weekday: "narrow" });
2006
- return Array.from({ length: 7 }, (_, i) => {
2007
- const date = new Date(anchor);
2008
- date.setDate(anchor.getDate() + (firstDayOfWeek + i) % 7);
2009
- return formatter.format(date);
2187
+ className: "nb-calendar__day"
2188
+ }) })]
2189
+ })] });
2190
+ }
2191
+ /** A parent modal owns containment; a standalone picker needs its own focus scope. */
2192
+ function CalendarDialog({ id, ariaLabel, children }) {
2193
+ return useOverlayContainer() ? /* @__PURE__ */ jsx("section", {
2194
+ id,
2195
+ "aria-label": ariaLabel,
2196
+ role: "dialog",
2197
+ tabIndex: -1,
2198
+ children
2199
+ }) : /* @__PURE__ */ jsx(Dialog$1, {
2200
+ id,
2201
+ "aria-label": ariaLabel,
2202
+ children
2010
2203
  });
2204
+ }
2205
+ //#endregion
2206
+ //#region packages/ui/dateValues.ts
2207
+ const getDateLocale = (locale) => locale || typeof document !== "undefined" && document.documentElement.lang || typeof navigator !== "undefined" && navigator.language || "en-US";
2208
+ const calendarDate = (value) => {
2209
+ if (!value || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return null;
2210
+ try {
2211
+ return parseDate(value);
2212
+ } catch {
2213
+ return null;
2214
+ }
2011
2215
  };
2012
- /** Short month labels (Jan, Feb, …) — capitalized for display. */
2013
- const getMonthLabels = (locale) => {
2014
- const formatter = new Intl.DateTimeFormat(getLocale$1(locale), { month: "short" });
2015
- return Array.from({ length: 12 }, (_, i) => {
2016
- const label = formatter.format(new Date(2024, i, 1));
2017
- return label.charAt(0).toUpperCase() + label.slice(1).replace(".", "");
2018
- });
2216
+ const formatDate = (value, locale) => {
2217
+ const date = calendarDate(value);
2218
+ return date ? new Intl.DateTimeFormat(locale, {
2219
+ day: "2-digit",
2220
+ month: "2-digit",
2221
+ year: "numeric",
2222
+ timeZone: "UTC"
2223
+ }).format(date.toDate("UTC")) : "";
2019
2224
  };
2020
- /** Year range: 12-year block containing the given year. */
2021
- const getYearRangeStart = (year) => Math.floor(year / 12) * 12;
2022
- /**
2023
- * Applies dd/mm/yyyy mask.
2024
- * Auto-inserts trailing slash when adding the 2nd or 4th digit.
2025
- * Does NOT add trailing slash when the user is deleting.
2026
- */
2027
- const applyDateMask = (rawValue, prevValue) => {
2225
+ const dateAllowed = (value, min, max) => Boolean(calendarDate(value)) && (!min || value >= min) && (!max || value <= max);
2226
+ const dateOrder = (locale) => new Intl.DateTimeFormat(getDateLocale(locale), {
2227
+ day: "2-digit",
2228
+ month: "2-digit",
2229
+ year: "numeric",
2230
+ timeZone: "UTC"
2231
+ }).formatToParts(new Date(Date.UTC(2026, 10, 23))).filter((part) => [
2232
+ "day",
2233
+ "month",
2234
+ "year"
2235
+ ].includes(part.type)).map((part) => part.type);
2236
+ const datePlaceholder = (locale) => dateOrder(locale).map((part) => part === "year" ? "yyyy" : part === "month" ? "mm" : "dd").join("/");
2237
+ const applyDateMask = (rawValue, prevValue, locale) => {
2238
+ if (/^\d{4}-\d{2}-\d{2}$/.test(rawValue)) return rawValue;
2028
2239
  const digits = rawValue.replace(/\D/g, "").slice(0, 8);
2029
- const prevDigits = prevValue.replace(/\D/g, "");
2030
- const isAdding = digits.length > prevDigits.length;
2031
- if (digits.length === 0) return "";
2032
- let result = digits.slice(0, 2);
2033
- if (digits.length > 2) result += "/" + digits.slice(2, 4);
2034
- if (digits.length > 4) result += "/" + digits.slice(4, 8);
2035
- if (isAdding && (digits.length === 2 || digits.length === 4)) result += "/";
2240
+ const adding = digits.length > prevValue.replace(/\D/g, "").length;
2241
+ const sizes = dateOrder(locale ?? "es-PE").map((part) => part === "year" ? 4 : 2);
2242
+ let offset = 0;
2243
+ let result = "";
2244
+ for (const [i, size] of sizes.entries()) {
2245
+ result += digits.slice(offset, offset + size);
2246
+ offset += size;
2247
+ if (i < 2 && (digits.length > offset || adding && digits.length === offset)) result += "/";
2248
+ }
2036
2249
  return result;
2037
2250
  };
2038
- /**
2039
- * Parses dd/mm/yyyy or ISO yyyy-mm-dd to ISO string.
2040
- * Returns null if not a valid date.
2041
- */
2042
2251
  const parseDisplayDate = (text, locale) => {
2043
- const match = text.match(/^(\d{1,2})[/-](\d{1,2})[/-](\d{4})$/);
2044
- if (match) {
2045
- const [, a, b, year] = match;
2046
- const [dd, mm] = (getLocale$1(locale).split("-")[1] ?? "").toUpperCase() === "US" ? [b, a] : [a, b];
2047
- const iso = `${year}-${mm.padStart(2, "0")}-${dd.padStart(2, "0")}`;
2048
- return parseIsoDate$1(iso) ? iso : null;
2049
- }
2050
- if (ISO_DATE_RE$1.test(text)) return parseIsoDate$1(text) ? text : null;
2051
- return null;
2252
+ if (calendarDate(text)) return text;
2253
+ const order = dateOrder(locale);
2254
+ const digits = text.match(/\d+/g);
2255
+ if (!digits || digits.length !== 3) return null;
2256
+ const fields = Object.fromEntries(order.map((key, i) => [key, digits[i]]));
2257
+ if (fields.year?.length !== 4) return null;
2258
+ const iso = `${fields.year}-${fields.month?.padStart(2, "0")}-${fields.day?.padStart(2, "0")}`;
2259
+ return calendarDate(iso) ? iso : null;
2052
2260
  };
2053
- const DatePicker = forwardRef(function DatePicker({ id, name, value, placeholder = "dd/mm/yyyy", disabled = false, readOnly = false, required = false, invalid = false, clearable = true, locale, min, max, className, ariaLabel, onChange, onBlur }, ref) {
2054
- const generatedId = useId();
2055
- const inputId = id ?? generatedId;
2056
- const panelId = `${inputId}-panel`;
2057
- const strings = useUiStrings();
2058
- const selectedDate = parseIsoDate$1(value);
2059
- const resolvedLocale = getLocale$1(locale);
2060
- const displayValue = formatDisplayDate$1(value, resolvedLocale);
2061
- const [viewMode, setViewMode] = useState("days");
2062
- const [month, setMonth] = useState(() => startOfMonth$1(selectedDate ?? /* @__PURE__ */ new Date()));
2063
- const [yearRangeStart, setYearRangeStart] = useState(() => getYearRangeStart((/* @__PURE__ */ new Date()).getFullYear()));
2064
- const [focusedIso, setFocusedIso] = useState(null);
2065
- const [inputText, setInputText] = useState("");
2066
- const [isEditing, setIsEditing] = useState(false);
2067
- const inputRef = useRef(null);
2068
- const triggerRef = useRef(null);
2069
- const { open, setOpen, containerRef: rootRef, panelRef, panelStyle } = useFloatingPanel({
2070
- onClose: () => {
2071
- setFocusedIso(null);
2072
- setViewMode("days");
2073
- },
2074
- onEscape: (e) => {
2075
- e.preventDefault();
2076
- inputRef.current?.focus();
2261
+ //#endregion
2262
+ //#region packages/ui/DateTextInput.tsx
2263
+ /** Keeps the real input/ref/ID contract used by CRUD forms. */
2264
+ const DateTextInput = forwardRef(function DateTextInput({ value, locale, min, max, onChange, onOpen, onBlur, onKeyDown, ...props }, ref) {
2265
+ const [draft, setDraft] = useState(null);
2266
+ const commit = () => {
2267
+ if (draft === null) return;
2268
+ const iso = parseDisplayDate(draft.trim(), locale);
2269
+ if (!draft.trim()) onChange("");
2270
+ else if (iso && dateAllowed(iso, min, max)) onChange(iso);
2271
+ setDraft(null);
2272
+ };
2273
+ return /* @__PURE__ */ jsx("input", {
2274
+ ...props,
2275
+ ref,
2276
+ type: "text",
2277
+ inputMode: "numeric",
2278
+ onPointerDown: (event) => event.stopPropagation(),
2279
+ onPointerUp: (event) => event.stopPropagation(),
2280
+ onMouseDown: (event) => event.stopPropagation(),
2281
+ onClick: (event) => event.stopPropagation(),
2282
+ value: draft ?? formatDate(value, locale),
2283
+ onChange: (event) => setDraft(applyDateMask(event.target.value, draft ?? "", locale)),
2284
+ onBlur: (event) => {
2285
+ commit();
2286
+ onBlur?.(event);
2077
2287
  },
2078
- computeStyle: () => {
2079
- const rect = triggerRef.current?.getBoundingClientRect();
2080
- if (!rect) return null;
2081
- const panelWidth = panelRef.current?.offsetWidth ?? 296;
2082
- const left = Math.min(Math.max(8, rect.left), window.innerWidth - panelWidth - 8);
2083
- const top = Math.min(rect.bottom + 6, window.innerHeight - 380);
2084
- return {
2085
- left,
2086
- top: Math.max(8, top)
2087
- };
2288
+ onKeyDown: (event) => {
2289
+ if (event.key !== "Escape") event.stopPropagation();
2290
+ onKeyDown?.(event);
2291
+ if (event.defaultPrevented) return;
2292
+ if (event.key === "Enter") {
2293
+ event.preventDefault();
2294
+ commit();
2295
+ }
2296
+ if (event.key === "Escape") setDraft(null);
2297
+ if (event.key === "ArrowDown" && !props.disabled && !props.readOnly) {
2298
+ event.preventDefault();
2299
+ commit();
2300
+ onOpen();
2301
+ }
2088
2302
  }
2089
2303
  });
2090
- const days = useMemo(() => buildCalendarDays$1(month, min, max, resolvedLocale), [
2091
- max,
2092
- min,
2093
- month,
2094
- resolvedLocale
2095
- ]);
2096
- const weekdayLabels = useMemo(() => weekDayLabels(resolvedLocale), [resolvedLocale]);
2097
- const monthLabels = useMemo(() => getMonthLabels(resolvedLocale), [resolvedLocale]);
2098
- const selectedIso = selectedDate ? toIsoDate$1(selectedDate) : "";
2099
- useEffect(() => {
2100
- if (selectedDate) setMonth(startOfMonth$1(selectedDate));
2101
- }, [value]);
2304
+ });
2305
+ //#endregion
2306
+ //#region packages/ui/useCalendarPopover.ts
2307
+ /** Bridge focus restoration between React Aria's popup and a parent Base UI modal. */
2308
+ function useCalendarPopover() {
2309
+ const container = useOverlayContainer();
2310
+ const groupRef = useRef(null);
2311
+ const panelRef = useRef(null);
2312
+ const frame = useRef(null);
2313
+ const outsideTarget = useRef(null);
2314
+ const [open, updateOpen] = useState(false);
2102
2315
  useEffect(() => {
2103
- if (!open) return;
2104
- const initialIso = selectedDate ? toIsoDate$1(selectedDate) : toIsoDate$1(/* @__PURE__ */ new Date());
2105
- setFocusedIso(initialIso);
2106
- window.setTimeout(() => {
2107
- panelRef.current?.querySelector(`[data-iso="${initialIso}"]`)?.focus();
2108
- }, 0);
2109
- }, [open]);
2110
- const commitValue = useCallback((nextValue) => {
2111
- onChange?.(nextValue);
2112
- setOpen(false);
2113
- setIsEditing(false);
2114
- setInputText("");
2115
- window.setTimeout(() => inputRef.current?.focus());
2116
- }, [onChange, setOpen]);
2117
- const handleToday = useCallback(() => {
2118
- const today = toIsoDate$1(/* @__PURE__ */ new Date());
2119
- if (isIsoDateDisabled(today, min, max)) return;
2120
- setMonth(startOfMonth$1(parseIsoDate$1(today)));
2121
- commitValue(today);
2122
- }, [
2123
- min,
2124
- max,
2125
- commitValue
2126
- ]);
2127
- const handleClear = useCallback((e) => {
2128
- e.preventDefault();
2129
- commitValue("");
2130
- }, [commitValue]);
2131
- const handleInputFocus = () => {
2132
- setIsEditing(true);
2133
- setInputText(displayValue);
2134
- window.setTimeout(() => inputRef.current?.select(), 0);
2135
- };
2136
- const handleInputChange = (e) => {
2137
- if (readOnly || disabled) return;
2138
- setInputText(applyDateMask(e.target.value, inputText));
2139
- };
2140
- const handleInputBlur = (e) => {
2141
- const related = e.relatedTarget;
2142
- if (rootRef.current?.contains(related) || panelRef.current?.contains(related)) return;
2143
- setIsEditing(false);
2144
- const parsed = parseDisplayDate(inputText, resolvedLocale);
2145
- if (parsed !== null) {
2146
- if (parsed !== value) onChange?.(parsed);
2147
- } else if (inputText === "" && value) onChange?.("");
2148
- setInputText("");
2149
- onBlur?.(e);
2150
- };
2151
- const handleInputKeyDown = (e) => {
2152
- if (e.key === "Enter") {
2153
- e.preventDefault();
2154
- const parsed = parseDisplayDate(inputText, resolvedLocale);
2155
- if (parsed !== null) commitValue(parsed);
2156
- else if (inputText === "") commitValue("");
2157
- } else if (e.key === "ArrowDown" || e.key === "F4") {
2158
- e.preventDefault();
2159
- if (!readOnly && !disabled) setOpen(true);
2160
- } else if (e.key === "Escape" && open) setOpen(false);
2161
- };
2162
- const handleCalendarPointerDown = (e) => {
2163
- e.preventDefault();
2164
- if (readOnly || disabled) return;
2165
- setOpen(!open);
2166
- };
2167
- const handleDayKeyDown = useCallback((e, iso) => {
2168
- if (![
2169
- "ArrowLeft",
2170
- "ArrowRight",
2171
- "ArrowUp",
2172
- "ArrowDown",
2173
- "Enter",
2174
- " "
2175
- ].includes(e.key)) return;
2176
- e.preventDefault();
2177
- if (e.key === "Enter" || e.key === " ") {
2178
- const day = days.find((d) => d.iso === iso);
2179
- if (day && !day.disabled) commitValue(iso);
2180
- return;
2181
- }
2182
- const delta = {
2183
- ArrowLeft: -1,
2184
- ArrowRight: 1,
2185
- ArrowUp: -7,
2186
- ArrowDown: 7
2187
- }[e.key] ?? 0;
2188
- const current = parseIsoDate$1(iso);
2189
- if (!current) return;
2190
- const next = new Date(current);
2191
- next.setDate(current.getDate() + delta);
2192
- const nextIso = toIsoDate$1(next);
2193
- if (next.getMonth() !== month.getMonth() || next.getFullYear() !== month.getFullYear()) setMonth(startOfMonth$1(next));
2194
- setFocusedIso(nextIso);
2195
- window.setTimeout(() => {
2196
- panelRef.current?.querySelector(`[data-iso="${nextIso}"]`)?.focus();
2197
- }, 0);
2198
- }, [
2199
- days,
2200
- month,
2201
- commitValue,
2202
- panelRef
2203
- ]);
2204
- const handleMonthSelect = (monthIndex) => {
2205
- setMonth(new Date(month.getFullYear(), monthIndex, 1));
2206
- setViewMode("days");
2207
- };
2208
- const handleYearSelect = (year) => {
2209
- setMonth(new Date(year, month.getMonth(), 1));
2210
- setViewMode("months");
2211
- };
2212
- const setInputRef = (node) => {
2213
- inputRef.current = node;
2214
- if (typeof ref === "function") ref(node);
2215
- else if (ref) ref.current = node;
2316
+ if (!open || !container) return;
2317
+ const rememberTarget = (event) => {
2318
+ if (event.target instanceof Element && container.contains(event.target) && !panelRef.current?.contains(event.target)) outsideTarget.current = event.target.closest("input, button, select, textarea, a[href], [tabindex]:not([tabindex=\"-1\"])");
2319
+ };
2320
+ document.addEventListener("pointerdown", rememberTarget, true);
2321
+ return () => document.removeEventListener("pointerdown", rememberTarget, true);
2322
+ }, [open, container]);
2323
+ useEffect(() => () => {
2324
+ if (frame.current !== null) cancelAnimationFrame(frame.current);
2325
+ }, []);
2326
+ return {
2327
+ container,
2328
+ groupRef,
2329
+ panelRef,
2330
+ open,
2331
+ setOpen: useCallback((next) => {
2332
+ if (frame.current !== null) cancelAnimationFrame(frame.current);
2333
+ if (next) outsideTarget.current = null;
2334
+ const active = document.activeElement;
2335
+ const target = outsideTarget.current ?? groupRef.current?.querySelector("input");
2336
+ const restore = !next && container && (outsideTarget.current || panelRef.current?.contains(active));
2337
+ updateOpen(next);
2338
+ if (restore) frame.current = requestAnimationFrame(() => {
2339
+ frame.current = requestAnimationFrame(() => {
2340
+ frame.current = null;
2341
+ if (document.activeElement === active || document.activeElement === container || document.activeElement === document.body) target?.focus();
2342
+ });
2343
+ });
2344
+ }, [container])
2216
2345
  };
2217
- const todayIso = toIsoDate$1(/* @__PURE__ */ new Date());
2218
- return /* @__PURE__ */ jsxs("div", {
2219
- ref: rootRef,
2220
- className: cx$1("nb-date-picker", className),
2221
- children: [
2222
- /* @__PURE__ */ jsx("input", {
2223
- type: "hidden",
2224
- name,
2225
- value: value ?? "",
2226
- required
2227
- }),
2228
- /* @__PURE__ */ jsxs("div", {
2229
- ref: triggerRef,
2230
- className: cx$1("nb-date-picker__trigger", invalid && "nb-date-picker__trigger--invalid", readOnly && "nb-date-picker__trigger--readonly", open && "nb-date-picker__trigger--open", disabled && "nb-date-picker__trigger--disabled"),
2231
- children: [/* @__PURE__ */ jsx("input", {
2232
- ref: setInputRef,
2233
- id: inputId,
2234
- type: "text",
2235
- inputMode: "numeric",
2236
- className: cx$1("nb-date-picker__input", !isEditing && !displayValue && "nb-date-picker__input--placeholder"),
2237
- value: isEditing ? inputText : displayValue,
2238
- placeholder,
2239
- disabled,
2240
- readOnly,
2241
- "aria-label": ariaLabel,
2242
- role: "combobox",
2243
- "aria-haspopup": "dialog",
2244
- "aria-expanded": open,
2245
- "aria-controls": open ? panelId : void 0,
2246
- "aria-invalid": invalid || void 0,
2247
- "aria-required": required || void 0,
2248
- autoComplete: "off",
2249
- onFocus: handleInputFocus,
2250
- onBlur: handleInputBlur,
2251
- onChange: handleInputChange,
2252
- onKeyDown: handleInputKeyDown
2253
- }), /* @__PURE__ */ jsxs("span", {
2254
- className: "nb-date-picker__icons",
2255
- children: [clearable && displayValue && !disabled && !readOnly && /* @__PURE__ */ jsx("span", {
2256
- role: "button",
2257
- tabIndex: -1,
2258
- className: "nb-date-picker__clear",
2259
- "aria-label": strings.clearDate,
2260
- onPointerDown: handleClear,
2261
- children: /* @__PURE__ */ jsx("i", {
2262
- className: "ph ph-x",
2263
- "aria-hidden": "true"
2264
- })
2265
- }), /* @__PURE__ */ jsx("span", {
2266
- role: "button",
2267
- tabIndex: -1,
2268
- className: "nb-date-picker__calendar-btn",
2269
- "aria-label": strings.openCalendar,
2270
- onPointerDown: handleCalendarPointerDown,
2271
- children: /* @__PURE__ */ jsx("i", {
2272
- className: "ph ph-calendar-blank",
2273
- "aria-hidden": "true"
2274
- })
2275
- })]
2276
- })]
2277
- }),
2278
- open && createPortal(/* @__PURE__ */ jsxs("div", {
2279
- ref: panelRef,
2280
- id: panelId,
2281
- className: "nb-date-picker__panel",
2282
- role: "dialog",
2283
- "aria-label": strings.selectDate,
2284
- style: panelStyle,
2285
- children: [
2286
- viewMode === "days" && /* @__PURE__ */ jsxs(Fragment, { children: [
2287
- /* @__PURE__ */ jsxs("div", {
2288
- className: "nb-date-picker__header",
2289
- children: [
2290
- /* @__PURE__ */ jsx("button", {
2291
- type: "button",
2292
- className: "nb-date-picker__nav",
2293
- "aria-label": strings.previousMonth,
2294
- onClick: () => setMonth((m) => addMonths$1(m, -1)),
2295
- children: /* @__PURE__ */ jsx("i", {
2296
- className: "ph ph-caret-left",
2297
- "aria-hidden": "true"
2298
- })
2299
- }),
2300
- /* @__PURE__ */ jsxs("button", {
2301
- type: "button",
2302
- className: "nb-date-picker__month nb-date-picker__month--clickable",
2303
- "aria-label": strings.selectMonthAndYear,
2304
- onClick: () => setViewMode("months"),
2305
- children: [formatMonthLabel$1(month, resolvedLocale), /* @__PURE__ */ jsx("i", {
2306
- className: "ph ph-caret-down nb-date-picker__month-caret",
2307
- "aria-hidden": "true"
2308
- })]
2309
- }),
2310
- /* @__PURE__ */ jsx("button", {
2311
- type: "button",
2312
- className: "nb-date-picker__nav",
2313
- "aria-label": strings.nextMonth,
2314
- onClick: () => setMonth((m) => addMonths$1(m, 1)),
2315
- children: /* @__PURE__ */ jsx("i", {
2316
- className: "ph ph-caret-right",
2317
- "aria-hidden": "true"
2318
- })
2319
- })
2320
- ]
2321
- }),
2322
- /* @__PURE__ */ jsx("div", {
2323
- className: "nb-date-picker__weekdays",
2324
- "aria-hidden": "true",
2325
- children: weekdayLabels.map((label, i) => /* @__PURE__ */ jsx("span", { children: label }, `${label}-${i}`))
2346
+ }
2347
+ //#endregion
2348
+ //#region packages/ui/DatePicker.tsx
2349
+ const DatePicker = forwardRef(function DatePicker({ id, name, value, placeholder, disabled = false, readOnly = false, required = false, invalid = false, clearable = true, locale, min, max, className, ariaLabel, onChange, onBlur }, ref) {
2350
+ const generatedId = useId();
2351
+ const inputId = id ?? generatedId;
2352
+ const { container, groupRef, panelRef, open, setOpen } = useCalendarPopover();
2353
+ const strings = useUiStrings();
2354
+ const resolvedLocale = getDateLocale(locale);
2355
+ const change = (next) => onChange?.(next);
2356
+ const todayIso = today(getLocalTimeZone()).toString();
2357
+ const prefix = "nb-date-picker";
2358
+ return /* @__PURE__ */ jsx(I18nProvider, {
2359
+ locale: resolvedLocale,
2360
+ children: /* @__PURE__ */ jsxs(DatePicker$1, {
2361
+ "aria-label": ariaLabel ?? strings.selectDate,
2362
+ value: calendarDate(value),
2363
+ onChange: (date) => change(date?.toString() ?? ""),
2364
+ minValue: calendarDate(min) ?? void 0,
2365
+ maxValue: calendarDate(max) ?? void 0,
2366
+ isDisabled: disabled,
2367
+ isReadOnly: readOnly,
2368
+ isRequired: required,
2369
+ isInvalid: invalid,
2370
+ validationBehavior: "aria",
2371
+ isOpen: open,
2372
+ onOpenChange: setOpen,
2373
+ className: [prefix, className].filter(Boolean).join(" "),
2374
+ children: [
2375
+ /* @__PURE__ */ jsx("input", {
2376
+ type: "hidden",
2377
+ name,
2378
+ value: value ?? "",
2379
+ disabled
2380
+ }),
2381
+ /* @__PURE__ */ jsxs(Group, {
2382
+ ref: groupRef,
2383
+ className: [
2384
+ `${prefix}__trigger`,
2385
+ disabled && `${prefix}__trigger--disabled`,
2386
+ readOnly && `${prefix}__trigger--readonly`,
2387
+ invalid && `${prefix}__trigger--invalid`,
2388
+ open && `${prefix}__trigger--open`
2389
+ ].filter(Boolean).join(" "),
2390
+ children: [
2391
+ /* @__PURE__ */ jsx(DateTextInput, {
2392
+ ref,
2393
+ id: inputId,
2394
+ value,
2395
+ locale: resolvedLocale,
2396
+ min,
2397
+ max,
2398
+ placeholder: placeholder ?? datePlaceholder(resolvedLocale),
2399
+ disabled,
2400
+ readOnly,
2401
+ required,
2402
+ "aria-label": ariaLabel ?? (id ? void 0 : strings.selectDate),
2403
+ "aria-invalid": invalid || void 0,
2404
+ role: "combobox",
2405
+ "aria-haspopup": "dialog",
2406
+ "aria-expanded": open,
2407
+ "aria-controls": open ? `${inputId}-panel` : void 0,
2408
+ className: `${prefix}__input`,
2409
+ onChange: change,
2410
+ onOpen: () => setOpen(true),
2411
+ onBlur,
2412
+ onKeyDown: (event) => {
2413
+ if (event.key === "Escape" && open) {
2414
+ event.stopPropagation();
2415
+ setOpen(false);
2416
+ }
2417
+ }
2326
2418
  }),
2327
- /* @__PURE__ */ jsx("div", {
2328
- className: "nb-date-picker__days",
2329
- role: "grid",
2330
- "aria-label": formatMonthLabel$1(month, resolvedLocale),
2331
- children: days.map((day) => /* @__PURE__ */ jsx("button", {
2332
- "data-iso": day.iso,
2333
- type: "button",
2334
- className: cx$1("nb-date-picker__day", !day.inCurrentMonth && "nb-date-picker__day--muted", day.iso === selectedIso && "nb-date-picker__day--selected", day.iso === todayIso && "nb-date-picker__day--today"),
2335
- disabled: day.disabled,
2336
- role: "gridcell",
2337
- "aria-selected": day.iso === selectedIso,
2338
- tabIndex: day.iso === (focusedIso ?? selectedIso ?? todayIso) ? 0 : -1,
2339
- onClick: () => commitValue(day.iso),
2340
- onKeyDown: (e) => handleDayKeyDown(e, day.iso),
2341
- children: day.date.getDate()
2342
- }, day.iso))
2419
+ clearable && value && !disabled && !readOnly && /* @__PURE__ */ jsx(Button$1, {
2420
+ slot: null,
2421
+ className: `${prefix}__clear`,
2422
+ "aria-label": strings.clearDate,
2423
+ onPress: () => change(""),
2424
+ children: "×"
2343
2425
  }),
2344
- /* @__PURE__ */ jsxs("div", {
2345
- className: "nb-date-picker__footer",
2346
- children: [/* @__PURE__ */ jsx("button", {
2347
- type: "button",
2348
- className: "nb-date-picker__text-button",
2349
- onClick: () => commitValue(""),
2426
+ /* @__PURE__ */ jsx(Button$1, {
2427
+ className: `${prefix}__calendar-btn`,
2428
+ "aria-label": strings.openCalendar,
2429
+ onPress: () => groupRef.current?.querySelector("input")?.focus(),
2430
+ isDisabled: disabled || readOnly,
2431
+ children: /* @__PURE__ */ jsx("i", {
2432
+ "aria-hidden": "true",
2433
+ className: "ph ph-calendar-blank"
2434
+ })
2435
+ })
2436
+ ]
2437
+ }),
2438
+ /* @__PURE__ */ jsx(Popover$1, {
2439
+ isNonModal: Boolean(container),
2440
+ ref: panelRef,
2441
+ UNSTABLE_portalContainer: container ?? void 0,
2442
+ className: `${prefix}__panel`,
2443
+ offset: 4,
2444
+ children: /* @__PURE__ */ jsxs(CalendarDialog, {
2445
+ id: `${inputId}-panel`,
2446
+ ariaLabel: strings.selectDate,
2447
+ children: [/* @__PURE__ */ jsx(Calendar, { children: /* @__PURE__ */ jsx(CalendarContent, {}) }), /* @__PURE__ */ jsxs("div", {
2448
+ className: `${prefix}__footer`,
2449
+ children: [/* @__PURE__ */ jsx(Button$1, {
2450
+ slot: null,
2451
+ className: `${prefix}__text-button`,
2452
+ onPress: () => {
2453
+ change("");
2454
+ setOpen(false);
2455
+ },
2350
2456
  children: strings.clear
2351
- }), /* @__PURE__ */ jsx("button", {
2352
- type: "button",
2353
- className: "nb-date-picker__text-button",
2354
- onClick: handleToday,
2457
+ }), /* @__PURE__ */ jsx(Button$1, {
2458
+ slot: null,
2459
+ className: `${prefix}__text-button`,
2460
+ isDisabled: !dateAllowed(todayIso, min, max),
2461
+ onPress: () => {
2462
+ change(todayIso);
2463
+ setOpen(false);
2464
+ },
2355
2465
  children: strings.today
2356
2466
  })]
2357
- })
2358
- ] }),
2359
- viewMode === "months" && /* @__PURE__ */ jsxs(Fragment, { children: [
2360
- /* @__PURE__ */ jsxs("div", {
2361
- className: "nb-date-picker__header",
2362
- children: [
2363
- /* @__PURE__ */ jsx("button", {
2364
- type: "button",
2365
- className: "nb-date-picker__nav",
2366
- "aria-label": strings.previousYear,
2367
- onClick: () => setMonth((m) => new Date(m.getFullYear() - 1, m.getMonth(), 1)),
2368
- children: /* @__PURE__ */ jsx("i", {
2369
- className: "ph ph-caret-left",
2370
- "aria-hidden": "true"
2371
- })
2372
- }),
2373
- /* @__PURE__ */ jsxs("button", {
2374
- type: "button",
2375
- className: "nb-date-picker__month nb-date-picker__month--clickable",
2376
- "aria-label": strings.selectYear,
2377
- onClick: () => {
2378
- setYearRangeStart(getYearRangeStart(month.getFullYear()));
2379
- setViewMode("years");
2380
- },
2381
- children: [month.getFullYear(), /* @__PURE__ */ jsx("i", {
2382
- className: "ph ph-caret-down nb-date-picker__month-caret",
2383
- "aria-hidden": "true"
2384
- })]
2385
- }),
2386
- /* @__PURE__ */ jsx("button", {
2387
- type: "button",
2388
- className: "nb-date-picker__nav",
2389
- "aria-label": strings.nextYear,
2390
- onClick: () => setMonth((m) => new Date(m.getFullYear() + 1, m.getMonth(), 1)),
2391
- children: /* @__PURE__ */ jsx("i", {
2392
- className: "ph ph-caret-right",
2393
- "aria-hidden": "true"
2394
- })
2395
- })
2396
- ]
2397
- }),
2398
- /* @__PURE__ */ jsx("div", {
2399
- className: "nb-date-picker__months-grid",
2400
- role: "grid",
2401
- "aria-label": `${month.getFullYear()}`,
2402
- children: monthLabels.map((label, i) => {
2403
- const isSelected = selectedDate ? selectedDate.getMonth() === i && selectedDate.getFullYear() === month.getFullYear() : false;
2404
- const isCurrent = (/* @__PURE__ */ new Date()).getMonth() === i && (/* @__PURE__ */ new Date()).getFullYear() === month.getFullYear();
2405
- return /* @__PURE__ */ jsx("button", {
2406
- type: "button",
2407
- className: cx$1("nb-date-picker__month-cell", isSelected && "nb-date-picker__month-cell--selected", isCurrent && "nb-date-picker__month-cell--current"),
2408
- role: "gridcell",
2409
- "aria-selected": isSelected,
2410
- onClick: () => handleMonthSelect(i),
2411
- children: label
2412
- }, i);
2413
- })
2414
- }),
2415
- /* @__PURE__ */ jsx("div", {
2416
- className: "nb-date-picker__footer",
2417
- children: /* @__PURE__ */ jsxs("button", {
2418
- type: "button",
2419
- className: "nb-date-picker__text-button",
2420
- onClick: () => setViewMode("days"),
2421
- children: [
2422
- /* @__PURE__ */ jsx("i", {
2423
- className: "ph ph-arrow-left",
2424
- "aria-hidden": "true"
2425
- }),
2426
- " ",
2427
- strings.back
2428
- ]
2429
- })
2430
- })
2431
- ] }),
2432
- viewMode === "years" && /* @__PURE__ */ jsxs(Fragment, { children: [
2433
- /* @__PURE__ */ jsxs("div", {
2434
- className: "nb-date-picker__header",
2435
- children: [
2436
- /* @__PURE__ */ jsx("button", {
2437
- type: "button",
2438
- className: "nb-date-picker__nav",
2439
- "aria-label": strings.previousYears,
2440
- onClick: () => setYearRangeStart((y) => y - 12),
2441
- children: /* @__PURE__ */ jsx("i", {
2442
- className: "ph ph-caret-left",
2443
- "aria-hidden": "true"
2444
- })
2445
- }),
2446
- /* @__PURE__ */ jsxs("div", {
2447
- className: "nb-date-picker__month",
2448
- children: [
2449
- yearRangeStart,
2450
- "–",
2451
- yearRangeStart + 11
2452
- ]
2453
- }),
2454
- /* @__PURE__ */ jsx("button", {
2455
- type: "button",
2456
- className: "nb-date-picker__nav",
2457
- "aria-label": strings.nextYears,
2458
- onClick: () => setYearRangeStart((y) => y + 12),
2459
- children: /* @__PURE__ */ jsx("i", {
2460
- className: "ph ph-caret-right",
2461
- "aria-hidden": "true"
2462
- })
2463
- })
2464
- ]
2465
- }),
2466
- /* @__PURE__ */ jsx("div", {
2467
- className: "nb-date-picker__years-grid",
2468
- role: "grid",
2469
- "aria-label": `${yearRangeStart}–${yearRangeStart + 11}`,
2470
- children: Array.from({ length: 12 }, (_, i) => yearRangeStart + i).map((year) => {
2471
- const isSelected = selectedDate ? selectedDate.getFullYear() === year : false;
2472
- const isCurrent = (/* @__PURE__ */ new Date()).getFullYear() === year;
2473
- return /* @__PURE__ */ jsx("button", {
2474
- type: "button",
2475
- className: cx$1("nb-date-picker__year-cell", isSelected && "nb-date-picker__year-cell--selected", isCurrent && "nb-date-picker__year-cell--current"),
2476
- role: "gridcell",
2477
- "aria-selected": isSelected,
2478
- onClick: () => handleYearSelect(year),
2479
- children: year
2480
- }, year);
2481
- })
2482
- }),
2483
- /* @__PURE__ */ jsx("div", {
2484
- className: "nb-date-picker__footer",
2485
- children: /* @__PURE__ */ jsxs("button", {
2486
- type: "button",
2487
- className: "nb-date-picker__text-button",
2488
- onClick: () => setViewMode("months"),
2489
- children: [
2490
- /* @__PURE__ */ jsx("i", {
2491
- className: "ph ph-arrow-left",
2492
- "aria-hidden": "true"
2493
- }),
2494
- " ",
2495
- strings.back
2496
- ]
2497
- })
2498
- })
2499
- ] })
2500
- ]
2501
- }), document.body)
2502
- ]
2467
+ })]
2468
+ })
2469
+ })
2470
+ ]
2471
+ })
2503
2472
  });
2504
2473
  });
2505
2474
  //#endregion
2506
2475
  //#region packages/ui/DateRangePicker.tsx
2507
- /**
2508
- * DateRangePicker — enterprise date range selector.
2509
- *
2510
- * A single trigger with two text inputs (start + end) sharing one calendar
2511
- * panel. Supports hover-preview, range highlighting, keyboard entry, min/max
2512
- * constraints, and full density/theme token compliance.
2513
- *
2514
- * Usage:
2515
- * <DateRangePicker
2516
- * startValue="2026-06-01"
2517
- * endValue="2026-06-30"
2518
- * onChange={(start, end) => ...}
2519
- * />
2520
- */
2521
- const ISO_DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
2522
- const pad = (v) => String(v).padStart(2, "0");
2523
- const toIsoDate = (d) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
2524
- const parseIsoDate = (value) => {
2525
- if (!value || !ISO_DATE_RE.test(value)) return null;
2526
- const [year, month, day] = value.split("-").map(Number);
2527
- const d = new Date(year, month - 1, day);
2528
- if (d.getFullYear() !== year || d.getMonth() !== month - 1 || d.getDate() !== day) return null;
2529
- return d;
2530
- };
2531
- const cx = (...vals) => vals.filter(Boolean).join(" ");
2532
- const getLocale = (override) => override || document.documentElement.lang || navigator.language || "en-US";
2533
- const startOfMonth = (date) => new Date(date.getFullYear(), date.getMonth(), 1);
2534
- const addMonths = (date, months) => new Date(date.getFullYear(), date.getMonth() + months, 1);
2535
- const formatDisplayDate = (value, locale) => {
2536
- const date = parseIsoDate(value);
2537
- if (!date) return "";
2538
- return new Intl.DateTimeFormat(getLocale(locale), {
2539
- day: "2-digit",
2540
- month: "2-digit",
2541
- year: "numeric"
2542
- }).format(date);
2543
- };
2544
- const formatMonthLabel = (date, locale) => new Intl.DateTimeFormat(getLocale(locale), {
2545
- month: "long",
2546
- year: "numeric"
2547
- }).format(date);
2548
- const buildCalendarDays = (month, min, max, locale) => {
2549
- const first = startOfMonth(month);
2550
- const firstDayOfWeek = getFirstDayOfWeek(locale);
2551
- const offset = (first.getDay() - firstDayOfWeek + 7) % 7;
2552
- const minDate = parseIsoDate(min);
2553
- const maxDate = parseIsoDate(max);
2554
- const start = new Date(first);
2555
- start.setDate(first.getDate() - offset);
2556
- return Array.from({ length: 42 }, (_, i) => {
2557
- const date = new Date(start);
2558
- date.setDate(start.getDate() + i);
2559
- return {
2560
- date,
2561
- iso: toIsoDate(date),
2562
- inCurrentMonth: date.getMonth() === month.getMonth(),
2563
- disabled: Boolean(minDate && date < minDate || maxDate && date > maxDate)
2564
- };
2565
- });
2566
- };
2567
- const getDayRoleInRange = (iso, startIso, endIso) => {
2568
- if (!startIso) return "none";
2569
- if (!endIso || startIso === endIso) return iso === startIso ? "single" : "none";
2570
- if (iso === startIso) return "start";
2571
- if (iso === endIso) return "end";
2572
- if (iso > startIso && iso < endIso) return "in-range";
2573
- return "none";
2574
- };
2575
- function DateRangePicker({ startValue, endValue, placeholder = "dd/mm/yyyy", disabled = false, readOnly = false, required = false, invalid = false, locale, min, max, className, ariaLabel, onChange, onBlur }) {
2576
- const startId = useId();
2577
- const endId = useId();
2476
+ function DateRangePicker({ startValue, endValue, placeholder, disabled = false, clearable = true, readOnly = false, required = false, invalid = false, locale, min, max, className, ariaLabel, onChange, onBlur }) {
2477
+ const { container, groupRef, panelRef, open, setOpen } = useCalendarPopover();
2578
2478
  const strings = useUiStrings();
2579
- const resolvedLocale = getLocale(locale);
2580
- const startDisplay = formatDisplayDate(startValue, resolvedLocale);
2581
- const endDisplay = formatDisplayDate(endValue, resolvedLocale);
2582
- const startIso = parseIsoDate(startValue) ? startValue : null;
2583
- const endIso = parseIsoDate(endValue) ? endValue : null;
2584
- const [phase, setPhase] = useState("idle");
2585
- const [pendingStart, setPendingStart] = useState(null);
2586
- const [hoverIso, setHoverIso] = useState(null);
2587
- const [month, setMonth] = useState(() => startOfMonth(parseIsoDate(startValue) ?? /* @__PURE__ */ new Date()));
2588
- const [startText, setStartText] = useState("");
2589
- const [endText, setEndText] = useState("");
2590
- const [editingField, setEditingField] = useState(null);
2591
- const triggerRef = useRef(null);
2592
- const startInputRef = useRef(null);
2593
- const endInputRef = useRef(null);
2594
- const days = useMemo(() => buildCalendarDays(month, min, max, resolvedLocale), [
2595
- month,
2479
+ const resolvedLocale = getDateLocale(locale);
2480
+ const start = calendarDate(startValue);
2481
+ const end = calendarDate(endValue);
2482
+ const change = (a, b) => a && b && a > b ? onChange?.(b, a) : onChange?.(a, b);
2483
+ const todayIso = today(getLocalTimeZone()).toString();
2484
+ const prefix = "nb-date-range-picker";
2485
+ const inputProps = {
2486
+ locale: resolvedLocale,
2596
2487
  min,
2597
2488
  max,
2598
- resolvedLocale
2599
- ]);
2600
- const weekdayLbls = useMemo(() => weekDayLabels(resolvedLocale), [resolvedLocale]);
2601
- const todayIso = toIsoDate(/* @__PURE__ */ new Date());
2602
- useEffect(() => {
2603
- const anchor = parseIsoDate(startValue) ?? parseIsoDate(endValue);
2604
- if (anchor) setMonth(startOfMonth(anchor));
2605
- }, [startValue]);
2606
- const { open, setOpen, containerRef: rootRef, panelRef, panelStyle } = useFloatingPanel({
2607
- onClose: () => {
2608
- setPhase("idle");
2609
- setPendingStart(null);
2610
- setHoverIso(null);
2611
- },
2612
- onEscape: (e) => {
2613
- e.preventDefault();
2614
- startInputRef.current?.focus();
2615
- },
2616
- computeStyle: () => {
2617
- const rect = triggerRef.current?.getBoundingClientRect();
2618
- if (!rect) return null;
2619
- const panelWidth = panelRef.current?.offsetWidth ?? 296;
2620
- const left = Math.min(Math.max(8, rect.left), window.innerWidth - panelWidth - 8);
2621
- const top = Math.min(rect.bottom + 6, window.innerHeight - 380);
2622
- return {
2623
- left,
2624
- top: Math.max(8, top)
2625
- };
2626
- }
2627
- });
2628
- const closePanel = useCallback(() => {
2629
- setOpen(false);
2630
- }, [setOpen]);
2631
- const commitRange = useCallback((start, end) => {
2632
- const [a, b] = start <= end ? [start, end] : [end, start];
2633
- onChange?.(a, b);
2634
- closePanel();
2635
- window.setTimeout(() => startInputRef.current?.focus());
2636
- }, [onChange, closePanel]);
2637
- const handleDayClick = useCallback((iso) => {
2638
- if (phase === "idle") {
2639
- setPendingStart(iso);
2640
- setPhase("selecting-end");
2641
- } else commitRange(pendingStart ?? iso, iso);
2642
- }, [
2643
- phase,
2644
- pendingStart,
2645
- commitRange
2646
- ]);
2647
- const getEffectiveRange = () => {
2648
- if (phase === "selecting-end" && pendingStart) {
2649
- const effectiveEnd = hoverIso ?? null;
2650
- return {
2651
- effectiveStart: pendingStart <= (effectiveEnd ?? pendingStart) ? pendingStart : effectiveEnd,
2652
- effectiveEnd: pendingStart <= (effectiveEnd ?? pendingStart) ? effectiveEnd : pendingStart
2653
- };
2654
- }
2655
- return {
2656
- effectiveStart: startIso,
2657
- effectiveEnd: endIso
2658
- };
2659
- };
2660
- const { effectiveStart, effectiveEnd } = getEffectiveRange();
2661
- const handleStartFocus = () => {
2662
- setEditingField("start");
2663
- setStartText(startDisplay);
2664
- window.setTimeout(() => startInputRef.current?.select(), 0);
2665
- };
2666
- const handleEndFocus = () => {
2667
- setEditingField("end");
2668
- setEndText(endDisplay);
2669
- window.setTimeout(() => endInputRef.current?.select(), 0);
2670
- };
2671
- const handleStartChange = (e) => {
2672
- if (readOnly || disabled) return;
2673
- setStartText(applyDateMask(e.target.value, startText));
2674
- };
2675
- const handleEndChange = (e) => {
2676
- if (readOnly || disabled) return;
2677
- setEndText(applyDateMask(e.target.value, endText));
2678
- };
2679
- const commitTextInput = (field, text) => {
2680
- const parsed = parseDisplayDate(text, resolvedLocale);
2681
- if (parsed !== null) {
2682
- const newStart = field === "start" ? parsed : startIso ?? "";
2683
- const newEnd = field === "end" ? parsed : endIso ?? "";
2684
- if (newStart && newEnd) {
2685
- const [a, b] = newStart <= newEnd ? [newStart, newEnd] : [newEnd, newStart];
2686
- onChange?.(a, b);
2687
- } else if (field === "start") onChange?.(parsed, endIso ?? "");
2688
- else onChange?.(startIso ?? "", parsed);
2689
- } else if (text === "") {
2690
- if (field === "start") onChange?.("", endIso ?? "");
2691
- else onChange?.(startIso ?? "", "");
2692
- }
2693
- };
2694
- const handleStartBlur = (e) => {
2695
- const related = e.relatedTarget;
2696
- if (rootRef.current?.contains(related) || panelRef.current?.contains(related)) return;
2697
- commitTextInput("start", startText);
2698
- setEditingField(null);
2699
- setStartText("");
2700
- onBlur?.(e);
2701
- };
2702
- const handleEndBlur = (e) => {
2703
- const related = e.relatedTarget;
2704
- if (rootRef.current?.contains(related) || panelRef.current?.contains(related)) return;
2705
- commitTextInput("end", endText);
2706
- setEditingField(null);
2707
- setEndText("");
2708
- onBlur?.(e);
2709
- };
2710
- const handleStartKeyDown = (e) => {
2711
- if (e.key === "Enter") {
2712
- e.preventDefault();
2713
- const parsed = parseDisplayDate(startText);
2714
- if (parsed) onChange?.(parsed, endIso ?? "");
2715
- endInputRef.current?.focus();
2716
- } else if (e.key === "ArrowDown" || e.key === "F4") {
2717
- e.preventDefault();
2718
- if (!readOnly && !disabled) setOpen(true);
2719
- }
2720
- };
2721
- const handleEndKeyDown = (e) => {
2722
- if (e.key === "Enter") {
2723
- e.preventDefault();
2724
- const parsed = parseDisplayDate(endText);
2725
- if (parsed) onChange?.(startIso ?? "", parsed);
2726
- } else if (e.key === "ArrowDown" || e.key === "F4") {
2727
- e.preventDefault();
2728
- if (!readOnly && !disabled) setOpen(true);
2489
+ placeholder: placeholder ?? datePlaceholder(resolvedLocale),
2490
+ disabled,
2491
+ readOnly,
2492
+ required,
2493
+ "aria-invalid": invalid || void 0,
2494
+ className: `${prefix}__input`,
2495
+ onOpen: () => setOpen(true),
2496
+ onBlur,
2497
+ onKeyDown: (event) => {
2498
+ if (event.key === "Escape" && open) {
2499
+ event.stopPropagation();
2500
+ setOpen(false);
2501
+ }
2729
2502
  }
2730
2503
  };
2731
- const handleCalendarPointerDown = (e) => {
2732
- e.preventDefault();
2733
- if (readOnly || disabled) return;
2734
- setOpen(!open);
2735
- };
2736
- const handleClear = (e) => {
2737
- e.preventDefault();
2738
- onChange?.("", "");
2739
- closePanel();
2740
- };
2741
- return /* @__PURE__ */ jsxs("div", {
2742
- ref: rootRef,
2743
- className: cx("nb-date-range-picker", className),
2744
- children: [
2745
- /* @__PURE__ */ jsxs("div", {
2746
- ref: triggerRef,
2747
- className: cx("nb-date-range-picker__trigger", invalid && "nb-date-range-picker__trigger--invalid", readOnly && "nb-date-range-picker__trigger--readonly", open && "nb-date-range-picker__trigger--open", disabled && "nb-date-range-picker__trigger--disabled"),
2748
- "aria-label": ariaLabel,
2504
+ return /* @__PURE__ */ jsx(I18nProvider, {
2505
+ locale: resolvedLocale,
2506
+ children: /* @__PURE__ */ jsxs(DateRangePicker$1, {
2507
+ "aria-label": ariaLabel ?? strings.selectDateRange,
2508
+ value: start && end && start.compare(end) <= 0 ? {
2509
+ start,
2510
+ end
2511
+ } : null,
2512
+ onChange: (range) => change(range?.start.toString() ?? "", range?.end.toString() ?? ""),
2513
+ minValue: calendarDate(min) ?? void 0,
2514
+ maxValue: calendarDate(max) ?? void 0,
2515
+ placeholderValue: start ?? end ?? void 0,
2516
+ isDisabled: disabled,
2517
+ isReadOnly: readOnly,
2518
+ isRequired: required,
2519
+ isInvalid: invalid,
2520
+ validationBehavior: "aria",
2521
+ isOpen: open,
2522
+ onOpenChange: setOpen,
2523
+ className: [prefix, className].filter(Boolean).join(" "),
2524
+ children: [/* @__PURE__ */ jsxs(Group, {
2525
+ ref: groupRef,
2526
+ className: [
2527
+ `${prefix}__trigger`,
2528
+ disabled && `${prefix}__trigger--disabled`,
2529
+ readOnly && `${prefix}__trigger--readonly`,
2530
+ invalid && `${prefix}__trigger--invalid`,
2531
+ open && `${prefix}__trigger--open`
2532
+ ].filter(Boolean).join(" "),
2749
2533
  children: [
2750
- /* @__PURE__ */ jsx("input", {
2751
- ref: startInputRef,
2752
- id: startId,
2753
- type: "text",
2754
- inputMode: "numeric",
2755
- className: cx("nb-date-range-picker__input", !editingField && !startDisplay && "nb-date-range-picker__input--placeholder"),
2756
- value: editingField === "start" ? startText : startDisplay,
2757
- placeholder,
2758
- disabled,
2759
- readOnly,
2760
- autoComplete: "off",
2761
- "aria-label": `Fecha inicio${ariaLabel ? ` ${ariaLabel}` : ""}`,
2762
- "aria-required": required || void 0,
2763
- onFocus: handleStartFocus,
2764
- onBlur: handleStartBlur,
2765
- onChange: handleStartChange,
2766
- onKeyDown: handleStartKeyDown
2534
+ /* @__PURE__ */ jsx(DateTextInput, {
2535
+ ...inputProps,
2536
+ "aria-label": [strings.startDate, ariaLabel].filter(Boolean).join(" "),
2537
+ value: startValue,
2538
+ onChange: (next) => change(next, endValue ?? "")
2767
2539
  }),
2768
2540
  /* @__PURE__ */ jsx("span", {
2769
- className: "nb-date-range-picker__sep",
2541
+ className: `${prefix}__sep`,
2770
2542
  "aria-hidden": "true",
2771
- children: /* @__PURE__ */ jsx("i", { className: "ph ph-arrow-right" })
2543
+ children: "→"
2772
2544
  }),
2773
- /* @__PURE__ */ jsx("input", {
2774
- ref: endInputRef,
2775
- id: endId,
2776
- type: "text",
2777
- inputMode: "numeric",
2778
- className: cx("nb-date-range-picker__input", !editingField && !endDisplay && "nb-date-range-picker__input--placeholder"),
2779
- value: editingField === "end" ? endText : endDisplay,
2780
- placeholder,
2781
- disabled,
2782
- readOnly,
2783
- autoComplete: "off",
2784
- "aria-label": `Fecha fin${ariaLabel ? ` ${ariaLabel}` : ""}`,
2785
- onFocus: handleEndFocus,
2786
- onBlur: handleEndBlur,
2787
- onChange: handleEndChange,
2788
- onKeyDown: handleEndKeyDown
2545
+ /* @__PURE__ */ jsx(DateTextInput, {
2546
+ ...inputProps,
2547
+ "aria-label": [strings.endDate, ariaLabel].filter(Boolean).join(" "),
2548
+ value: endValue,
2549
+ onChange: (next) => change(startValue ?? "", next)
2789
2550
  }),
2790
- /* @__PURE__ */ jsxs("span", {
2791
- className: "nb-date-range-picker__icons",
2792
- children: [(startDisplay || endDisplay) && !disabled && !readOnly && /* @__PURE__ */ jsx("span", {
2793
- role: "button",
2794
- tabIndex: -1,
2795
- className: "nb-date-range-picker__clear",
2796
- "aria-label": strings.clearDateRange,
2797
- onPointerDown: handleClear,
2798
- children: /* @__PURE__ */ jsx("i", {
2799
- className: "ph ph-x",
2800
- "aria-hidden": "true"
2801
- })
2802
- }), /* @__PURE__ */ jsx("span", {
2803
- role: "button",
2804
- tabIndex: -1,
2805
- className: "nb-date-range-picker__calendar-btn",
2806
- "aria-label": strings.openCalendar,
2807
- onPointerDown: handleCalendarPointerDown,
2808
- children: /* @__PURE__ */ jsx("i", {
2809
- className: "ph ph-calendar-blank",
2810
- "aria-hidden": "true"
2811
- })
2812
- })]
2551
+ clearable && (startValue || endValue) && !disabled && !readOnly && /* @__PURE__ */ jsx(Button$1, {
2552
+ slot: null,
2553
+ className: `${prefix}__clear`,
2554
+ "aria-label": strings.clearDateRange,
2555
+ onPress: () => change("", ""),
2556
+ children: "×"
2557
+ }),
2558
+ /* @__PURE__ */ jsx(Button$1, {
2559
+ className: `${prefix}__calendar-btn`,
2560
+ "aria-label": strings.openCalendar,
2561
+ onPress: () => groupRef.current?.querySelector("input")?.focus(),
2562
+ isDisabled: disabled || readOnly,
2563
+ children: /* @__PURE__ */ jsx("i", {
2564
+ "aria-hidden": "true",
2565
+ className: "ph ph-calendar-blank"
2566
+ })
2813
2567
  })
2814
2568
  ]
2815
- }),
2816
- phase === "selecting-end" && /* @__PURE__ */ jsx("div", {
2817
- className: "nb-date-range-picker__hint",
2818
- role: "status",
2819
- "aria-live": "polite",
2820
- children: "Selecciona la fecha de fin"
2821
- }),
2822
- open && createPortal(/* @__PURE__ */ jsxs("div", {
2569
+ }), /* @__PURE__ */ jsx(Popover$1, {
2570
+ isNonModal: Boolean(container),
2823
2571
  ref: panelRef,
2824
- className: "nb-date-range-picker__panel",
2825
- role: "dialog",
2826
- "aria-label": strings.selectDateRange,
2827
- style: panelStyle,
2828
- children: [
2829
- /* @__PURE__ */ jsxs("div", {
2830
- className: "nb-date-range-picker__header",
2831
- children: [
2832
- /* @__PURE__ */ jsx("button", {
2833
- type: "button",
2834
- className: "nb-date-range-picker__nav",
2835
- "aria-label": strings.previousMonth,
2836
- onClick: () => setMonth((m) => addMonths(m, -1)),
2837
- children: /* @__PURE__ */ jsx("i", {
2838
- className: "ph ph-caret-left",
2839
- "aria-hidden": "true"
2840
- })
2841
- }),
2842
- /* @__PURE__ */ jsx("div", {
2843
- className: "nb-date-range-picker__month",
2844
- "aria-live": "polite",
2845
- children: formatMonthLabel(month, resolvedLocale)
2846
- }),
2847
- /* @__PURE__ */ jsx("button", {
2848
- type: "button",
2849
- className: "nb-date-range-picker__nav",
2850
- "aria-label": strings.nextMonth,
2851
- onClick: () => setMonth((m) => addMonths(m, 1)),
2852
- children: /* @__PURE__ */ jsx("i", {
2853
- className: "ph ph-caret-right",
2854
- "aria-hidden": "true"
2855
- })
2856
- })
2857
- ]
2858
- }),
2859
- /* @__PURE__ */ jsx("div", {
2860
- className: "nb-date-range-picker__weekdays",
2861
- "aria-hidden": "true",
2862
- children: weekdayLbls.map((label, i) => /* @__PURE__ */ jsx("span", { children: label }, `${label}-${i}`))
2863
- }),
2864
- phase === "selecting-end" && /* @__PURE__ */ jsxs("div", {
2865
- className: "nb-date-range-picker__phase-banner",
2866
- children: [/* @__PURE__ */ jsx("i", {
2867
- className: "ph ph-info",
2868
- "aria-hidden": "true"
2869
- }), "Ahora selecciona la fecha de fin"]
2870
- }),
2871
- /* @__PURE__ */ jsx("div", {
2872
- className: "nb-date-range-picker__days",
2873
- role: "grid",
2874
- "aria-label": formatMonthLabel(month, resolvedLocale),
2875
- children: days.map((day) => {
2876
- const role = getDayRoleInRange(day.iso, effectiveStart, effectiveEnd);
2877
- return /* @__PURE__ */ jsx("button", {
2878
- type: "button",
2879
- className: cx("nb-date-range-picker__day", !day.inCurrentMonth && "nb-date-range-picker__day--muted", day.iso === todayIso && "nb-date-range-picker__day--today", role === "start" && "nb-date-range-picker__day--range-start", role === "end" && "nb-date-range-picker__day--range-end", role === "in-range" && "nb-date-range-picker__day--in-range", role === "single" && "nb-date-range-picker__day--range-single", phase === "selecting-end" && "nb-date-range-picker__day--selecting"),
2880
- disabled: day.disabled,
2881
- role: "gridcell",
2882
- "aria-selected": role !== "none",
2883
- onMouseEnter: () => phase === "selecting-end" && setHoverIso(day.iso),
2884
- onMouseLeave: () => phase === "selecting-end" && setHoverIso(null),
2885
- onClick: () => !day.disabled && handleDayClick(day.iso),
2886
- children: /* @__PURE__ */ jsx("span", {
2887
- className: "nb-date-range-picker__day-inner",
2888
- children: day.date.getDate()
2889
- })
2890
- }, day.iso);
2891
- })
2892
- }),
2893
- /* @__PURE__ */ jsxs("div", {
2894
- className: "nb-date-range-picker__footer",
2895
- children: [/* @__PURE__ */ jsx("button", {
2896
- type: "button",
2897
- className: "nb-date-range-picker__text-button",
2898
- onClick: () => {
2899
- onChange?.("", "");
2900
- closePanel();
2572
+ UNSTABLE_portalContainer: container ?? void 0,
2573
+ className: `${prefix}__panel`,
2574
+ offset: 4,
2575
+ children: /* @__PURE__ */ jsxs(CalendarDialog, {
2576
+ ariaLabel: strings.selectDateRange,
2577
+ children: [/* @__PURE__ */ jsx(RangeCalendar, {
2578
+ className: "nb-calendar--range",
2579
+ children: /* @__PURE__ */ jsx(CalendarContent, {})
2580
+ }), /* @__PURE__ */ jsxs("div", {
2581
+ className: `${prefix}__footer`,
2582
+ children: [/* @__PURE__ */ jsx(Button$1, {
2583
+ slot: null,
2584
+ className: `${prefix}__text-button`,
2585
+ onPress: () => {
2586
+ change("", "");
2587
+ setOpen(false);
2901
2588
  },
2902
2589
  children: strings.clear
2903
- }), phase === "selecting-end" ? /* @__PURE__ */ jsx("button", {
2904
- type: "button",
2905
- className: "nb-date-range-picker__text-button",
2906
- onClick: () => {
2907
- setPendingStart(null);
2908
- setPhase("idle");
2909
- setHoverIso(null);
2910
- },
2911
- children: strings.cancel
2912
- }) : /* @__PURE__ */ jsx("button", {
2913
- type: "button",
2914
- className: "nb-date-range-picker__text-button",
2915
- onClick: () => {
2916
- const today = toIsoDate(/* @__PURE__ */ new Date());
2917
- setMonth(startOfMonth(/* @__PURE__ */ new Date()));
2918
- if (!startIso) onChange?.(today, endIso ?? "");
2919
- else if (!endIso) onChange?.(startIso, today);
2920
- else onChange?.(today, today);
2921
- closePanel();
2590
+ }), /* @__PURE__ */ jsx(Button$1, {
2591
+ slot: null,
2592
+ className: `${prefix}__text-button`,
2593
+ isDisabled: !dateAllowed(todayIso, min, max),
2594
+ onPress: () => {
2595
+ change(todayIso, todayIso);
2596
+ setOpen(false);
2922
2597
  },
2923
2598
  children: strings.today
2924
2599
  })]
2925
- })
2926
- ]
2927
- }), document.body)
2928
- ]
2600
+ })]
2601
+ })
2602
+ })]
2603
+ })
2929
2604
  });
2930
2605
  }
2931
2606
  //#endregion
2932
2607
  //#region packages/ui/Popover.tsx
2933
2608
  const Popover = ({ trigger, panel, align = "end", ariaLabel, className }) => {
2934
- const { open, setOpen, toggle, containerRef } = useFloatingPanel();
2935
- return /* @__PURE__ */ jsxs("div", {
2936
- ref: containerRef,
2937
- className: [
2938
- "nb-popover",
2939
- `nb-popover--${align}`,
2940
- open && "nb-popover--open",
2941
- className
2942
- ].filter(Boolean).join(" "),
2943
- children: [trigger({
2944
- open,
2945
- toggle
2946
- }), open && /* @__PURE__ */ jsx("div", {
2947
- className: "nb-popover__panel",
2948
- role: "dialog",
2949
- "aria-label": ariaLabel,
2950
- children: panel({ close: () => setOpen(false) })
2951
- })]
2609
+ const [open, setOpen] = useState(false);
2610
+ const triggerRef = useRef(null);
2611
+ const [restoreFocus, setRestoreFocus] = useState(true);
2612
+ const changeOpen = (next) => {
2613
+ setRestoreFocus(true);
2614
+ setOpen(next);
2615
+ };
2616
+ const container = useOverlayContainer();
2617
+ const triggerNode = trigger({
2618
+ open,
2619
+ toggle: () => changeOpen(!open)
2620
+ });
2621
+ return /* @__PURE__ */ jsx(Popover$2.Root, {
2622
+ open,
2623
+ onOpenChange: (next, details) => {
2624
+ setRestoreFocus(details.reason !== "outside-press" && details.reason !== "focus-out");
2625
+ setOpen(next);
2626
+ },
2627
+ onOpenChangeComplete: (next) => {
2628
+ if (!next && restoreFocus) triggerRef.current?.focus({ preventScroll: true });
2629
+ },
2630
+ children: /* @__PURE__ */ jsxs("div", {
2631
+ className: [
2632
+ "nb-popover",
2633
+ `nb-popover--${align}`,
2634
+ open && "nb-popover--open",
2635
+ className
2636
+ ].filter(Boolean).join(" "),
2637
+ children: [/* @__PURE__ */ jsx(Popover$2.Trigger, {
2638
+ ref: triggerRef,
2639
+ render: isValidElement(triggerNode) ? triggerNode : /* @__PURE__ */ jsx("button", {
2640
+ type: "button",
2641
+ children: triggerNode
2642
+ })
2643
+ }), /* @__PURE__ */ jsx(Popover$2.Portal, {
2644
+ container: container ?? void 0,
2645
+ children: /* @__PURE__ */ jsx(Popover$2.Positioner, {
2646
+ align,
2647
+ sideOffset: 8,
2648
+ className: "nb-popover-positioner",
2649
+ children: /* @__PURE__ */ jsx(Popover$2.Popup, {
2650
+ finalFocus: triggerRef,
2651
+ onKeyDownCapture: (event) => {
2652
+ if (event.key === "Escape") {
2653
+ event.preventDefault();
2654
+ event.stopPropagation();
2655
+ changeOpen(false);
2656
+ }
2657
+ },
2658
+ className: "nb-popover__panel",
2659
+ "aria-label": ariaLabel,
2660
+ children: panel({ close: () => changeOpen(false) })
2661
+ })
2662
+ })
2663
+ })]
2664
+ })
2952
2665
  });
2953
2666
  };
2954
2667
  //#endregion
2668
+ //#region packages/ui/useFloatingPanel.ts
2669
+ /** Style applied to an anchored panel before its first position is computed. */
2670
+ const HIDDEN_PANEL_STYLE = {
2671
+ position: "fixed",
2672
+ visibility: "hidden",
2673
+ margin: 0
2674
+ };
2675
+ function useFloatingPanel(options = {}) {
2676
+ const [open, setOpenState] = useState(false);
2677
+ const [panelStyle, setPanelStyle] = useState(HIDDEN_PANEL_STYLE);
2678
+ const containerRef = useRef(null);
2679
+ const panelRef = useRef(null);
2680
+ const optionsRef = useRef(options);
2681
+ optionsRef.current = options;
2682
+ const anchored = !!options.computeStyle;
2683
+ const dismissEvent = options.dismissEvent ?? "pointerdown";
2684
+ const setOpen = useCallback((next) => {
2685
+ setOpenState(next);
2686
+ if (!next) optionsRef.current.onClose?.();
2687
+ optionsRef.current.onOpenChange?.(next);
2688
+ }, []);
2689
+ const applyStyle = useCallback(() => {
2690
+ const compute = optionsRef.current.computeStyle;
2691
+ if (!compute) return;
2692
+ const style = compute(containerRef.current);
2693
+ if (style) setPanelStyle(style);
2694
+ }, []);
2695
+ const openPanel = useCallback(() => {
2696
+ applyStyle();
2697
+ setOpen(true);
2698
+ }, [applyStyle, setOpen]);
2699
+ const toggle = useCallback(() => open ? setOpen(false) : openPanel(), [
2700
+ open,
2701
+ openPanel,
2702
+ setOpen
2703
+ ]);
2704
+ useEffect(() => {
2705
+ if (!open) return;
2706
+ const handleOutside = (e) => {
2707
+ const target = e.target;
2708
+ if (containerRef.current?.contains(target) || panelRef.current?.contains(target)) return;
2709
+ setOpen(false);
2710
+ };
2711
+ const handleKeyDown = (e) => {
2712
+ if (e.key !== "Escape" || e.defaultPrevented) return;
2713
+ e.preventDefault();
2714
+ e.stopPropagation();
2715
+ setOpen(false);
2716
+ optionsRef.current.onEscape?.(e);
2717
+ };
2718
+ document.addEventListener(dismissEvent, handleOutside);
2719
+ document.addEventListener("keydown", handleKeyDown, true);
2720
+ return () => {
2721
+ document.removeEventListener(dismissEvent, handleOutside);
2722
+ document.removeEventListener("keydown", handleKeyDown, true);
2723
+ };
2724
+ }, [
2725
+ dismissEvent,
2726
+ open,
2727
+ setOpen
2728
+ ]);
2729
+ useLayoutEffect(() => {
2730
+ if (!open || !anchored) return;
2731
+ const update = () => {
2732
+ const container = containerRef.current;
2733
+ if (!container) return;
2734
+ if (optionsRef.current.closeOnViewportExit) {
2735
+ const rect = container.getBoundingClientRect();
2736
+ if ((rect.width > 0 || rect.height > 0) && (rect.top >= window.innerHeight || rect.bottom <= 0)) {
2737
+ setOpen(false);
2738
+ return;
2739
+ }
2740
+ }
2741
+ applyStyle();
2742
+ };
2743
+ update();
2744
+ window.addEventListener("resize", update);
2745
+ window.addEventListener("scroll", update, {
2746
+ capture: true,
2747
+ passive: true
2748
+ });
2749
+ return () => {
2750
+ window.removeEventListener("resize", update);
2751
+ window.removeEventListener("scroll", update, { capture: true });
2752
+ };
2753
+ }, [
2754
+ anchored,
2755
+ applyStyle,
2756
+ open,
2757
+ setOpen
2758
+ ]);
2759
+ return {
2760
+ open,
2761
+ setOpen,
2762
+ toggle,
2763
+ openPanel,
2764
+ containerRef,
2765
+ panelRef,
2766
+ panelStyle
2767
+ };
2768
+ }
2769
+ //#endregion
2955
2770
  //#region packages/ui/Drawer.tsx
2956
2771
  const formatWidth = (value) => {
2957
2772
  if (value === void 0) return void 0;
2958
2773
  return typeof value === "number" ? `${value}px` : value;
2959
2774
  };
2960
- const Drawer = ({ isOpen, onClose, title, width, side = "right", scrim = "subtle", children, footer, closeLabel, scrimLabel, className, "aria-label": ariaLabel }) => {
2775
+ const Drawer = ({ isOpen, busy = false, onClose, title, width, side = "right", scrim = "subtle", children, footer, closeLabel, scrimLabel, className, "aria-label": ariaLabel }) => {
2961
2776
  const strings = useUiStrings();
2962
2777
  const resolvedCloseLabel = closeLabel ?? strings.close;
2963
2778
  const resolvedScrimLabel = scrimLabel ?? strings.closePanel;
2964
2779
  const titleId = useId();
2965
- const panelRef = useRef(null);
2966
- const lastFocusRef = useRef(null);
2967
- useEffect(() => {
2968
- if (!isOpen) return;
2969
- lastFocusRef.current = document.activeElement;
2970
- const timer = window.setTimeout(() => {
2971
- (panelRef.current?.querySelector("button:not(:disabled), [href], input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex=\"-1\"])"))?.focus();
2972
- });
2973
- return () => {
2974
- clearTimeout(timer);
2975
- lastFocusRef.current?.focus?.();
2976
- };
2977
- }, [isOpen]);
2978
- useEffect(() => {
2979
- if (!isOpen) return;
2980
- const handler = (e) => {
2981
- if (e.key === "Escape") {
2982
- e.preventDefault();
2983
- onClose();
2984
- }
2985
- };
2986
- document.addEventListener("keydown", handler);
2987
- return () => document.removeEventListener("keydown", handler);
2988
- }, [isOpen, onClose]);
2989
- return createPortal(/* @__PURE__ */ jsxs("div", {
2990
- className: [
2780
+ return /* @__PURE__ */ jsxs(ModalSurface, {
2781
+ open: isOpen,
2782
+ onClose,
2783
+ closeOnEscape: !busy,
2784
+ closeOnOutsideClick: !busy,
2785
+ rootClassName: [
2991
2786
  "nb-drawer-root",
2992
2787
  isOpen && "nb-drawer-root--open",
2993
2788
  `nb-drawer-root--${side}`
2994
2789
  ].filter(Boolean).join(" "),
2995
- "aria-hidden": !isOpen,
2996
- style: { pointerEvents: isOpen ? void 0 : "none" },
2997
- children: [/* @__PURE__ */ jsx("button", {
2998
- className: `nb-drawer__scrim nb-drawer__scrim--${scrim}`,
2999
- type: "button",
3000
- "aria-label": resolvedScrimLabel,
3001
- tabIndex: -1,
3002
- onClick: onClose
3003
- }), /* @__PURE__ */ jsxs("aside", {
3004
- ref: panelRef,
3005
- className: ["nb-drawer", className].filter(Boolean).join(" "),
3006
- role: "dialog",
3007
- "aria-modal": "false",
3008
- "aria-labelledby": title ? titleId : void 0,
3009
- "aria-label": !title ? ariaLabel : void 0,
3010
- style: { width: formatWidth(width) },
3011
- children: [
3012
- title !== void 0 && /* @__PURE__ */ jsxs("header", {
3013
- className: "nb-drawer__header",
3014
- children: [/* @__PURE__ */ jsx("h2", {
3015
- className: "nb-drawer__title",
3016
- id: titleId,
3017
- children: title
3018
- }), /* @__PURE__ */ jsx(IconButton, {
3019
- className: "nb-drawer__close",
3020
- icon: "ph ph-x",
3021
- label: resolvedCloseLabel,
3022
- onClick: onClose
3023
- })]
3024
- }),
3025
- /* @__PURE__ */ jsx("div", {
3026
- className: "nb-drawer__body",
3027
- children
3028
- }),
3029
- footer && /* @__PURE__ */ jsx("footer", {
3030
- className: "nb-drawer__footer",
3031
- children: footer
3032
- })
3033
- ]
3034
- })]
3035
- }), document.body);
2790
+ className: ["nb-drawer", className].filter(Boolean).join(" "),
2791
+ scrimClassName: `nb-drawer__scrim nb-drawer__scrim--${scrim}`,
2792
+ scrimLabel: resolvedScrimLabel,
2793
+ labelledBy: title ? titleId : void 0,
2794
+ ariaLabel: !title ? ariaLabel : void 0,
2795
+ style: { width: formatWidth(width) },
2796
+ keepMounted: true,
2797
+ children: [
2798
+ title !== void 0 && /* @__PURE__ */ jsxs("header", {
2799
+ className: "nb-drawer__header",
2800
+ children: [/* @__PURE__ */ jsx("h2", {
2801
+ className: "nb-drawer__title",
2802
+ id: titleId,
2803
+ children: title
2804
+ }), /* @__PURE__ */ jsx(IconButton, {
2805
+ className: "nb-drawer__close",
2806
+ icon: "ph ph-x",
2807
+ label: resolvedCloseLabel,
2808
+ onClick: onClose,
2809
+ disabled: busy
2810
+ })]
2811
+ }),
2812
+ /* @__PURE__ */ jsx("div", {
2813
+ className: "nb-drawer__body",
2814
+ children
2815
+ }),
2816
+ footer && /* @__PURE__ */ jsx("footer", {
2817
+ className: "nb-drawer__footer",
2818
+ children: footer
2819
+ })
2820
+ ]
2821
+ });
3036
2822
  };
3037
2823
  //#endregion
3038
2824
  //#region packages/ui/Timeline.tsx
@@ -3142,7 +2928,7 @@ function Page({ children, fill, wide, narrow, gap = 5, className, ...props }) {
3142
2928
  }
3143
2929
  //#endregion
3144
2930
  //#region packages/ui/PageHeader.tsx
3145
- function PageHeader({ title, subtitle, breadcrumb, breadcrumbSlot, badge, actions, className }) {
2931
+ function PageHeader({ title, subtitle, metadata, breadcrumb, breadcrumbSlot, badge, actions, className }) {
3146
2932
  const breadcrumbNode = breadcrumbSlot ?? (breadcrumb ? /* @__PURE__ */ jsxs("a", {
3147
2933
  href: breadcrumb.href,
3148
2934
  className: "nb-page-header__breadcrumb",
@@ -3161,6 +2947,10 @@ function PageHeader({ title, subtitle, breadcrumb, breadcrumbSlot, badge, action
3161
2947
  className: "nb-page-header__title",
3162
2948
  children: title
3163
2949
  }),
2950
+ metadata && /* @__PURE__ */ jsx("div", {
2951
+ className: "nb-page-header__metadata",
2952
+ children: metadata
2953
+ }),
3164
2954
  subtitle && /* @__PURE__ */ jsx("p", {
3165
2955
  className: "nb-page-header__subtitle",
3166
2956
  children: subtitle
@@ -3230,9 +3020,9 @@ function Col({ children, span, spanSm, spanMd, spanLg, fullWidth, className, ...
3230
3020
  }
3231
3021
  //#endregion
3232
3022
  //#region packages/ui/Section.tsx
3233
- function Section({ title, children, className }) {
3023
+ function Section({ title, children, className, variant = "label" }) {
3234
3024
  return /* @__PURE__ */ jsxs("section", {
3235
- className: joinClasses("nb-section", className),
3025
+ className: joinClasses("nb-section", variant === "panel" && "nb-section--panel", className),
3236
3026
  children: [/* @__PURE__ */ jsx("h2", {
3237
3027
  className: "nb-section__title",
3238
3028
  children: title
@@ -3435,4 +3225,239 @@ function useConfirm() {
3435
3225
  };
3436
3226
  }
3437
3227
  //#endregion
3438
- export { ACCENT_PRESETS, Alert, AppDialog, AppDropdown, AppToolbar, Avatar, Badge, Button, Card, Chip, Cluster, Code, Col, CollapsibleSection, ConfirmDialog, ContextMenu, DataTable, DatePicker, DateRangePicker, DensityContext, DensityProvider, DescriptionList, Drawer, EN_UI_STRINGS, ES_UI_STRINGS, EmptyState, FeatureGate, FileDropzone, FilterPanel, FormActions, FormField, FormLayout, Grid, HubPanel, IconButton, KpiMetricRow, OperationCardGrid, Page, PageHeader, Pagination, Popover, Row, RowActions, ScopeTabs, SearchableAppDropdown, Section, SegmentedControl, SelectField, SettingsPanel, Skeleton, Stack, StatCard, Text, TextAreaField, TextField, ThemeContext, ThemeProvider, ThemeSwitcher, Timeline, TimelineItem, Toggle, UiStringsProvider, getAvatarHue, getAvatarInitials, useAccentColor, useConfirm, useDensity, useFloatingPanel, useTheme, useUiStrings };
3228
+ //#region packages/ui/Checkbox.tsx
3229
+ /** Native checkbox, including the mixed state used by bulk selection. */
3230
+ const Checkbox = forwardRef(function Checkbox({ label, indeterminate = false, invalid = false, id, className, ...props }, ref) {
3231
+ const generatedId = useId();
3232
+ const inputRef = useRef(null);
3233
+ useEffect(() => {
3234
+ if (inputRef.current) inputRef.current.indeterminate = indeterminate;
3235
+ }, [indeterminate]);
3236
+ return /* @__PURE__ */ jsxs("label", {
3237
+ className: `nb-selection-control${className ? ` ${className}` : ""}`,
3238
+ children: [/* @__PURE__ */ jsx("input", {
3239
+ ...props,
3240
+ id: id ?? generatedId,
3241
+ type: "checkbox",
3242
+ "aria-invalid": props["aria-invalid"] ?? (invalid || void 0),
3243
+ ref: (node) => {
3244
+ inputRef.current = node;
3245
+ if (typeof ref === "function") return ref(node);
3246
+ if (ref) ref.current = node;
3247
+ }
3248
+ }), label && /* @__PURE__ */ jsx("span", { children: label })]
3249
+ });
3250
+ });
3251
+ //#endregion
3252
+ //#region packages/ui/RadioGroup.tsx
3253
+ /** Native radios share a name for browser keyboard navigation and form submission. */
3254
+ function RadioGroup({ label, name, value, options, onChange, orientation = "vertical", required, invalid = false, disabled, className, ...props }) {
3255
+ const generatedName = useId();
3256
+ return /* @__PURE__ */ jsxs("fieldset", {
3257
+ ...props,
3258
+ disabled,
3259
+ "aria-invalid": props["aria-invalid"] ?? (invalid || void 0),
3260
+ className: `nb-radio-group${className ? ` ${className}` : ""}`,
3261
+ children: [label && /* @__PURE__ */ jsx("legend", { children: label }), /* @__PURE__ */ jsx("div", {
3262
+ className: `nb-radio-group__options nb-radio-group__options--${orientation}`,
3263
+ children: options.map((option) => /* @__PURE__ */ jsxs("label", {
3264
+ className: "nb-selection-control",
3265
+ children: [/* @__PURE__ */ jsx("input", {
3266
+ type: "radio",
3267
+ name: name ?? generatedName,
3268
+ value: option.value,
3269
+ checked: value === option.value,
3270
+ disabled: disabled || option.disabled,
3271
+ required,
3272
+ onChange: () => onChange(option.value)
3273
+ }), /* @__PURE__ */ jsx("span", { children: option.label })]
3274
+ }, option.value))
3275
+ })]
3276
+ });
3277
+ }
3278
+ //#endregion
3279
+ //#region packages/ui/Tabs.tsx
3280
+ function Tabs({ items, value, onChange, "aria-label": ariaLabel, orientation = "horizontal", activationMode = "automatic", keepMounted = false, className }) {
3281
+ const id = useId();
3282
+ const listRef = useRef(null);
3283
+ const [focusedValue, setFocusedValue] = useState(null);
3284
+ const selectedIndex = items.findIndex((item) => item.value === value && !item.disabled);
3285
+ const focusedIndex = items.findIndex((item) => item.value === focusedValue && !item.disabled);
3286
+ const tabStop = activationMode === "manual" && focusedIndex >= 0 ? focusedIndex : selectedIndex >= 0 ? selectedIndex : items.findIndex((item) => !item.disabled);
3287
+ return /* @__PURE__ */ jsxs("div", {
3288
+ className: `nb-tabs nb-tabs--${orientation}${className ? ` ${className}` : ""}`,
3289
+ children: [/* @__PURE__ */ jsx("div", {
3290
+ ref: listRef,
3291
+ role: "tablist",
3292
+ "aria-label": ariaLabel,
3293
+ "aria-orientation": orientation,
3294
+ className: "nb-tabs__list",
3295
+ children: items.map((item, index) => /* @__PURE__ */ jsx("button", {
3296
+ type: "button",
3297
+ role: "tab",
3298
+ id: `${id}-tab-${index}`,
3299
+ "aria-controls": `${id}-panel-${index}`,
3300
+ "aria-selected": index === selectedIndex,
3301
+ disabled: item.disabled,
3302
+ tabIndex: index === tabStop ? 0 : -1,
3303
+ className: "nb-tabs__tab",
3304
+ onFocus: () => setFocusedValue(item.value),
3305
+ onClick: () => onChange(item.value),
3306
+ onKeyDown: (event) => {
3307
+ const nextKey = orientation === "horizontal" ? "ArrowRight" : "ArrowDown";
3308
+ if (![
3309
+ nextKey,
3310
+ orientation === "horizontal" ? "ArrowLeft" : "ArrowUp",
3311
+ "Home",
3312
+ "End"
3313
+ ].includes(event.key)) return;
3314
+ event.preventDefault();
3315
+ const enabled = items.map((entry, i) => entry.disabled ? -1 : i).filter((i) => i >= 0);
3316
+ const position = enabled.indexOf(index);
3317
+ const next = event.key === "Home" ? enabled[0] : event.key === "End" ? enabled[enabled.length - 1] : enabled[(position + (event.key === nextKey ? 1 : -1) + enabled.length) % enabled.length];
3318
+ if (next === void 0) return;
3319
+ listRef.current?.querySelectorAll("[role=\"tab\"]")[next]?.focus();
3320
+ if (activationMode === "automatic") onChange(items[next].value);
3321
+ },
3322
+ children: item.label
3323
+ }, item.value))
3324
+ }), items.map((item, index) => /* @__PURE__ */ jsx("div", {
3325
+ role: "tabpanel",
3326
+ id: `${id}-panel-${index}`,
3327
+ "aria-labelledby": `${id}-tab-${index}`,
3328
+ hidden: index !== selectedIndex,
3329
+ tabIndex: 0,
3330
+ className: "nb-tabs__panel",
3331
+ children: keepMounted || index === selectedIndex ? item.content : null
3332
+ }, item.value))]
3333
+ });
3334
+ }
3335
+ //#endregion
3336
+ //#region packages/ui/Spinner.tsx
3337
+ function Spinner({ label, size = "md", className, ...props }) {
3338
+ return /* @__PURE__ */ jsx("span", {
3339
+ ...props,
3340
+ className: `nb-spinner nb-spinner--${size}${className ? ` ${className}` : ""}`,
3341
+ role: label ? "status" : void 0,
3342
+ "aria-label": label,
3343
+ "aria-hidden": label ? void 0 : true
3344
+ });
3345
+ }
3346
+ //#endregion
3347
+ //#region packages/ui/Progress.tsx
3348
+ /** Omit value for indeterminate progress; max defaults to 100. */
3349
+ function Progress({ label, id, max = 100, className, ...props }) {
3350
+ const generatedId = useId();
3351
+ const progressId = id ?? generatedId;
3352
+ return /* @__PURE__ */ jsxs("div", {
3353
+ className: "nb-progress-field",
3354
+ children: [label && /* @__PURE__ */ jsx("label", {
3355
+ htmlFor: progressId,
3356
+ children: label
3357
+ }), /* @__PURE__ */ jsx("progress", {
3358
+ ...props,
3359
+ id: progressId,
3360
+ max,
3361
+ className: `nb-progress${className ? ` ${className}` : ""}`
3362
+ })]
3363
+ });
3364
+ }
3365
+ //#endregion
3366
+ //#region packages/ui/Tooltip.tsx
3367
+ const TooltipProvider = Tooltip$1.Provider;
3368
+ /** Uses the existing child as the trigger without adding a nested button. */
3369
+ function Tooltip({ children, content, side = "top", delay, disabled, className }) {
3370
+ const overlayContainer = useOverlayContainer();
3371
+ const id = useId();
3372
+ const [open, setOpen] = useState(false);
3373
+ const description = [children.props["aria-describedby"], open && !disabled ? id : void 0].filter(Boolean).join(" ") || void 0;
3374
+ return /* @__PURE__ */ jsxs(Tooltip$1.Root, {
3375
+ open,
3376
+ disabled,
3377
+ onOpenChange: setOpen,
3378
+ children: [/* @__PURE__ */ jsx(Tooltip$1.Trigger, {
3379
+ render: cloneElement(children, { "aria-describedby": description }),
3380
+ onKeyDownCapture: (event) => {
3381
+ if (open && event.key === "Escape") {
3382
+ event.stopPropagation();
3383
+ setOpen(false);
3384
+ }
3385
+ },
3386
+ delay
3387
+ }), /* @__PURE__ */ jsx(Tooltip$1.Portal, {
3388
+ container: overlayContainer ?? void 0,
3389
+ children: /* @__PURE__ */ jsx(Tooltip$1.Positioner, {
3390
+ side,
3391
+ sideOffset: 8,
3392
+ className: "nb-tooltip-positioner",
3393
+ children: /* @__PURE__ */ jsx(Tooltip$1.Popup, {
3394
+ id,
3395
+ role: "tooltip",
3396
+ className: `nb-tooltip${className ? ` ${className}` : ""}`,
3397
+ children: content
3398
+ })
3399
+ })
3400
+ })]
3401
+ });
3402
+ }
3403
+ //#endregion
3404
+ //#region packages/ui/TimePicker.tsx
3405
+ const timeValue = (value) => {
3406
+ if (!value) return null;
3407
+ try {
3408
+ return parseTime(value);
3409
+ } catch {
3410
+ return null;
3411
+ }
3412
+ };
3413
+ /** Accessible segmented time entry. Values never pass through Date or a timezone. */
3414
+ const TimePicker = forwardRef(function TimePicker({ id, name, value, onChange, onBlur, min, max, locale, hourCycle, granularity = "minute", disabled, readOnly, required, invalid, className, ariaLabel }, ref) {
3415
+ const strings = useUiStrings();
3416
+ return /* @__PURE__ */ jsx(I18nProvider, {
3417
+ locale: getDateLocale(locale),
3418
+ children: /* @__PURE__ */ jsx(TimeField, {
3419
+ id,
3420
+ name,
3421
+ "aria-label": ariaLabel ?? strings.selectTime,
3422
+ value: timeValue(value),
3423
+ onChange: (next) => onChange?.(next ? next.toString().slice(0, granularity === "second" ? 8 : 5) : ""),
3424
+ onBlur,
3425
+ minValue: timeValue(min) ?? void 0,
3426
+ maxValue: timeValue(max) ?? void 0,
3427
+ granularity,
3428
+ hourCycle,
3429
+ isDisabled: disabled,
3430
+ isReadOnly: readOnly,
3431
+ isRequired: required,
3432
+ isInvalid: invalid,
3433
+ validationBehavior: "aria",
3434
+ className: ["nb-time-picker", className].filter(Boolean).join(" "),
3435
+ children: /* @__PURE__ */ jsx(DateInput, {
3436
+ ref,
3437
+ className: "nb-time-picker__input",
3438
+ children: (segment) => /* @__PURE__ */ jsx(DateSegment, {
3439
+ segment,
3440
+ className: "nb-time-picker__segment"
3441
+ })
3442
+ })
3443
+ })
3444
+ });
3445
+ });
3446
+ //#endregion
3447
+ //#region packages/ui/DetailLayout.tsx
3448
+ /** Responsive main/aside composition for record detail pages. */
3449
+ function DetailLayout({ children, aside, asideLabel, className }) {
3450
+ return /* @__PURE__ */ jsxs("div", {
3451
+ className: joinClasses("nb-detail-layout", className),
3452
+ children: [/* @__PURE__ */ jsx("div", {
3453
+ className: "nb-detail-layout__main",
3454
+ children
3455
+ }), /* @__PURE__ */ jsx("aside", {
3456
+ className: "nb-detail-layout__aside",
3457
+ "aria-label": asideLabel,
3458
+ children: aside
3459
+ })]
3460
+ });
3461
+ }
3462
+ //#endregion
3463
+ export { ACCENT_PRESETS, Alert, AppDialog, AppDropdown, AppToolbar, Avatar, Badge, Button, Card, Checkbox, Chip, Cluster, Code, Col, CollapsibleSection, Combobox, ConfirmDialog, ContextMenu, DataTable, DatePicker, DateRangePicker, DensityContext, DensityProvider, DescriptionList, DetailLayout, Drawer, EN_UI_STRINGS, ES_UI_STRINGS, EmptyState, FeatureGate, FileDropzone, FilterPanel, FormActions, FormField, FormLayout, Grid, HubPanel, IconButton, KpiMetricRow, MultiSelect, OperationCardGrid, Page, PageHeader, Pagination, Popover, Progress, RadioGroup, Row, RowActions, ScopeTabs, SearchableAppDropdown, Section, SegmentedControl, SelectField, SettingsPanel, Skeleton, Spinner, Stack, StatCard, Tabs, Text, TextAreaField, TextField, ThemeContext, ThemeProvider, ThemeSwitcher, TimePicker, Timeline, TimelineItem, Toggle, Tooltip, TooltipProvider, UiStringsProvider, getAvatarHue, getAvatarInitials, useAccentColor, useConfirm, useDensity, useFloatingPanel, useOverlayContainer, useTheme, useUiStrings };