@nubitio/ui 1.1.2 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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,532 @@ 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(Input, {
1010
+ ...inputProps,
1011
+ ref: inputRef,
1012
+ id: inputId,
1013
+ className: `nb-input nb-combobox__input${invalid || error ? " nb-input--invalid" : ""}${inputClassName ? ` ${inputClassName}` : ""}`,
1014
+ onKeyDown: (event) => {
1015
+ inputProps.onKeyDown?.(event);
1016
+ if (open && event.key === "Escape") event.stopPropagation();
1017
+ if (!event.defaultPrevented && event.key === "PageDown" && remote.hasMore) {
1018
+ event.preventDefault();
1019
+ remote.loadMore();
1020
+ }
1021
+ },
1022
+ "aria-invalid": inputProps["aria-invalid"] ?? (invalid || !!error || void 0),
1023
+ "aria-describedby": description
1024
+ }), /* @__PURE__ */ jsxs("div", {
1025
+ className: "nb-combobox__actions",
1026
+ children: [clearable && !readOnly && /* @__PURE__ */ jsx(ComboboxClear, {
1027
+ label: clearLabel ?? strings.clear,
1028
+ disabled,
1029
+ multiple
1030
+ }), /* @__PURE__ */ jsx(Button$1, {
1031
+ className: "nb-combobox__action",
1032
+ "aria-label": openLabel ?? strings.openOptions,
1033
+ children: /* @__PURE__ */ jsx("svg", {
1034
+ viewBox: "0 0 24 24",
1035
+ "aria-hidden": "true",
1036
+ focusable: "false",
1037
+ children: /* @__PURE__ */ jsx("path", { d: "m6 9 6 6 6-6" })
1038
+ })
1039
+ })]
1040
+ })]
795
1041
  }),
796
- open && !disabled && createPortal(/* @__PURE__ */ jsxs("div", {
797
- ref: menuRef,
798
- className: cx$2("nb-dropdown__menu", `nb-dropdown__menu--${variant}`),
799
- style: menuStyle,
1042
+ multiple && selectedOptions.length > 0 && /* @__PURE__ */ jsx(ComboBoxValue, { children: () => /* @__PURE__ */ jsx(TagGroup, {
1043
+ "aria-label": selectedLabel ?? strings.selectedOptions,
1044
+ onRemove: disabled || readOnly ? void 0 : (keys) => onChange(selected.filter((key) => !keys.has(key))),
1045
+ className: "nb-combobox-tags",
1046
+ children: /* @__PURE__ */ jsx(TagList, {
1047
+ items: selectedOptions,
1048
+ children: (option) => /* @__PURE__ */ jsxs(Tag, {
1049
+ id: option.value,
1050
+ textValue: option.label,
1051
+ className: "nb-combobox-tags__tag",
1052
+ children: [option.label, !disabled && !readOnly && /* @__PURE__ */ jsx(Button$1, {
1053
+ slot: "remove",
1054
+ className: "nb-combobox-tags__remove",
1055
+ "aria-label": removeLabel?.(option) ?? strings.removeOption,
1056
+ children: /* @__PURE__ */ jsx("svg", {
1057
+ viewBox: "0 0 24 24",
1058
+ "aria-hidden": "true",
1059
+ focusable: "false",
1060
+ children: /* @__PURE__ */ jsx("path", { d: "m6 6 12 12M18 6 6 18" })
1061
+ })
1062
+ })]
1063
+ })
1064
+ })
1065
+ }) }),
1066
+ /* @__PURE__ */ jsxs(Popover$1, {
1067
+ UNSTABLE_portalContainer: overlayContainer ?? void 0,
1068
+ className: "nb-combobox-popup",
1069
+ offset: 4,
1070
+ isNonModal: true,
1071
+ onScroll: (event) => {
1072
+ const panel = event.currentTarget;
1073
+ if (panel.scrollHeight - panel.scrollTop <= panel.clientHeight + 20) remote.loadMore();
1074
+ },
800
1075
  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);
1076
+ remoteStatus && /* @__PURE__ */ jsx("div", {
1077
+ className: "nb-combobox-popup__empty",
1078
+ role: remote.failed ? "alert" : "status",
1079
+ children: remoteStatus
1080
+ }),
1081
+ /* @__PURE__ */ jsx(ListBox, {
1082
+ className: "nb-combobox-popup__list",
1083
+ "aria-busy": remote.loading || void 0,
1084
+ renderEmptyState: () => remoteStatus ? null : /* @__PURE__ */ jsx("div", {
1085
+ className: "nb-combobox-popup__empty",
1086
+ children: emptyMessage ?? strings.noOptions
1087
+ }),
1088
+ children: (option) => /* @__PURE__ */ jsx(ListBoxItem, {
1089
+ id: option.value,
1090
+ textValue: option.label,
1091
+ isDisabled: option.disabled,
1092
+ className: "nb-combobox-popup__item",
1093
+ children: ({ isSelected }) => /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("span", {
1094
+ className: "nb-combobox-popup__indicator",
1095
+ "aria-hidden": "true",
1096
+ children: isSelected ? "✓" : ""
1097
+ }), option.content ?? option.label] })
831
1098
  })
832
1099
  }),
833
- menuFooter
1100
+ remote.hasMore && !remote.failed && /* @__PURE__ */ jsx(Button$1, {
1101
+ slot: null,
1102
+ className: "nb-combobox__action",
1103
+ isDisabled: remote.loading,
1104
+ onPress: () => {
1105
+ remote.loadMore();
1106
+ },
1107
+ children: strings.loadMore
1108
+ }),
1109
+ remote.failed && /* @__PURE__ */ jsx(Button$1, {
1110
+ className: "nb-combobox__action",
1111
+ onPress: remote.retry,
1112
+ children: strings.retrySearch
1113
+ })
834
1114
  ]
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
1115
  }),
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
1116
+ message && /* @__PURE__ */ jsx("span", {
1117
+ id: messageId,
1118
+ className: error ? "nb-form-field__error" : "nb-form-field__help",
1119
+ role: error ? "alert" : void 0,
1120
+ children: message
1121
+ })
857
1122
  ]
858
1123
  });
859
1124
  }
1125
+ function ComboboxClear({ label, disabled, multiple }) {
1126
+ const state = useContext(ComboBoxStateContext);
1127
+ const hasValue = multiple ? Array.isArray(state?.value) && state.value.length > 0 : !!state?.inputValue;
1128
+ if (!state || !hasValue || state.isOpen) return null;
1129
+ return /* @__PURE__ */ jsx(Button$1, {
1130
+ slot: null,
1131
+ isDisabled: disabled,
1132
+ className: "nb-combobox__action nb-combobox__clear",
1133
+ "aria-label": label,
1134
+ onPress: () => {
1135
+ state.setValue(multiple ? [] : null);
1136
+ state.setInputValue("");
1137
+ },
1138
+ children: /* @__PURE__ */ jsx("svg", {
1139
+ viewBox: "0 0 24 24",
1140
+ "aria-hidden": "true",
1141
+ focusable: "false",
1142
+ children: /* @__PURE__ */ jsx("path", { d: "m6 6 12 12M18 6 6 18" })
1143
+ })
1144
+ });
1145
+ }
860
1146
  //#endregion
861
1147
  //#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, {
1148
+ const toOption = (option) => ({
1149
+ value: option.value,
1150
+ label: option.selectedLabel ?? option.label,
1151
+ disabled: option.disabled,
1152
+ content: /* @__PURE__ */ jsxs("span", {
1153
+ className: "nb-dropdown__option-content",
1154
+ children: [option.iconText && /* @__PURE__ */ jsx("span", {
1155
+ className: "nb-dropdown__option-icon",
1156
+ "aria-hidden": "true",
1157
+ children: option.iconText
1158
+ }), option.label]
1159
+ })
1160
+ });
1161
+ 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 }) {
1162
+ const loadOptions = useCallback(async (query, { signal }) => {
1163
+ const results = await onSearch(query.trim());
1164
+ if (signal.aborted) throw new DOMException("Search cancelled", "AbortError");
1165
+ return { options: results.map(toOption) };
1166
+ }, [onSearch]);
1167
+ if (!searchable) return /* @__PURE__ */ jsx(AppDropdown, {
979
1168
  ...rest,
1169
+ options,
980
1170
  value,
981
1171
  onChange,
982
1172
  placeholder,
983
1173
  disabled,
984
- options: [{
985
- value: "",
986
- label: placeholder ?? "Seleccionar…"
987
- }, ...resolvedOptions],
988
- menuHeader,
989
- menuFooter,
990
- onOpenChange: setOpen
1174
+ label,
1175
+ showFieldLabel,
1176
+ variant,
1177
+ icon: _icon,
1178
+ menuMinWidth: _menuMinWidth,
1179
+ menuHeader: _header,
1180
+ menuFooter: _footer
1181
+ });
1182
+ const seeds = selectedOption && !options.some((option) => option.value === selectedOption.value) ? [...options, selectedOption] : options;
1183
+ return /* @__PURE__ */ jsx(Combobox, {
1184
+ ...rest,
1185
+ label: showFieldLabel === false ? void 0 : label,
1186
+ "aria-label": showFieldLabel === false && typeof label === "string" ? label : void 0,
1187
+ placeholder: placeholder ?? searchPlaceholder,
1188
+ options: seeds.map(toOption),
1189
+ value: value || null,
1190
+ onChange: (next) => onChange(next ?? ""),
1191
+ disabled,
1192
+ loadOptions: onSearch ? loadOptions : void 0,
1193
+ minSearchLength,
1194
+ emptyMessage: emptySearchLabel,
1195
+ loadingMessage: loadingLabel
991
1196
  });
992
1197
  }
993
1198
  //#endregion
@@ -1050,7 +1255,7 @@ function applyThemeAttributes(theme, themePrefix) {
1050
1255
  themeValues.forEach((value) => root.classList.remove(`${themePrefix}${value}`));
1051
1256
  root.classList.add(`${themePrefix}${theme}`);
1052
1257
  }
1053
- const ThemeProvider = ({ storageKey = "nb-theme", themePrefix = "nb-theme-", basePath = "/themes/", children }) => {
1258
+ const ThemeProvider = ({ storageKey = "nb-theme", themePrefix = "nb-theme-", basePath = "/themes/", visualStyle = "default", children }) => {
1054
1259
  const getPersistedMode = () => {
1055
1260
  const persisted = window.localStorage.getItem(storageKey);
1056
1261
  return persisted && themeModes.includes(persisted) ? persisted : "auto";
@@ -1059,6 +1264,15 @@ const ThemeProvider = ({ storageKey = "nb-theme", themePrefix = "nb-theme-", bas
1059
1264
  const [systemTheme, setSystemTheme] = useState(getSystemTheme);
1060
1265
  const [isLoaded, setIsLoaded] = useState(false);
1061
1266
  const theme = useMemo(() => resolveTheme(mode, systemTheme), [mode, systemTheme]);
1267
+ useEffect(() => {
1268
+ const root = document.documentElement;
1269
+ const previous = root.getAttribute("data-visual-style");
1270
+ root.setAttribute("data-visual-style", visualStyle);
1271
+ return () => {
1272
+ if (previous === null) root.removeAttribute("data-visual-style");
1273
+ else root.setAttribute("data-visual-style", previous);
1274
+ };
1275
+ }, [visualStyle]);
1062
1276
  useEffect(() => {
1063
1277
  applyThemeAttributes(theme, themePrefix);
1064
1278
  setThemeToDOM(`${basePath}${themePrefix}${theme}.css`).then(() => setIsLoaded(true));
@@ -1401,7 +1615,7 @@ const DEFAULT_ICONS = {
1401
1615
  warning: "warning",
1402
1616
  success: "check-circle"
1403
1617
  };
1404
- const EmptyState = ({ icon, variant = "default", title, description, action, size = "md", fill = false, className }) => {
1618
+ const EmptyState = ({ icon, illustration, variant = "default", title, description, action, size = "md", fill = false, className }) => {
1405
1619
  const iconName = icon ?? DEFAULT_ICONS[variant];
1406
1620
  const classes = [
1407
1621
  "nb-empty-state",
@@ -1417,7 +1631,7 @@ const EmptyState = ({ icon, variant = "default", title, description, action, siz
1417
1631
  children: [
1418
1632
  /* @__PURE__ */ jsx("div", {
1419
1633
  className: "nb-empty-state__icon-wrap",
1420
- children: /* @__PURE__ */ jsx("i", {
1634
+ children: illustration ?? /* @__PURE__ */ jsx("i", {
1421
1635
  className: `ph ph-${iconName}`,
1422
1636
  "aria-hidden": "true"
1423
1637
  })
@@ -1498,73 +1712,51 @@ const Toggle = ({ checked, onChange, label, size = "md", disabled = false, "aria
1498
1712
  };
1499
1713
  //#endregion
1500
1714
  //#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
1715
  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
- });
1716
+ const container = useOverlayContainer();
1717
+ const triggerRef = useRef(null);
1718
+ const restoreFocus = useRef(false);
1526
1719
  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)]
1720
+ return /* @__PURE__ */ jsx(Menu.Root, {
1721
+ modal: false,
1722
+ onOpenChange: (open, details) => {
1723
+ restoreFocus.current = !open && (details.reason === "item-press" || details.reason === "escape-key");
1724
+ },
1725
+ onOpenChangeComplete: (open) => {
1726
+ if (!open && restoreFocus.current) triggerRef.current?.focus({ preventScroll: true });
1727
+ },
1728
+ children: /* @__PURE__ */ jsxs("div", {
1729
+ className: `nb-context-menu${className ? ` ${className}` : ""}`,
1730
+ children: [/* @__PURE__ */ jsx(Menu.Trigger, {
1731
+ ref: triggerRef,
1732
+ render: isValidElement(trigger) ? trigger : /* @__PURE__ */ jsx(IconButton, {
1733
+ icon: "ph ph-dots-three",
1734
+ label: triggerLabel,
1735
+ children: trigger
1736
+ })
1737
+ }), /* @__PURE__ */ jsx(Menu.Portal, {
1738
+ container: container ?? void 0,
1739
+ children: /* @__PURE__ */ jsx(Menu.Positioner, {
1740
+ align: align === "right" ? "end" : "start",
1741
+ sideOffset: 4,
1742
+ className: "nb-context-menu-positioner",
1743
+ children: /* @__PURE__ */ jsx(Menu.Popup, {
1744
+ finalFocus: triggerRef,
1745
+ className: "nb-context-menu__dropdown",
1746
+ 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, {
1747
+ disabled: item.disabled,
1748
+ label: item.label,
1749
+ className: `nb-context-menu__item${item.danger ? " nb-context-menu__item--danger" : ""}`,
1750
+ onClick: item.onClick,
1751
+ children: [item.icon && /* @__PURE__ */ jsx("i", {
1752
+ className: item.icon,
1753
+ "aria-hidden": "true"
1754
+ }), item.label]
1755
+ })] }, index))
1756
+ })
1757
+ })
1758
+ })]
1759
+ })
1568
1760
  });
1569
1761
  };
1570
1762
  //#endregion
@@ -1889,6 +2081,7 @@ const CollapsibleSection = ({ label, icon, open, onToggle, children, trailing, c
1889
2081
  className: "nb-collapsible__header",
1890
2082
  children: [/* @__PURE__ */ jsxs("button", {
1891
2083
  type: "button",
2084
+ id: `${bodyId}-trigger`,
1892
2085
  className: "nb-collapsible__trigger",
1893
2086
  "aria-expanded": open,
1894
2087
  "aria-controls": bodyId,
@@ -1915,1124 +2108,699 @@ const CollapsibleSection = ({ label, icon, open, onToggle, children, trailing, c
1915
2108
  id: bodyId,
1916
2109
  className: ["nb-collapsible__body", bodyClassName].filter(Boolean).join(" "),
1917
2110
  role: "region",
1918
- "aria-labelledby": void 0,
2111
+ "aria-labelledby": `${bodyId}-trigger`,
1919
2112
  hidden: !open,
1920
2113
  children
1921
2114
  })]
1922
2115
  });
1923
2116
  };
1924
2117
  //#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 {
2118
+ //#region packages/ui/CalendarContent.tsx
2119
+ /** Shared presentation; React Aria owns navigation, focus and range preview. */
2120
+ function CalendarContent() {
2121
+ const strings = useUiStrings();
2122
+ return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsxs("header", {
2123
+ className: "nb-calendar__header",
2124
+ children: [
2125
+ /* @__PURE__ */ jsx(Button$1, {
2126
+ slot: "previous",
2127
+ className: "nb-date-picker__nav",
2128
+ "aria-label": strings.previousMonth,
2129
+ children: "‹"
2130
+ }),
2131
+ /* @__PURE__ */ jsxs("div", {
2132
+ className: "nb-calendar__selectors",
2133
+ children: [
2134
+ /* @__PURE__ */ jsx(Heading, { className: "nb-calendar__heading" }),
2135
+ /* @__PURE__ */ jsx(CalendarMonthPicker, { children: ({ items, value, onChange, ...props }) => /* @__PURE__ */ jsx("select", {
2136
+ ...props,
2137
+ value,
2138
+ onChange: (event) => onChange(Number(event.target.value)),
2139
+ children: items.map((item) => /* @__PURE__ */ jsx("option", {
2140
+ value: item.id,
2141
+ children: item.formatted
2142
+ }, item.id))
2143
+ }) }),
2144
+ /* @__PURE__ */ jsx(CalendarYearPicker, { children: ({ items, value, onChange, ...props }) => /* @__PURE__ */ jsx("select", {
2145
+ ...props,
2146
+ value,
2147
+ onChange: (event) => onChange(Number(event.target.value)),
2148
+ children: items.map((item) => /* @__PURE__ */ jsx("option", {
2149
+ value: item.id,
2150
+ children: item.formatted
2151
+ }, item.id))
2152
+ }) })
2153
+ ]
2154
+ }),
2155
+ /* @__PURE__ */ jsx(Button$1, {
2156
+ slot: "next",
2157
+ className: "nb-date-picker__nav",
2158
+ "aria-label": strings.nextMonth,
2159
+ children: "›"
2160
+ })
2161
+ ]
2162
+ }), /* @__PURE__ */ jsxs(CalendarGrid, {
2163
+ className: "nb-calendar__grid",
2164
+ children: [/* @__PURE__ */ jsx(CalendarGridHeader, { children: (day) => /* @__PURE__ */ jsx(CalendarHeaderCell, {
2165
+ className: "nb-calendar__weekday",
2166
+ children: day
2167
+ }) }), /* @__PURE__ */ jsx(CalendarGridBody, { children: (date) => /* @__PURE__ */ jsx(CalendarCell, {
1988
2168
  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);
2169
+ className: "nb-calendar__day"
2170
+ }) })]
2171
+ })] });
2172
+ }
2173
+ /** A parent modal owns containment; a standalone picker needs its own focus scope. */
2174
+ function CalendarDialog({ id, ariaLabel, children }) {
2175
+ return useOverlayContainer() ? /* @__PURE__ */ jsx("section", {
2176
+ id,
2177
+ "aria-label": ariaLabel,
2178
+ role: "dialog",
2179
+ tabIndex: -1,
2180
+ children
2181
+ }) : /* @__PURE__ */ jsx(Dialog$1, {
2182
+ id,
2183
+ "aria-label": ariaLabel,
2184
+ children
2010
2185
  });
2186
+ }
2187
+ //#endregion
2188
+ //#region packages/ui/dateValues.ts
2189
+ const getDateLocale = (locale) => locale || typeof document !== "undefined" && document.documentElement.lang || typeof navigator !== "undefined" && navigator.language || "en-US";
2190
+ const calendarDate = (value) => {
2191
+ if (!value || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return null;
2192
+ try {
2193
+ return parseDate(value);
2194
+ } catch {
2195
+ return null;
2196
+ }
2011
2197
  };
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
- });
2198
+ const formatDate = (value, locale) => {
2199
+ const date = calendarDate(value);
2200
+ return date ? new Intl.DateTimeFormat(locale, {
2201
+ day: "2-digit",
2202
+ month: "2-digit",
2203
+ year: "numeric",
2204
+ timeZone: "UTC"
2205
+ }).format(date.toDate("UTC")) : "";
2019
2206
  };
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) => {
2207
+ const dateAllowed = (value, min, max) => Boolean(calendarDate(value)) && (!min || value >= min) && (!max || value <= max);
2208
+ const dateOrder = (locale) => new Intl.DateTimeFormat(getDateLocale(locale), {
2209
+ day: "2-digit",
2210
+ month: "2-digit",
2211
+ year: "numeric",
2212
+ timeZone: "UTC"
2213
+ }).formatToParts(new Date(Date.UTC(2026, 10, 23))).filter((part) => [
2214
+ "day",
2215
+ "month",
2216
+ "year"
2217
+ ].includes(part.type)).map((part) => part.type);
2218
+ const datePlaceholder = (locale) => dateOrder(locale).map((part) => part === "year" ? "yyyy" : part === "month" ? "mm" : "dd").join("/");
2219
+ const applyDateMask = (rawValue, prevValue, locale) => {
2220
+ if (/^\d{4}-\d{2}-\d{2}$/.test(rawValue)) return rawValue;
2028
2221
  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 += "/";
2222
+ const adding = digits.length > prevValue.replace(/\D/g, "").length;
2223
+ const sizes = dateOrder(locale ?? "es-PE").map((part) => part === "year" ? 4 : 2);
2224
+ let offset = 0;
2225
+ let result = "";
2226
+ for (const [i, size] of sizes.entries()) {
2227
+ result += digits.slice(offset, offset + size);
2228
+ offset += size;
2229
+ if (i < 2 && (digits.length > offset || adding && digits.length === offset)) result += "/";
2230
+ }
2036
2231
  return result;
2037
2232
  };
2038
- /**
2039
- * Parses dd/mm/yyyy or ISO yyyy-mm-dd to ISO string.
2040
- * Returns null if not a valid date.
2041
- */
2042
2233
  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;
2234
+ if (calendarDate(text)) return text;
2235
+ const order = dateOrder(locale);
2236
+ const digits = text.match(/\d+/g);
2237
+ if (!digits || digits.length !== 3) return null;
2238
+ const fields = Object.fromEntries(order.map((key, i) => [key, digits[i]]));
2239
+ if (fields.year?.length !== 4) return null;
2240
+ const iso = `${fields.year}-${fields.month?.padStart(2, "0")}-${fields.day?.padStart(2, "0")}`;
2241
+ return calendarDate(iso) ? iso : null;
2052
2242
  };
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();
2243
+ //#endregion
2244
+ //#region packages/ui/DateTextInput.tsx
2245
+ /** Keeps the real input/ref/ID contract used by CRUD forms. */
2246
+ const DateTextInput = forwardRef(function DateTextInput({ value, locale, min, max, onChange, onOpen, onBlur, onKeyDown, ...props }, ref) {
2247
+ const [draft, setDraft] = useState(null);
2248
+ const commit = () => {
2249
+ if (draft === null) return;
2250
+ const iso = parseDisplayDate(draft.trim(), locale);
2251
+ if (!draft.trim()) onChange("");
2252
+ else if (iso && dateAllowed(iso, min, max)) onChange(iso);
2253
+ setDraft(null);
2254
+ };
2255
+ return /* @__PURE__ */ jsx("input", {
2256
+ ...props,
2257
+ ref,
2258
+ type: "text",
2259
+ inputMode: "numeric",
2260
+ onPointerDown: (event) => event.stopPropagation(),
2261
+ onPointerUp: (event) => event.stopPropagation(),
2262
+ onMouseDown: (event) => event.stopPropagation(),
2263
+ onClick: (event) => event.stopPropagation(),
2264
+ value: draft ?? formatDate(value, locale),
2265
+ onChange: (event) => setDraft(applyDateMask(event.target.value, draft ?? "", locale)),
2266
+ onBlur: (event) => {
2267
+ commit();
2268
+ onBlur?.(event);
2077
2269
  },
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
- };
2270
+ onKeyDown: (event) => {
2271
+ if (event.key !== "Escape") event.stopPropagation();
2272
+ onKeyDown?.(event);
2273
+ if (event.defaultPrevented) return;
2274
+ if (event.key === "Enter") {
2275
+ event.preventDefault();
2276
+ commit();
2277
+ }
2278
+ if (event.key === "Escape") setDraft(null);
2279
+ if (event.key === "ArrowDown" && !props.disabled && !props.readOnly) {
2280
+ event.preventDefault();
2281
+ commit();
2282
+ onOpen();
2283
+ }
2088
2284
  }
2089
2285
  });
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]);
2286
+ });
2287
+ //#endregion
2288
+ //#region packages/ui/useCalendarPopover.ts
2289
+ /** Bridge focus restoration between React Aria's popup and a parent Base UI modal. */
2290
+ function useCalendarPopover() {
2291
+ const container = useOverlayContainer();
2292
+ const groupRef = useRef(null);
2293
+ const panelRef = useRef(null);
2294
+ const frame = useRef(null);
2295
+ const outsideTarget = useRef(null);
2296
+ const [open, updateOpen] = useState(false);
2102
2297
  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;
2298
+ if (!open || !container) return;
2299
+ const rememberTarget = (event) => {
2300
+ 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\"])");
2301
+ };
2302
+ document.addEventListener("pointerdown", rememberTarget, true);
2303
+ return () => document.removeEventListener("pointerdown", rememberTarget, true);
2304
+ }, [open, container]);
2305
+ useEffect(() => () => {
2306
+ if (frame.current !== null) cancelAnimationFrame(frame.current);
2307
+ }, []);
2308
+ return {
2309
+ container,
2310
+ groupRef,
2311
+ panelRef,
2312
+ open,
2313
+ setOpen: useCallback((next) => {
2314
+ if (frame.current !== null) cancelAnimationFrame(frame.current);
2315
+ if (next) outsideTarget.current = null;
2316
+ const active = document.activeElement;
2317
+ const target = outsideTarget.current ?? groupRef.current?.querySelector("input");
2318
+ const restore = !next && container && (outsideTarget.current || panelRef.current?.contains(active));
2319
+ updateOpen(next);
2320
+ if (restore) frame.current = requestAnimationFrame(() => {
2321
+ frame.current = requestAnimationFrame(() => {
2322
+ frame.current = null;
2323
+ if (document.activeElement === active || document.activeElement === container || document.activeElement === document.body) target?.focus();
2324
+ });
2325
+ });
2326
+ }, [container])
2216
2327
  };
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}`))
2328
+ }
2329
+ //#endregion
2330
+ //#region packages/ui/DatePicker.tsx
2331
+ 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) {
2332
+ const generatedId = useId();
2333
+ const inputId = id ?? generatedId;
2334
+ const { container, groupRef, panelRef, open, setOpen } = useCalendarPopover();
2335
+ const strings = useUiStrings();
2336
+ const resolvedLocale = getDateLocale(locale);
2337
+ const change = (next) => onChange?.(next);
2338
+ const todayIso = today(getLocalTimeZone()).toString();
2339
+ const prefix = "nb-date-picker";
2340
+ return /* @__PURE__ */ jsx(I18nProvider, {
2341
+ locale: resolvedLocale,
2342
+ children: /* @__PURE__ */ jsxs(DatePicker$1, {
2343
+ "aria-label": ariaLabel ?? strings.selectDate,
2344
+ value: calendarDate(value),
2345
+ onChange: (date) => change(date?.toString() ?? ""),
2346
+ minValue: calendarDate(min) ?? void 0,
2347
+ maxValue: calendarDate(max) ?? void 0,
2348
+ isDisabled: disabled,
2349
+ isReadOnly: readOnly,
2350
+ isRequired: required,
2351
+ isInvalid: invalid,
2352
+ validationBehavior: "aria",
2353
+ isOpen: open,
2354
+ onOpenChange: setOpen,
2355
+ className: [prefix, className].filter(Boolean).join(" "),
2356
+ children: [
2357
+ /* @__PURE__ */ jsx("input", {
2358
+ type: "hidden",
2359
+ name,
2360
+ value: value ?? "",
2361
+ disabled
2362
+ }),
2363
+ /* @__PURE__ */ jsxs(Group, {
2364
+ ref: groupRef,
2365
+ className: [
2366
+ `${prefix}__trigger`,
2367
+ disabled && `${prefix}__trigger--disabled`,
2368
+ readOnly && `${prefix}__trigger--readonly`,
2369
+ invalid && `${prefix}__trigger--invalid`,
2370
+ open && `${prefix}__trigger--open`
2371
+ ].filter(Boolean).join(" "),
2372
+ children: [
2373
+ /* @__PURE__ */ jsx(DateTextInput, {
2374
+ ref,
2375
+ id: inputId,
2376
+ value,
2377
+ locale: resolvedLocale,
2378
+ min,
2379
+ max,
2380
+ placeholder: placeholder ?? datePlaceholder(resolvedLocale),
2381
+ disabled,
2382
+ readOnly,
2383
+ required,
2384
+ "aria-label": ariaLabel ?? (id ? void 0 : strings.selectDate),
2385
+ "aria-invalid": invalid || void 0,
2386
+ role: "combobox",
2387
+ "aria-haspopup": "dialog",
2388
+ "aria-expanded": open,
2389
+ "aria-controls": open ? `${inputId}-panel` : void 0,
2390
+ className: `${prefix}__input`,
2391
+ onChange: change,
2392
+ onOpen: () => setOpen(true),
2393
+ onBlur,
2394
+ onKeyDown: (event) => {
2395
+ if (event.key === "Escape" && open) {
2396
+ event.stopPropagation();
2397
+ setOpen(false);
2398
+ }
2399
+ }
2326
2400
  }),
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))
2401
+ clearable && value && !disabled && !readOnly && /* @__PURE__ */ jsx(Button$1, {
2402
+ slot: null,
2403
+ className: `${prefix}__clear`,
2404
+ "aria-label": strings.clearDate,
2405
+ onPress: () => change(""),
2406
+ children: "×"
2343
2407
  }),
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(""),
2408
+ /* @__PURE__ */ jsx(Button$1, {
2409
+ className: `${prefix}__calendar-btn`,
2410
+ "aria-label": strings.openCalendar,
2411
+ onPress: () => groupRef.current?.querySelector("input")?.focus(),
2412
+ isDisabled: disabled || readOnly,
2413
+ children: /* @__PURE__ */ jsx("i", {
2414
+ "aria-hidden": "true",
2415
+ className: "ph ph-calendar-blank"
2416
+ })
2417
+ })
2418
+ ]
2419
+ }),
2420
+ /* @__PURE__ */ jsx(Popover$1, {
2421
+ isNonModal: Boolean(container),
2422
+ ref: panelRef,
2423
+ UNSTABLE_portalContainer: container ?? void 0,
2424
+ className: `${prefix}__panel`,
2425
+ offset: 4,
2426
+ children: /* @__PURE__ */ jsxs(CalendarDialog, {
2427
+ id: `${inputId}-panel`,
2428
+ ariaLabel: strings.selectDate,
2429
+ children: [/* @__PURE__ */ jsx(Calendar, { children: /* @__PURE__ */ jsx(CalendarContent, {}) }), /* @__PURE__ */ jsxs("div", {
2430
+ className: `${prefix}__footer`,
2431
+ children: [/* @__PURE__ */ jsx(Button$1, {
2432
+ slot: null,
2433
+ className: `${prefix}__text-button`,
2434
+ onPress: () => {
2435
+ change("");
2436
+ setOpen(false);
2437
+ },
2350
2438
  children: strings.clear
2351
- }), /* @__PURE__ */ jsx("button", {
2352
- type: "button",
2353
- className: "nb-date-picker__text-button",
2354
- onClick: handleToday,
2439
+ }), /* @__PURE__ */ jsx(Button$1, {
2440
+ slot: null,
2441
+ className: `${prefix}__text-button`,
2442
+ isDisabled: !dateAllowed(todayIso, min, max),
2443
+ onPress: () => {
2444
+ change(todayIso);
2445
+ setOpen(false);
2446
+ },
2355
2447
  children: strings.today
2356
2448
  })]
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
- ]
2449
+ })]
2450
+ })
2451
+ })
2452
+ ]
2453
+ })
2503
2454
  });
2504
2455
  });
2505
2456
  //#endregion
2506
2457
  //#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();
2458
+ function DateRangePicker({ startValue, endValue, placeholder, disabled = false, clearable = true, readOnly = false, required = false, invalid = false, locale, min, max, className, ariaLabel, onChange, onBlur }) {
2459
+ const { container, groupRef, panelRef, open, setOpen } = useCalendarPopover();
2578
2460
  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,
2461
+ const resolvedLocale = getDateLocale(locale);
2462
+ const start = calendarDate(startValue);
2463
+ const end = calendarDate(endValue);
2464
+ const change = (a, b) => a && b && a > b ? onChange?.(b, a) : onChange?.(a, b);
2465
+ const todayIso = today(getLocalTimeZone()).toString();
2466
+ const prefix = "nb-date-range-picker";
2467
+ const inputProps = {
2468
+ locale: resolvedLocale,
2596
2469
  min,
2597
2470
  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);
2471
+ placeholder: placeholder ?? datePlaceholder(resolvedLocale),
2472
+ disabled,
2473
+ readOnly,
2474
+ required,
2475
+ "aria-invalid": invalid || void 0,
2476
+ className: `${prefix}__input`,
2477
+ onOpen: () => setOpen(true),
2478
+ onBlur,
2479
+ onKeyDown: (event) => {
2480
+ if (event.key === "Escape" && open) {
2481
+ event.stopPropagation();
2482
+ setOpen(false);
2483
+ }
2729
2484
  }
2730
2485
  };
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,
2486
+ return /* @__PURE__ */ jsx(I18nProvider, {
2487
+ locale: resolvedLocale,
2488
+ children: /* @__PURE__ */ jsxs(DateRangePicker$1, {
2489
+ "aria-label": ariaLabel ?? strings.selectDateRange,
2490
+ value: start && end && start.compare(end) <= 0 ? {
2491
+ start,
2492
+ end
2493
+ } : null,
2494
+ onChange: (range) => change(range?.start.toString() ?? "", range?.end.toString() ?? ""),
2495
+ minValue: calendarDate(min) ?? void 0,
2496
+ maxValue: calendarDate(max) ?? void 0,
2497
+ placeholderValue: start ?? end ?? void 0,
2498
+ isDisabled: disabled,
2499
+ isReadOnly: readOnly,
2500
+ isRequired: required,
2501
+ isInvalid: invalid,
2502
+ validationBehavior: "aria",
2503
+ isOpen: open,
2504
+ onOpenChange: setOpen,
2505
+ className: [prefix, className].filter(Boolean).join(" "),
2506
+ children: [/* @__PURE__ */ jsxs(Group, {
2507
+ ref: groupRef,
2508
+ className: [
2509
+ `${prefix}__trigger`,
2510
+ disabled && `${prefix}__trigger--disabled`,
2511
+ readOnly && `${prefix}__trigger--readonly`,
2512
+ invalid && `${prefix}__trigger--invalid`,
2513
+ open && `${prefix}__trigger--open`
2514
+ ].filter(Boolean).join(" "),
2749
2515
  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
2516
+ /* @__PURE__ */ jsx(DateTextInput, {
2517
+ ...inputProps,
2518
+ "aria-label": [strings.startDate, ariaLabel].filter(Boolean).join(" "),
2519
+ value: startValue,
2520
+ onChange: (next) => change(next, endValue ?? "")
2767
2521
  }),
2768
2522
  /* @__PURE__ */ jsx("span", {
2769
- className: "nb-date-range-picker__sep",
2523
+ className: `${prefix}__sep`,
2770
2524
  "aria-hidden": "true",
2771
- children: /* @__PURE__ */ jsx("i", { className: "ph ph-arrow-right" })
2525
+ children: "→"
2772
2526
  }),
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
2527
+ /* @__PURE__ */ jsx(DateTextInput, {
2528
+ ...inputProps,
2529
+ "aria-label": [strings.endDate, ariaLabel].filter(Boolean).join(" "),
2530
+ value: endValue,
2531
+ onChange: (next) => change(startValue ?? "", next)
2789
2532
  }),
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
- })]
2533
+ clearable && (startValue || endValue) && !disabled && !readOnly && /* @__PURE__ */ jsx(Button$1, {
2534
+ slot: null,
2535
+ className: `${prefix}__clear`,
2536
+ "aria-label": strings.clearDateRange,
2537
+ onPress: () => change("", ""),
2538
+ children: "×"
2539
+ }),
2540
+ /* @__PURE__ */ jsx(Button$1, {
2541
+ className: `${prefix}__calendar-btn`,
2542
+ "aria-label": strings.openCalendar,
2543
+ onPress: () => groupRef.current?.querySelector("input")?.focus(),
2544
+ isDisabled: disabled || readOnly,
2545
+ children: /* @__PURE__ */ jsx("i", {
2546
+ "aria-hidden": "true",
2547
+ className: "ph ph-calendar-blank"
2548
+ })
2813
2549
  })
2814
2550
  ]
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", {
2551
+ }), /* @__PURE__ */ jsx(Popover$1, {
2552
+ isNonModal: Boolean(container),
2823
2553
  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();
2554
+ UNSTABLE_portalContainer: container ?? void 0,
2555
+ className: `${prefix}__panel`,
2556
+ offset: 4,
2557
+ children: /* @__PURE__ */ jsxs(CalendarDialog, {
2558
+ ariaLabel: strings.selectDateRange,
2559
+ children: [/* @__PURE__ */ jsx(RangeCalendar, {
2560
+ className: "nb-calendar--range",
2561
+ children: /* @__PURE__ */ jsx(CalendarContent, {})
2562
+ }), /* @__PURE__ */ jsxs("div", {
2563
+ className: `${prefix}__footer`,
2564
+ children: [/* @__PURE__ */ jsx(Button$1, {
2565
+ slot: null,
2566
+ className: `${prefix}__text-button`,
2567
+ onPress: () => {
2568
+ change("", "");
2569
+ setOpen(false);
2901
2570
  },
2902
2571
  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();
2572
+ }), /* @__PURE__ */ jsx(Button$1, {
2573
+ slot: null,
2574
+ className: `${prefix}__text-button`,
2575
+ isDisabled: !dateAllowed(todayIso, min, max),
2576
+ onPress: () => {
2577
+ change(todayIso, todayIso);
2578
+ setOpen(false);
2922
2579
  },
2923
2580
  children: strings.today
2924
2581
  })]
2925
- })
2926
- ]
2927
- }), document.body)
2928
- ]
2582
+ })]
2583
+ })
2584
+ })]
2585
+ })
2929
2586
  });
2930
2587
  }
2931
2588
  //#endregion
2932
2589
  //#region packages/ui/Popover.tsx
2933
2590
  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
- })]
2591
+ const [open, setOpen] = useState(false);
2592
+ const triggerRef = useRef(null);
2593
+ const [restoreFocus, setRestoreFocus] = useState(true);
2594
+ const changeOpen = (next) => {
2595
+ setRestoreFocus(true);
2596
+ setOpen(next);
2597
+ };
2598
+ const container = useOverlayContainer();
2599
+ const triggerNode = trigger({
2600
+ open,
2601
+ toggle: () => changeOpen(!open)
2602
+ });
2603
+ return /* @__PURE__ */ jsx(Popover$2.Root, {
2604
+ open,
2605
+ onOpenChange: (next, details) => {
2606
+ setRestoreFocus(details.reason !== "outside-press" && details.reason !== "focus-out");
2607
+ setOpen(next);
2608
+ },
2609
+ onOpenChangeComplete: (next) => {
2610
+ if (!next && restoreFocus) triggerRef.current?.focus({ preventScroll: true });
2611
+ },
2612
+ children: /* @__PURE__ */ jsxs("div", {
2613
+ className: [
2614
+ "nb-popover",
2615
+ `nb-popover--${align}`,
2616
+ open && "nb-popover--open",
2617
+ className
2618
+ ].filter(Boolean).join(" "),
2619
+ children: [/* @__PURE__ */ jsx(Popover$2.Trigger, {
2620
+ ref: triggerRef,
2621
+ render: isValidElement(triggerNode) ? triggerNode : /* @__PURE__ */ jsx("button", {
2622
+ type: "button",
2623
+ children: triggerNode
2624
+ })
2625
+ }), /* @__PURE__ */ jsx(Popover$2.Portal, {
2626
+ container: container ?? void 0,
2627
+ children: /* @__PURE__ */ jsx(Popover$2.Positioner, {
2628
+ align,
2629
+ sideOffset: 8,
2630
+ className: "nb-popover-positioner",
2631
+ children: /* @__PURE__ */ jsx(Popover$2.Popup, {
2632
+ finalFocus: triggerRef,
2633
+ onKeyDownCapture: (event) => {
2634
+ if (event.key === "Escape") {
2635
+ event.preventDefault();
2636
+ event.stopPropagation();
2637
+ changeOpen(false);
2638
+ }
2639
+ },
2640
+ className: "nb-popover__panel",
2641
+ "aria-label": ariaLabel,
2642
+ children: panel({ close: () => changeOpen(false) })
2643
+ })
2644
+ })
2645
+ })]
2646
+ })
2952
2647
  });
2953
2648
  };
2954
2649
  //#endregion
2650
+ //#region packages/ui/useFloatingPanel.ts
2651
+ /** Style applied to an anchored panel before its first position is computed. */
2652
+ const HIDDEN_PANEL_STYLE = {
2653
+ position: "fixed",
2654
+ visibility: "hidden",
2655
+ margin: 0
2656
+ };
2657
+ function useFloatingPanel(options = {}) {
2658
+ const [open, setOpenState] = useState(false);
2659
+ const [panelStyle, setPanelStyle] = useState(HIDDEN_PANEL_STYLE);
2660
+ const containerRef = useRef(null);
2661
+ const panelRef = useRef(null);
2662
+ const optionsRef = useRef(options);
2663
+ optionsRef.current = options;
2664
+ const anchored = !!options.computeStyle;
2665
+ const dismissEvent = options.dismissEvent ?? "pointerdown";
2666
+ const setOpen = useCallback((next) => {
2667
+ setOpenState(next);
2668
+ if (!next) optionsRef.current.onClose?.();
2669
+ optionsRef.current.onOpenChange?.(next);
2670
+ }, []);
2671
+ const applyStyle = useCallback(() => {
2672
+ const compute = optionsRef.current.computeStyle;
2673
+ if (!compute) return;
2674
+ const style = compute(containerRef.current);
2675
+ if (style) setPanelStyle(style);
2676
+ }, []);
2677
+ const openPanel = useCallback(() => {
2678
+ applyStyle();
2679
+ setOpen(true);
2680
+ }, [applyStyle, setOpen]);
2681
+ const toggle = useCallback(() => open ? setOpen(false) : openPanel(), [
2682
+ open,
2683
+ openPanel,
2684
+ setOpen
2685
+ ]);
2686
+ useEffect(() => {
2687
+ if (!open) return;
2688
+ const handleOutside = (e) => {
2689
+ const target = e.target;
2690
+ if (containerRef.current?.contains(target) || panelRef.current?.contains(target)) return;
2691
+ setOpen(false);
2692
+ };
2693
+ const handleKeyDown = (e) => {
2694
+ if (e.key !== "Escape" || e.defaultPrevented) return;
2695
+ e.preventDefault();
2696
+ e.stopPropagation();
2697
+ setOpen(false);
2698
+ optionsRef.current.onEscape?.(e);
2699
+ };
2700
+ document.addEventListener(dismissEvent, handleOutside);
2701
+ document.addEventListener("keydown", handleKeyDown, true);
2702
+ return () => {
2703
+ document.removeEventListener(dismissEvent, handleOutside);
2704
+ document.removeEventListener("keydown", handleKeyDown, true);
2705
+ };
2706
+ }, [
2707
+ dismissEvent,
2708
+ open,
2709
+ setOpen
2710
+ ]);
2711
+ useLayoutEffect(() => {
2712
+ if (!open || !anchored) return;
2713
+ const update = () => {
2714
+ const container = containerRef.current;
2715
+ if (!container) return;
2716
+ if (optionsRef.current.closeOnViewportExit) {
2717
+ const rect = container.getBoundingClientRect();
2718
+ if ((rect.width > 0 || rect.height > 0) && (rect.top >= window.innerHeight || rect.bottom <= 0)) {
2719
+ setOpen(false);
2720
+ return;
2721
+ }
2722
+ }
2723
+ applyStyle();
2724
+ };
2725
+ update();
2726
+ window.addEventListener("resize", update);
2727
+ window.addEventListener("scroll", update, {
2728
+ capture: true,
2729
+ passive: true
2730
+ });
2731
+ return () => {
2732
+ window.removeEventListener("resize", update);
2733
+ window.removeEventListener("scroll", update, { capture: true });
2734
+ };
2735
+ }, [
2736
+ anchored,
2737
+ applyStyle,
2738
+ open,
2739
+ setOpen
2740
+ ]);
2741
+ return {
2742
+ open,
2743
+ setOpen,
2744
+ toggle,
2745
+ openPanel,
2746
+ containerRef,
2747
+ panelRef,
2748
+ panelStyle
2749
+ };
2750
+ }
2751
+ //#endregion
2955
2752
  //#region packages/ui/Drawer.tsx
2956
2753
  const formatWidth = (value) => {
2957
2754
  if (value === void 0) return void 0;
2958
2755
  return typeof value === "number" ? `${value}px` : value;
2959
2756
  };
2960
- const Drawer = ({ isOpen, onClose, title, width, side = "right", scrim = "subtle", children, footer, closeLabel, scrimLabel, className, "aria-label": ariaLabel }) => {
2757
+ const Drawer = ({ isOpen, busy = false, onClose, title, width, side = "right", scrim = "subtle", children, footer, closeLabel, scrimLabel, className, "aria-label": ariaLabel }) => {
2961
2758
  const strings = useUiStrings();
2962
2759
  const resolvedCloseLabel = closeLabel ?? strings.close;
2963
2760
  const resolvedScrimLabel = scrimLabel ?? strings.closePanel;
2964
2761
  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: [
2762
+ return /* @__PURE__ */ jsxs(ModalSurface, {
2763
+ open: isOpen,
2764
+ onClose,
2765
+ closeOnEscape: !busy,
2766
+ closeOnOutsideClick: !busy,
2767
+ rootClassName: [
2991
2768
  "nb-drawer-root",
2992
2769
  isOpen && "nb-drawer-root--open",
2993
2770
  `nb-drawer-root--${side}`
2994
2771
  ].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);
2772
+ className: ["nb-drawer", className].filter(Boolean).join(" "),
2773
+ scrimClassName: `nb-drawer__scrim nb-drawer__scrim--${scrim}`,
2774
+ scrimLabel: resolvedScrimLabel,
2775
+ labelledBy: title ? titleId : void 0,
2776
+ ariaLabel: !title ? ariaLabel : void 0,
2777
+ style: { width: formatWidth(width) },
2778
+ keepMounted: true,
2779
+ children: [
2780
+ title !== void 0 && /* @__PURE__ */ jsxs("header", {
2781
+ className: "nb-drawer__header",
2782
+ children: [/* @__PURE__ */ jsx("h2", {
2783
+ className: "nb-drawer__title",
2784
+ id: titleId,
2785
+ children: title
2786
+ }), /* @__PURE__ */ jsx(IconButton, {
2787
+ className: "nb-drawer__close",
2788
+ icon: "ph ph-x",
2789
+ label: resolvedCloseLabel,
2790
+ onClick: onClose,
2791
+ disabled: busy
2792
+ })]
2793
+ }),
2794
+ /* @__PURE__ */ jsx("div", {
2795
+ className: "nb-drawer__body",
2796
+ children
2797
+ }),
2798
+ footer && /* @__PURE__ */ jsx("footer", {
2799
+ className: "nb-drawer__footer",
2800
+ children: footer
2801
+ })
2802
+ ]
2803
+ });
3036
2804
  };
3037
2805
  //#endregion
3038
2806
  //#region packages/ui/Timeline.tsx
@@ -3142,7 +2910,7 @@ function Page({ children, fill, wide, narrow, gap = 5, className, ...props }) {
3142
2910
  }
3143
2911
  //#endregion
3144
2912
  //#region packages/ui/PageHeader.tsx
3145
- function PageHeader({ title, subtitle, breadcrumb, breadcrumbSlot, badge, actions, className }) {
2913
+ function PageHeader({ title, subtitle, metadata, breadcrumb, breadcrumbSlot, badge, actions, className }) {
3146
2914
  const breadcrumbNode = breadcrumbSlot ?? (breadcrumb ? /* @__PURE__ */ jsxs("a", {
3147
2915
  href: breadcrumb.href,
3148
2916
  className: "nb-page-header__breadcrumb",
@@ -3161,6 +2929,10 @@ function PageHeader({ title, subtitle, breadcrumb, breadcrumbSlot, badge, action
3161
2929
  className: "nb-page-header__title",
3162
2930
  children: title
3163
2931
  }),
2932
+ metadata && /* @__PURE__ */ jsx("div", {
2933
+ className: "nb-page-header__metadata",
2934
+ children: metadata
2935
+ }),
3164
2936
  subtitle && /* @__PURE__ */ jsx("p", {
3165
2937
  className: "nb-page-header__subtitle",
3166
2938
  children: subtitle
@@ -3230,9 +3002,9 @@ function Col({ children, span, spanSm, spanMd, spanLg, fullWidth, className, ...
3230
3002
  }
3231
3003
  //#endregion
3232
3004
  //#region packages/ui/Section.tsx
3233
- function Section({ title, children, className }) {
3005
+ function Section({ title, children, className, variant = "label" }) {
3234
3006
  return /* @__PURE__ */ jsxs("section", {
3235
- className: joinClasses("nb-section", className),
3007
+ className: joinClasses("nb-section", variant === "panel" && "nb-section--panel", className),
3236
3008
  children: [/* @__PURE__ */ jsx("h2", {
3237
3009
  className: "nb-section__title",
3238
3010
  children: title
@@ -3435,4 +3207,239 @@ function useConfirm() {
3435
3207
  };
3436
3208
  }
3437
3209
  //#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 };
3210
+ //#region packages/ui/Checkbox.tsx
3211
+ /** Native checkbox, including the mixed state used by bulk selection. */
3212
+ const Checkbox = forwardRef(function Checkbox({ label, indeterminate = false, invalid = false, id, className, ...props }, ref) {
3213
+ const generatedId = useId();
3214
+ const inputRef = useRef(null);
3215
+ useEffect(() => {
3216
+ if (inputRef.current) inputRef.current.indeterminate = indeterminate;
3217
+ }, [indeterminate]);
3218
+ return /* @__PURE__ */ jsxs("label", {
3219
+ className: `nb-selection-control${className ? ` ${className}` : ""}`,
3220
+ children: [/* @__PURE__ */ jsx("input", {
3221
+ ...props,
3222
+ id: id ?? generatedId,
3223
+ type: "checkbox",
3224
+ "aria-invalid": props["aria-invalid"] ?? (invalid || void 0),
3225
+ ref: (node) => {
3226
+ inputRef.current = node;
3227
+ if (typeof ref === "function") return ref(node);
3228
+ if (ref) ref.current = node;
3229
+ }
3230
+ }), label && /* @__PURE__ */ jsx("span", { children: label })]
3231
+ });
3232
+ });
3233
+ //#endregion
3234
+ //#region packages/ui/RadioGroup.tsx
3235
+ /** Native radios share a name for browser keyboard navigation and form submission. */
3236
+ function RadioGroup({ label, name, value, options, onChange, orientation = "vertical", required, invalid = false, disabled, className, ...props }) {
3237
+ const generatedName = useId();
3238
+ return /* @__PURE__ */ jsxs("fieldset", {
3239
+ ...props,
3240
+ disabled,
3241
+ "aria-invalid": props["aria-invalid"] ?? (invalid || void 0),
3242
+ className: `nb-radio-group${className ? ` ${className}` : ""}`,
3243
+ children: [label && /* @__PURE__ */ jsx("legend", { children: label }), /* @__PURE__ */ jsx("div", {
3244
+ className: `nb-radio-group__options nb-radio-group__options--${orientation}`,
3245
+ children: options.map((option) => /* @__PURE__ */ jsxs("label", {
3246
+ className: "nb-selection-control",
3247
+ children: [/* @__PURE__ */ jsx("input", {
3248
+ type: "radio",
3249
+ name: name ?? generatedName,
3250
+ value: option.value,
3251
+ checked: value === option.value,
3252
+ disabled: disabled || option.disabled,
3253
+ required,
3254
+ onChange: () => onChange(option.value)
3255
+ }), /* @__PURE__ */ jsx("span", { children: option.label })]
3256
+ }, option.value))
3257
+ })]
3258
+ });
3259
+ }
3260
+ //#endregion
3261
+ //#region packages/ui/Tabs.tsx
3262
+ function Tabs({ items, value, onChange, "aria-label": ariaLabel, orientation = "horizontal", activationMode = "automatic", keepMounted = false, className }) {
3263
+ const id = useId();
3264
+ const listRef = useRef(null);
3265
+ const [focusedValue, setFocusedValue] = useState(null);
3266
+ const selectedIndex = items.findIndex((item) => item.value === value && !item.disabled);
3267
+ const focusedIndex = items.findIndex((item) => item.value === focusedValue && !item.disabled);
3268
+ const tabStop = activationMode === "manual" && focusedIndex >= 0 ? focusedIndex : selectedIndex >= 0 ? selectedIndex : items.findIndex((item) => !item.disabled);
3269
+ return /* @__PURE__ */ jsxs("div", {
3270
+ className: `nb-tabs nb-tabs--${orientation}${className ? ` ${className}` : ""}`,
3271
+ children: [/* @__PURE__ */ jsx("div", {
3272
+ ref: listRef,
3273
+ role: "tablist",
3274
+ "aria-label": ariaLabel,
3275
+ "aria-orientation": orientation,
3276
+ className: "nb-tabs__list",
3277
+ children: items.map((item, index) => /* @__PURE__ */ jsx("button", {
3278
+ type: "button",
3279
+ role: "tab",
3280
+ id: `${id}-tab-${index}`,
3281
+ "aria-controls": `${id}-panel-${index}`,
3282
+ "aria-selected": index === selectedIndex,
3283
+ disabled: item.disabled,
3284
+ tabIndex: index === tabStop ? 0 : -1,
3285
+ className: "nb-tabs__tab",
3286
+ onFocus: () => setFocusedValue(item.value),
3287
+ onClick: () => onChange(item.value),
3288
+ onKeyDown: (event) => {
3289
+ const nextKey = orientation === "horizontal" ? "ArrowRight" : "ArrowDown";
3290
+ if (![
3291
+ nextKey,
3292
+ orientation === "horizontal" ? "ArrowLeft" : "ArrowUp",
3293
+ "Home",
3294
+ "End"
3295
+ ].includes(event.key)) return;
3296
+ event.preventDefault();
3297
+ const enabled = items.map((entry, i) => entry.disabled ? -1 : i).filter((i) => i >= 0);
3298
+ const position = enabled.indexOf(index);
3299
+ 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];
3300
+ if (next === void 0) return;
3301
+ listRef.current?.querySelectorAll("[role=\"tab\"]")[next]?.focus();
3302
+ if (activationMode === "automatic") onChange(items[next].value);
3303
+ },
3304
+ children: item.label
3305
+ }, item.value))
3306
+ }), items.map((item, index) => /* @__PURE__ */ jsx("div", {
3307
+ role: "tabpanel",
3308
+ id: `${id}-panel-${index}`,
3309
+ "aria-labelledby": `${id}-tab-${index}`,
3310
+ hidden: index !== selectedIndex,
3311
+ tabIndex: 0,
3312
+ className: "nb-tabs__panel",
3313
+ children: keepMounted || index === selectedIndex ? item.content : null
3314
+ }, item.value))]
3315
+ });
3316
+ }
3317
+ //#endregion
3318
+ //#region packages/ui/Spinner.tsx
3319
+ function Spinner({ label, size = "md", className, ...props }) {
3320
+ return /* @__PURE__ */ jsx("span", {
3321
+ ...props,
3322
+ className: `nb-spinner nb-spinner--${size}${className ? ` ${className}` : ""}`,
3323
+ role: label ? "status" : void 0,
3324
+ "aria-label": label,
3325
+ "aria-hidden": label ? void 0 : true
3326
+ });
3327
+ }
3328
+ //#endregion
3329
+ //#region packages/ui/Progress.tsx
3330
+ /** Omit value for indeterminate progress; max defaults to 100. */
3331
+ function Progress({ label, id, max = 100, className, ...props }) {
3332
+ const generatedId = useId();
3333
+ const progressId = id ?? generatedId;
3334
+ return /* @__PURE__ */ jsxs("div", {
3335
+ className: "nb-progress-field",
3336
+ children: [label && /* @__PURE__ */ jsx("label", {
3337
+ htmlFor: progressId,
3338
+ children: label
3339
+ }), /* @__PURE__ */ jsx("progress", {
3340
+ ...props,
3341
+ id: progressId,
3342
+ max,
3343
+ className: `nb-progress${className ? ` ${className}` : ""}`
3344
+ })]
3345
+ });
3346
+ }
3347
+ //#endregion
3348
+ //#region packages/ui/Tooltip.tsx
3349
+ const TooltipProvider = Tooltip$1.Provider;
3350
+ /** Uses the existing child as the trigger without adding a nested button. */
3351
+ function Tooltip({ children, content, side = "top", delay, disabled, className }) {
3352
+ const overlayContainer = useOverlayContainer();
3353
+ const id = useId();
3354
+ const [open, setOpen] = useState(false);
3355
+ const description = [children.props["aria-describedby"], open && !disabled ? id : void 0].filter(Boolean).join(" ") || void 0;
3356
+ return /* @__PURE__ */ jsxs(Tooltip$1.Root, {
3357
+ open,
3358
+ disabled,
3359
+ onOpenChange: setOpen,
3360
+ children: [/* @__PURE__ */ jsx(Tooltip$1.Trigger, {
3361
+ render: cloneElement(children, { "aria-describedby": description }),
3362
+ onKeyDownCapture: (event) => {
3363
+ if (open && event.key === "Escape") {
3364
+ event.stopPropagation();
3365
+ setOpen(false);
3366
+ }
3367
+ },
3368
+ delay
3369
+ }), /* @__PURE__ */ jsx(Tooltip$1.Portal, {
3370
+ container: overlayContainer ?? void 0,
3371
+ children: /* @__PURE__ */ jsx(Tooltip$1.Positioner, {
3372
+ side,
3373
+ sideOffset: 8,
3374
+ className: "nb-tooltip-positioner",
3375
+ children: /* @__PURE__ */ jsx(Tooltip$1.Popup, {
3376
+ id,
3377
+ role: "tooltip",
3378
+ className: `nb-tooltip${className ? ` ${className}` : ""}`,
3379
+ children: content
3380
+ })
3381
+ })
3382
+ })]
3383
+ });
3384
+ }
3385
+ //#endregion
3386
+ //#region packages/ui/TimePicker.tsx
3387
+ const timeValue = (value) => {
3388
+ if (!value) return null;
3389
+ try {
3390
+ return parseTime(value);
3391
+ } catch {
3392
+ return null;
3393
+ }
3394
+ };
3395
+ /** Accessible segmented time entry. Values never pass through Date or a timezone. */
3396
+ const TimePicker = forwardRef(function TimePicker({ id, name, value, onChange, onBlur, min, max, locale, hourCycle, granularity = "minute", disabled, readOnly, required, invalid, className, ariaLabel }, ref) {
3397
+ const strings = useUiStrings();
3398
+ return /* @__PURE__ */ jsx(I18nProvider, {
3399
+ locale: getDateLocale(locale),
3400
+ children: /* @__PURE__ */ jsx(TimeField, {
3401
+ id,
3402
+ name,
3403
+ "aria-label": ariaLabel ?? strings.selectTime,
3404
+ value: timeValue(value),
3405
+ onChange: (next) => onChange?.(next ? next.toString().slice(0, granularity === "second" ? 8 : 5) : ""),
3406
+ onBlur,
3407
+ minValue: timeValue(min) ?? void 0,
3408
+ maxValue: timeValue(max) ?? void 0,
3409
+ granularity,
3410
+ hourCycle,
3411
+ isDisabled: disabled,
3412
+ isReadOnly: readOnly,
3413
+ isRequired: required,
3414
+ isInvalid: invalid,
3415
+ validationBehavior: "aria",
3416
+ className: ["nb-time-picker", className].filter(Boolean).join(" "),
3417
+ children: /* @__PURE__ */ jsx(DateInput, {
3418
+ ref,
3419
+ className: "nb-time-picker__input",
3420
+ children: (segment) => /* @__PURE__ */ jsx(DateSegment, {
3421
+ segment,
3422
+ className: "nb-time-picker__segment"
3423
+ })
3424
+ })
3425
+ })
3426
+ });
3427
+ });
3428
+ //#endregion
3429
+ //#region packages/ui/DetailLayout.tsx
3430
+ /** Responsive main/aside composition for record detail pages. */
3431
+ function DetailLayout({ children, aside, asideLabel, className }) {
3432
+ return /* @__PURE__ */ jsxs("div", {
3433
+ className: joinClasses("nb-detail-layout", className),
3434
+ children: [/* @__PURE__ */ jsx("div", {
3435
+ className: "nb-detail-layout__main",
3436
+ children
3437
+ }), /* @__PURE__ */ jsx("aside", {
3438
+ className: "nb-detail-layout__aside",
3439
+ "aria-label": asideLabel,
3440
+ children: aside
3441
+ })]
3442
+ });
3443
+ }
3444
+ //#endregion
3445
+ 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 };