@zovaris/sephiro 0.9.0 → 0.11.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.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { cn } from "cn";
2
2
  import { Fragment, cloneElement, createContext, isValidElement, useCallback, useContext, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";
3
3
  import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
4
- import { ArrowDownIcon, ArrowUpRightIcon, ArrowsHorizontalIcon, CaretDownIcon, CaretLeftIcon, CaretRightIcon, CaretUpIcon, CheckIcon, FileCodeIcon, FileIcon, FileTextIcon, ImageIcon, InfoIcon, MagnifyingGlassIcon, MinusIcon, MusicNotesIcon, PlusIcon, TrayIcon, VideoIcon, WarningIcon, XIcon } from "@phosphor-icons/react";
4
+ import { ArrowDownIcon, ArrowUpIcon, ArrowUpRightIcon, ArrowsHorizontalIcon, CalendarBlankIcon, CaretDownIcon, CaretLeftIcon, CaretRightIcon, CaretUpIcon, CheckIcon, FileCodeIcon, FileIcon, FileTextIcon, ImageIcon, InfoIcon, MagnifyingGlassIcon, MinusIcon, MusicNotesIcon, PlusIcon, StopIcon, TrayIcon, VideoIcon, WarningIcon, XIcon } from "@phosphor-icons/react";
5
5
  import { createPortal } from "react-dom";
6
6
  import { Toaster, toast } from "sonner";
7
7
  //#region src/lib/node.ts
@@ -133,16 +133,32 @@ function usePortaled() {
133
133
  }, []);
134
134
  return portaled;
135
135
  }
136
+ function anchorArea(side, align) {
137
+ if (side === "left" || side === "right") return `${side} span-all`;
138
+ return `${side} ${align === "center" ? "span-all" : align === "start" ? "span-right" : "span-left"}`;
139
+ }
136
140
  /**
137
- * Measures trigger and content, then pins the overlay to fixed coordinates.
138
- * Flips, clamps, and re-measures on scroll (capture, so inner scrollers
139
- * count) and resize while active.
141
+ * Uses native CSS anchors when supported; otherwise measures fixed coordinates.
142
+ * Native anchors follow scrolling without JS; older browsers re-measure on
143
+ * scroll (including inner scrollers). Both paths react to size changes.
140
144
  */
141
145
  function useOverlayPosition(triggerRef, contentRef, active, placement = {}) {
142
146
  const { side = "bottom", align = "start", offset = 4, padding = 8, matchWidth = false } = placement;
143
147
  const frameRef = useRef(null);
148
+ const anchorName = `--sph-overlay-${useId().replace(/[^a-zA-Z0-9_-]/g, "")}`;
144
149
  useIsoLayoutEffect(() => {
145
150
  if (!active) return;
151
+ const trigger = triggerRef.current;
152
+ const content = contentRef.current;
153
+ if (!trigger || !content) return;
154
+ inheritMotionScope(trigger, content);
155
+ const native = typeof CSS !== "undefined" && CSS.supports("anchor-name", anchorName) && CSS.supports("position-area", "bottom span-right") && CSS.supports("position-try-fallbacks", "flip-block");
156
+ const previousAnchor = trigger.style.getPropertyValue("anchor-name");
157
+ if (native) {
158
+ trigger.style.setProperty("anchor-name", previousAnchor && previousAnchor !== "none" ? `${previousAnchor}, ${anchorName}` : anchorName);
159
+ content.style.setProperty("position-anchor", anchorName);
160
+ content.style.setProperty("position-visibility", "anchors-visible");
161
+ }
146
162
  const update = () => {
147
163
  frameRef.current = null;
148
164
  const trigger = triggerRef.current;
@@ -164,32 +180,65 @@ function useOverlayPosition(triggerRef, contentRef, active, placement = {}) {
164
180
  padding
165
181
  });
166
182
  const style = content.style;
167
- style.left = `${resolved.left}px`;
168
- style.top = `${resolved.top}px`;
169
- style.right = "auto";
170
- style.bottom = "auto";
171
- style.translate = "none";
183
+ if (native) {
184
+ style.inset = "auto";
185
+ style.translate = "none";
186
+ style.setProperty("position-area", anchorArea(resolved.side, align));
187
+ style.setProperty("position-try-fallbacks", side === "left" || side === "right" ? "flip-inline, flip-block, flip-inline flip-block" : "flip-block, flip-inline, flip-block flip-inline");
188
+ style.margin = `${padding}px`;
189
+ if (side === "top" || side === "bottom") {
190
+ if (align === "start") style.marginLeft = "0";
191
+ if (align === "end") style.marginRight = "0";
192
+ }
193
+ style.setProperty(`margin-${resolved.side === "bottom" ? "top" : resolved.side === "top" ? "bottom" : resolved.side === "right" ? "left" : "right"}`, `${offset}px`);
194
+ style.justifySelf = side === "left" || side === "right" ? "normal" : align === "center" ? "anchor-center" : align;
195
+ style.alignSelf = side === "left" || side === "right" ? "anchor-center" : "normal";
196
+ } else {
197
+ style.left = `${resolved.left}px`;
198
+ style.top = `${resolved.top}px`;
199
+ style.right = "auto";
200
+ style.bottom = "auto";
201
+ style.translate = "none";
202
+ }
172
203
  style.transformOrigin = overlayOrigin(resolved.side, align);
173
204
  content.dataset.side = resolved.side;
174
205
  };
175
206
  const schedule = () => {
176
207
  if (frameRef.current === null) frameRef.current = requestAnimationFrame(update);
177
208
  };
178
- inheritMotionScope(triggerRef.current, contentRef.current);
179
209
  update();
210
+ const observer = new ResizeObserver(schedule);
211
+ observer.observe(trigger);
212
+ observer.observe(content);
180
213
  window.addEventListener("resize", schedule);
181
- document.addEventListener("scroll", schedule, {
214
+ if (!native) document.addEventListener("scroll", schedule, {
182
215
  capture: true,
183
216
  passive: true
184
217
  });
185
218
  return () => {
219
+ observer.disconnect();
186
220
  window.removeEventListener("resize", schedule);
187
221
  document.removeEventListener("scroll", schedule, { capture: true });
188
222
  if (frameRef.current !== null) cancelAnimationFrame(frameRef.current);
223
+ frameRef.current = null;
224
+ if (native) {
225
+ if (previousAnchor) trigger.style.setProperty("anchor-name", previousAnchor);
226
+ else trigger.style.removeProperty("anchor-name");
227
+ for (const name of [
228
+ "position-anchor",
229
+ "position-area",
230
+ "position-try-fallbacks",
231
+ "position-visibility",
232
+ "margin",
233
+ "justify-self",
234
+ "align-self"
235
+ ]) content.style.removeProperty(name);
236
+ }
189
237
  };
190
238
  }, [
191
239
  active,
192
240
  align,
241
+ anchorName,
193
242
  matchWidth,
194
243
  offset,
195
244
  padding,
@@ -207,9 +256,14 @@ const SPEED_TOKEN = {
207
256
  };
208
257
  /** Extra time granted to an exit animation so React never cuts it short. */
209
258
  const EXIT_FRAME_BUDGET = 40;
210
- /** Parses a CSS time string ("180ms", "0.18s", "0ms") into milliseconds. */
259
+ /**
260
+ * Parses a CSS time string ("180ms", "0.18s", "0ms") into milliseconds.
261
+ *
262
+ * The leading digit is optional because a minifier shortens `180ms` to `.18s`
263
+ * in production, and that is what `getComputedStyle` gives back there.
264
+ */
211
265
  function parseDurationMs(value) {
212
- const match = value.trim().match(/^(\d+(?:\.\d+)?)(ms|s)?$/);
266
+ const match = value.trim().match(/^(\d*\.?\d+)(ms|s)?$/);
213
267
  if (!match) return 0;
214
268
  const amount = Number.parseFloat(match[1]);
215
269
  if (!Number.isFinite(amount) || amount <= 0) return 0;
@@ -343,24 +397,36 @@ function Avatar({ src, name, size = "md", status, className, ...props }) {
343
397
  }
344
398
  //#endregion
345
399
  //#region src/atoms/Badge/index.tsx
346
- function Badge({ variant = "neutral", size = "sm", className, children, ...props }) {
347
- return /* @__PURE__ */ jsx("span", {
400
+ function Badge({ variant = "neutral", size = "sm", onRemove, removeLabel, className, children, ...props }) {
401
+ return /* @__PURE__ */ jsxs("span", {
348
402
  ...node(props),
349
403
  className: cn("sph-badge", className),
350
404
  "data-variant": variant,
351
405
  "data-size": size,
352
- children: node(children)
406
+ "data-removable": onRemove ? true : void 0,
407
+ children: [node(children), onRemove ? /* @__PURE__ */ jsx("button", {
408
+ type: "button",
409
+ className: "sph-badge__remove",
410
+ "aria-label": removeLabel ?? (typeof children === "string" ? `Remove ${children}` : "Remove"),
411
+ onClick: onRemove,
412
+ children: /* @__PURE__ */ jsx(XIcon, {
413
+ size: 10,
414
+ "aria-hidden": "true"
415
+ })
416
+ }) : null]
353
417
  });
354
418
  }
355
419
  //#endregion
356
420
  //#region src/atoms/Spinner/index.tsx
357
- function Spinner({ size = "md", label, className, ...props }) {
421
+ function Spinner({ size = "md", label, variant = "ring", className, ...props }) {
358
422
  return /* @__PURE__ */ jsx("span", {
359
423
  ...node(props),
360
- className: cn("sph-spinner", `sph-spinner--${size}`, className),
424
+ className: cn("sph-spinner", `sph-spinner--${size}`, variant === "dots" && "sph-spinner--dots", className),
425
+ "data-variant": variant === "dots" ? "dots" : void 0,
361
426
  role: label ? "status" : void 0,
362
427
  "aria-label": label,
363
- "aria-hidden": label ? void 0 : true
428
+ "aria-hidden": label ? void 0 : true,
429
+ children: variant === "dots" && /* @__PURE__ */ jsx("span", { "aria-hidden": "true" })
364
430
  });
365
431
  }
366
432
  //#endregion
@@ -466,10 +532,11 @@ function Input({ invalid = false, size = "md", className, "aria-invalid": ariaIn
466
532
  }
467
533
  //#endregion
468
534
  //#region src/atoms/Kbd/index.tsx
469
- function Kbd({ keys, className }) {
535
+ function Kbd({ keys, variant = "solid", className }) {
470
536
  const caps = Array.isArray(keys) ? keys : [keys];
471
537
  return /* @__PURE__ */ jsx("kbd", {
472
538
  className: cn("sph-kbd", className),
539
+ "data-variant": variant,
473
540
  children: caps.map((cap, index) => /* @__PURE__ */ jsx("kbd", {
474
541
  className: "sph-kbd__key",
475
542
  children: node(cap)
@@ -677,14 +744,14 @@ function Accordion({ items, type = "single", value, defaultValue, onValueChange,
677
744
  });
678
745
  }
679
746
  //#endregion
680
- //#region src/molecules/Alert/index.tsx
681
- const alertIcons = {
682
- info: /* @__PURE__ */ jsx(InfoIcon, { size: 16 }),
683
- success: /* @__PURE__ */ jsx(CheckIcon, { size: 16 }),
684
- warning: /* @__PURE__ */ jsx(WarningIcon, { size: 16 }),
685
- danger: /* @__PURE__ */ jsx(XIcon, { size: 16 })
747
+ //#region src/molecules/Notice/index.tsx
748
+ const noticeIcons = {
749
+ info: /* @__PURE__ */ jsx(InfoIcon, { size: 14 }),
750
+ success: /* @__PURE__ */ jsx(CheckIcon, { size: 14 }),
751
+ warning: /* @__PURE__ */ jsx(WarningIcon, { size: 14 }),
752
+ danger: /* @__PURE__ */ jsx(XIcon, { size: 14 })
686
753
  };
687
- function Alert({ variant = "info", title, children, dismissible = false, onDismiss, className, role, ...props }) {
754
+ function Notice({ variant = "info", title, children, dismissible = false, onDismiss, className, role, ...props }) {
688
755
  const rootRef = useRef(null);
689
756
  const timerRef = useRef(void 0);
690
757
  const [dismissing, setDismissing] = useState(false);
@@ -708,30 +775,30 @@ function Alert({ variant = "info", title, children, dismissible = false, onDismi
708
775
  return /* @__PURE__ */ jsxs("div", {
709
776
  ref: rootRef,
710
777
  ...node(props),
711
- className: cn("sph-alert", className),
778
+ className: cn("sph-notice", className),
712
779
  "data-variant": variant,
713
780
  "data-state": dismissing ? "closed" : "open",
714
781
  role: role ?? (variant === "danger" ? "alert" : "status"),
715
782
  "aria-live": role ? void 0 : variant === "danger" ? "assertive" : "polite",
716
783
  children: [
717
784
  /* @__PURE__ */ jsx("span", {
718
- className: "sph-alert__icon",
785
+ className: "sph-notice__icon",
719
786
  "aria-hidden": "true",
720
- children: alertIcons[variant]
787
+ children: noticeIcons[variant]
721
788
  }),
722
789
  /* @__PURE__ */ jsxs("div", {
723
- className: "sph-alert__body",
790
+ className: "sph-notice__body",
724
791
  children: [title !== void 0 && /* @__PURE__ */ jsx("p", {
725
- className: "sph-alert__title",
792
+ className: "sph-notice__title",
726
793
  children: node(title)
727
794
  }), children !== void 0 && /* @__PURE__ */ jsx("div", {
728
- className: "sph-alert__content",
795
+ className: "sph-notice__content",
729
796
  children: node(children)
730
797
  })]
731
798
  }),
732
799
  dismissible && /* @__PURE__ */ jsx("button", {
733
800
  type: "button",
734
- className: "sph-alert__dismiss",
801
+ className: "sph-notice__dismiss",
735
802
  "aria-label": "Dismiss notification",
736
803
  onClick: requestDismiss,
737
804
  children: /* @__PURE__ */ jsx(XIcon, {
@@ -742,7 +809,6 @@ function Alert({ variant = "info", title, children, dismissible = false, onDismi
742
809
  ]
743
810
  });
744
811
  }
745
- const Notice = Alert;
746
812
  //#endregion
747
813
  //#region src/molecules/Attachment/index.tsx
748
814
  const IMAGE_EXT = [
@@ -1001,7 +1067,7 @@ const DAYS_IN_MONTH = [
1001
1067
  30,
1002
1068
  31
1003
1069
  ];
1004
- const pad = (value) => String(value).padStart(2, "0");
1070
+ const pad$1 = (value) => String(value).padStart(2, "0");
1005
1071
  function isLeapYear(year) {
1006
1072
  return year % 4 === 0 && year % 100 !== 0 || year % 400 === 0;
1007
1073
  }
@@ -1015,13 +1081,13 @@ function shiftMonth(month, delta) {
1015
1081
  const index = mon - 1 + delta;
1016
1082
  const nextYear = year + Math.floor(index / 12);
1017
1083
  const nextMonth = (index % 12 + 12) % 12;
1018
- return `${nextYear}-${pad(nextMonth + 1)}`;
1084
+ return `${nextYear}-${pad$1(nextMonth + 1)}`;
1019
1085
  }
1020
1086
  /** Shifts a `YYYY-MM-DD` day by a number of days (UTC math, timezone safe). */
1021
1087
  function shiftDay(day, delta) {
1022
1088
  const [year, mon, date] = day.split("-").map(Number);
1023
1089
  const next = new Date(Date.UTC(year, mon - 1, date + delta));
1024
- return `${next.getUTCFullYear()}-${pad(next.getUTCMonth() + 1)}-${pad(next.getUTCDate())}`;
1090
+ return `${next.getUTCFullYear()}-${pad$1(next.getUTCMonth() + 1)}-${pad$1(next.getUTCDate())}`;
1025
1091
  }
1026
1092
  /**
1027
1093
  * Grid cells for a month: leading blanks for the offset, then one
@@ -1031,13 +1097,13 @@ function monthGrid(month, weekStartsOn) {
1031
1097
  const [year, mon] = month.split("-").map(Number);
1032
1098
  const offset = (new Date(Date.UTC(year, mon - 1, 1)).getUTCDay() - weekStartsOn + 7) % 7;
1033
1099
  const cells = Array.from({ length: offset }, () => null);
1034
- for (let day = 1; day <= daysInMonth(month); day++) cells.push(`${month}-${pad(day)}`);
1100
+ for (let day = 1; day <= daysInMonth(month); day++) cells.push(`${month}-${pad$1(day)}`);
1035
1101
  return cells;
1036
1102
  }
1037
1103
  function shiftMonthDay(day, delta) {
1038
1104
  const month = shiftMonth(day.slice(0, 7), delta);
1039
1105
  const date = Math.min(Number(day.slice(8, 10)), daysInMonth(month));
1040
- return `${month}-${pad(date)}`;
1106
+ return `${month}-${pad$1(date)}`;
1041
1107
  }
1042
1108
  function weekday(day) {
1043
1109
  const [year, mon, date] = day.split("-").map(Number);
@@ -1068,7 +1134,7 @@ function rangeSpan(range, hover = null) {
1068
1134
  }
1069
1135
  function localToday() {
1070
1136
  const now = /* @__PURE__ */ new Date();
1071
- return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
1137
+ return `${now.getFullYear()}-${pad$1(now.getMonth() + 1)}-${pad$1(now.getDate())}`;
1072
1138
  }
1073
1139
  const EMPTY_RANGE = {
1074
1140
  start: null,
@@ -1146,6 +1212,7 @@ function Calendar({ value, onValueChange, month, onMonthChange, min, max, weekSt
1146
1212
  return /* @__PURE__ */ jsxs("button", {
1147
1213
  type: "button",
1148
1214
  role: "gridcell",
1215
+ className: "sph-calendar__day",
1149
1216
  "data-date": day,
1150
1217
  "data-today": day === today || void 0,
1151
1218
  "data-in-range": inSpan || void 0,
@@ -1833,8 +1900,20 @@ function ContextMenu({ children, items, onSelect, disabled = false, label = "Con
1833
1900
  const target = event.target;
1834
1901
  if (!rootRef.current?.contains(target) && !contentRef.current?.contains(target)) close();
1835
1902
  };
1903
+ const handleScroll = (event) => {
1904
+ if (!contentRef.current?.contains(event.target)) close();
1905
+ };
1836
1906
  document.addEventListener("pointerdown", handlePointerDown);
1837
- return () => document.removeEventListener("pointerdown", handlePointerDown);
1907
+ document.addEventListener("scroll", handleScroll, {
1908
+ capture: true,
1909
+ passive: true
1910
+ });
1911
+ window.addEventListener("resize", close);
1912
+ return () => {
1913
+ document.removeEventListener("pointerdown", handlePointerDown);
1914
+ document.removeEventListener("scroll", handleScroll, { capture: true });
1915
+ window.removeEventListener("resize", close);
1916
+ };
1838
1917
  }, [open]);
1839
1918
  useEffect(() => {
1840
1919
  if (!open) return;
@@ -1847,7 +1926,12 @@ function ContextMenu({ children, items, onSelect, disabled = false, label = "Con
1847
1926
  const el = contentRef.current;
1848
1927
  if (!present || !portaled || !el) return;
1849
1928
  inheritScope(rootRef.current, el);
1850
- const rect = el.getBoundingClientRect();
1929
+ const rect = {
1930
+ right: coords.x + el.offsetWidth,
1931
+ bottom: coords.y + el.offsetHeight,
1932
+ width: el.offsetWidth,
1933
+ height: el.offsetHeight
1934
+ };
1851
1935
  const margin = 8;
1852
1936
  const flipX = rect.right > window.innerWidth - margin;
1853
1937
  const flipY = rect.bottom > window.innerHeight - margin;
@@ -1855,7 +1939,11 @@ function ContextMenu({ children, items, onSelect, disabled = false, label = "Con
1855
1939
  if (flipY) el.style.top = `${Math.max(margin, coords.y - rect.height)}px`;
1856
1940
  el.style.transformOrigin = `${flipX ? "right" : "left"} ${flipY ? "bottom" : "top"}`;
1857
1941
  el.dataset.side = flipY ? "top" : "bottom";
1858
- }, [present, coords]);
1942
+ }, [
1943
+ present,
1944
+ portaled,
1945
+ coords
1946
+ ]);
1859
1947
  return /* @__PURE__ */ jsxs("div", {
1860
1948
  ...node(props),
1861
1949
  ref: rootRef,
@@ -1954,7 +2042,7 @@ const modals = createLayerStack();
1954
2042
  * themselves (clear a query, pop a level) before closing.
1955
2043
  */
1956
2044
  function useFocusTrap(ref, active, initial, options = {}) {
1957
- const { fallbackToContainer = false } = options;
2045
+ const { fallbackToContainer = false, trap = true } = options;
1958
2046
  const initialRef = useRef(initial);
1959
2047
  useEffect(() => {
1960
2048
  initialRef.current = initial;
@@ -1969,10 +2057,10 @@ function useFocusTrap(ref, active, initial, options = {}) {
1969
2057
  const resolve = initialRef.current;
1970
2058
  const explicit = typeof resolve === "function" ? resolve() : resolve?.current;
1971
2059
  if (!explicit && container.contains(document.activeElement)) return;
1972
- (explicit ?? focusable(container)[0] ?? (fallbackToContainer ? container : void 0))?.focus();
2060
+ (explicit ?? focusable(container)[0] ?? (fallbackToContainer ? container : void 0))?.focus({ preventScroll: true });
1973
2061
  });
1974
2062
  const handleKeyDown = (event) => {
1975
- if (event.key !== "Tab" || traps.top() !== layer) return;
2063
+ if (!trap || event.key !== "Tab" || traps.top() !== layer) return;
1976
2064
  const container = ref.current;
1977
2065
  const focused = document.activeElement;
1978
2066
  const lost = !focused || focused === document.body;
@@ -1990,7 +2078,8 @@ function useFocusTrap(ref, active, initial, options = {}) {
1990
2078
  }, [
1991
2079
  active,
1992
2080
  fallbackToContainer,
1993
- ref
2081
+ ref,
2082
+ trap
1994
2083
  ]);
1995
2084
  }
1996
2085
  function canReceiveFocus(element) {
@@ -2091,11 +2180,13 @@ function inertTargets(keep, root, owned = /* @__PURE__ */ new Set()) {
2091
2180
  }
2092
2181
  const inerted = /* @__PURE__ */ new Set();
2093
2182
  function syncInert() {
2094
- const top = modals.top()?.element;
2183
+ const layer = modals.top();
2184
+ const top = layer?.element;
2185
+ const root = layer?.root ?? document.body;
2095
2186
  const next = /* @__PURE__ */ new Set();
2096
- if (top && document.body.contains(top)) {
2097
- const regions = Array.from(document.body.querySelectorAll(LIVE_REGION_SELECTOR)).filter((region) => !region.contains(top) && !top.contains(region));
2098
- for (const element of inertTargets([top, ...regions], document.body, inerted)) next.add(element);
2187
+ if (top && root.contains(top)) {
2188
+ const regions = Array.from(root.querySelectorAll(LIVE_REGION_SELECTOR)).filter((region) => !region.contains(top) && !top.contains(region));
2189
+ for (const element of inertTargets([top, ...regions], root, inerted)) next.add(element);
2099
2190
  }
2100
2191
  for (const element of inerted) if (!next.has(element)) {
2101
2192
  element.removeAttribute("inert");
@@ -2106,13 +2197,16 @@ function syncInert() {
2106
2197
  inerted.add(element);
2107
2198
  }
2108
2199
  }
2109
- function useModalLayer(ref, active) {
2200
+ function useModalLayer(ref, active, scope = "page") {
2110
2201
  const layerRef = useRef(null);
2111
2202
  const handle = useRef(null);
2112
2203
  handle.current ??= { isTopmost: () => layerRef.current !== null && modals.top() === layerRef.current };
2113
2204
  useEffect(() => {
2114
2205
  if (!active) return;
2115
- const layer = { element: ref.current };
2206
+ const layer = {
2207
+ element: ref.current,
2208
+ root: scope === "local" ? ref.current?.closest("[data-sph-modal-scope]") ?? ref.current?.parentElement?.parentElement ?? void 0 : void 0
2209
+ };
2116
2210
  layerRef.current = layer;
2117
2211
  const release = modals.push(layer);
2118
2212
  syncInert();
@@ -2121,24 +2215,40 @@ function useModalLayer(ref, active) {
2121
2215
  if (layerRef.current === layer) layerRef.current = null;
2122
2216
  syncInert();
2123
2217
  };
2124
- }, [active, ref]);
2218
+ }, [
2219
+ active,
2220
+ ref,
2221
+ scope
2222
+ ]);
2125
2223
  return handle.current;
2126
2224
  }
2127
2225
  //#endregion
2128
2226
  //#region src/molecules/Dialog/index.tsx
2129
- function Dialog({ open, onClose, title, description, children, footer, closeLabel = "Close dialog", closeOnOverlayClick = true, closeOnEscape = true, initialFocus, returnFocus = true, className }) {
2227
+ function Dialog({ open, onClose, title, description, children, footer, closeLabel = "Close dialog", closeOnOverlayClick = true, closeOnEscape = true, initialFocus, returnFocus = true, scope = "page", className }) {
2130
2228
  const id = useId();
2131
2229
  const titleId = `${id}-title`;
2132
2230
  const descriptionId = description !== void 0 ? `${id}-description` : void 0;
2133
2231
  const { present, state, ref: dialogRef } = usePresence(open);
2232
+ const backdropRef = useRef(null);
2233
+ const portaled = usePortaled();
2234
+ useIsoLayoutEffect(() => {
2235
+ if (scope === "page" && present && portaled) inheritScope(document.activeElement, backdropRef.current);
2236
+ }, [
2237
+ present,
2238
+ portaled,
2239
+ scope
2240
+ ]);
2134
2241
  const active = open && present;
2135
- const layer = useModalLayer(dialogRef, active);
2136
- useFocusTrap(dialogRef, active, initialFocus, { fallbackToContainer: true });
2242
+ const layer = useModalLayer(dialogRef, active, scope);
2243
+ useFocusTrap(dialogRef, active, initialFocus, {
2244
+ fallbackToContainer: true,
2245
+ trap: scope === "page"
2246
+ });
2137
2247
  useReturnFocus(present, {
2138
2248
  ref: dialogRef,
2139
2249
  returnFocus
2140
2250
  });
2141
- useScrollLock(present);
2251
+ useScrollLock(present && scope === "page");
2142
2252
  useEffect(() => {
2143
2253
  if (!open || !closeOnEscape) return;
2144
2254
  const handleKeyDown = (event) => {
@@ -2156,7 +2266,9 @@ function Dialog({ open, onClose, title, description, children, footer, closeLabe
2156
2266
  open
2157
2267
  ]);
2158
2268
  if (!present) return null;
2159
- return /* @__PURE__ */ jsx("div", {
2269
+ const content = /* @__PURE__ */ jsx("div", {
2270
+ ref: backdropRef,
2271
+ "data-scope": scope,
2160
2272
  className: "sph-dialog__backdrop",
2161
2273
  "data-state": state,
2162
2274
  role: "presentation",
@@ -2167,7 +2279,7 @@ function Dialog({ open, onClose, title, description, children, footer, closeLabe
2167
2279
  ref: dialogRef,
2168
2280
  className: cn("sph-dialog", className),
2169
2281
  role: "dialog",
2170
- "aria-modal": "true",
2282
+ "aria-modal": scope === "page" ? true : void 0,
2171
2283
  tabIndex: -1,
2172
2284
  "aria-labelledby": titleId,
2173
2285
  "aria-describedby": descriptionId,
@@ -2207,22 +2319,35 @@ function Dialog({ open, onClose, title, description, children, footer, closeLabe
2207
2319
  ]
2208
2320
  })
2209
2321
  });
2322
+ return scope === "page" && portaled ? createPortal(content, document.body) : content;
2210
2323
  }
2211
2324
  //#endregion
2212
2325
  //#region src/molecules/Drawer/index.tsx
2213
- function Drawer({ open, onClose, title, description, children, footer, side = "right", size = "md", closeLabel = "Close panel", closeOnOverlayClick = true, closeOnEscape = true, initialFocus, returnFocus = true, className }) {
2326
+ function Drawer({ open, onClose, title, description, children, footer, side = "right", size = "md", closeLabel = "Close panel", closeOnOverlayClick = true, closeOnEscape = true, initialFocus, returnFocus = true, scope = "page", className }) {
2214
2327
  const id = useId();
2215
2328
  const titleId = `${id}-title`;
2216
2329
  const descriptionId = description !== void 0 ? `${id}-description` : void 0;
2217
2330
  const { present, state, ref: drawerRef } = usePresence(open);
2331
+ const backdropRef = useRef(null);
2332
+ const portaled = usePortaled();
2333
+ useIsoLayoutEffect(() => {
2334
+ if (scope === "page" && present && portaled) inheritScope(document.activeElement, backdropRef.current);
2335
+ }, [
2336
+ present,
2337
+ portaled,
2338
+ scope
2339
+ ]);
2218
2340
  const active = open && present;
2219
- const layer = useModalLayer(drawerRef, active);
2220
- useFocusTrap(drawerRef, active, initialFocus, { fallbackToContainer: true });
2341
+ const layer = useModalLayer(drawerRef, active, scope);
2342
+ useFocusTrap(drawerRef, active, initialFocus, {
2343
+ fallbackToContainer: true,
2344
+ trap: scope === "page"
2345
+ });
2221
2346
  useReturnFocus(present, {
2222
2347
  ref: drawerRef,
2223
2348
  returnFocus
2224
2349
  });
2225
- useScrollLock(present);
2350
+ useScrollLock(present && scope === "page");
2226
2351
  useEffect(() => {
2227
2352
  if (!open || !closeOnEscape) return;
2228
2353
  const handleKeyDown = (event) => {
@@ -2240,7 +2365,9 @@ function Drawer({ open, onClose, title, description, children, footer, side = "r
2240
2365
  open
2241
2366
  ]);
2242
2367
  if (!present) return null;
2243
- return /* @__PURE__ */ jsx("div", {
2368
+ const content = /* @__PURE__ */ jsx("div", {
2369
+ ref: backdropRef,
2370
+ "data-scope": scope,
2244
2371
  className: "sph-drawer__backdrop",
2245
2372
  "data-state": state,
2246
2373
  "data-side": side,
@@ -2254,7 +2381,7 @@ function Drawer({ open, onClose, title, description, children, footer, side = "r
2254
2381
  "data-side": side,
2255
2382
  "data-size": size,
2256
2383
  role: "dialog",
2257
- "aria-modal": "true",
2384
+ "aria-modal": scope === "page" ? true : void 0,
2258
2385
  tabIndex: -1,
2259
2386
  "aria-labelledby": titleId,
2260
2387
  "aria-describedby": descriptionId,
@@ -2294,6 +2421,7 @@ function Drawer({ open, onClose, title, description, children, footer, side = "r
2294
2421
  ]
2295
2422
  })
2296
2423
  });
2424
+ return scope === "page" && portaled ? createPortal(content, document.body) : content;
2297
2425
  }
2298
2426
  //#endregion
2299
2427
  //#region src/molecules/FieldMessage/index.tsx
@@ -3467,8 +3595,27 @@ function Delta({ value, format = signed, className, ...props }) {
3467
3595
  function firstEnabled(items) {
3468
3596
  return items.find((item) => !item.disabled)?.value;
3469
3597
  }
3598
+ /** The enabled tab a key press moves to, or undefined if the key does nothing. */
3599
+ function tabTarget(items, index, key, vertical) {
3600
+ const enabled = items.flatMap((item, position) => item.disabled ? [] : [position]);
3601
+ if (key === "Home") return enabled[0];
3602
+ if (key === "End") return enabled[enabled.length - 1];
3603
+ if (![
3604
+ "ArrowLeft",
3605
+ "ArrowRight",
3606
+ "ArrowUp",
3607
+ "ArrowDown"
3608
+ ].includes(key)) return void 0;
3609
+ const direction = vertical ? key === "ArrowDown" ? 1 : -1 : key === "ArrowRight" ? 1 : -1;
3610
+ for (let step = 1; step <= items.length; step += 1) {
3611
+ const next = (index + step * direction + items.length) % items.length;
3612
+ if (!items[next]?.disabled) return next;
3613
+ }
3614
+ }
3470
3615
  function Tabs({ items, value, defaultValue, onValueChange, children, ariaLabel = "Tabs", orientation = "horizontal", className }) {
3471
3616
  const generatedId = useId();
3617
+ const listRef = useRef(null);
3618
+ const [measured, setMeasured] = useState(false);
3472
3619
  const [uncontrolledValue, setUncontrolledValue] = useState(defaultValue ?? firstEnabled(items) ?? "");
3473
3620
  const activeValue = value ?? uncontrolledValue;
3474
3621
  const activeIndex = Math.max(0, items.findIndex((item) => item.value === activeValue));
@@ -3478,33 +3625,51 @@ function Tabs({ items, value, defaultValue, onValueChange, children, ariaLabel =
3478
3625
  onValueChange?.(nextValue);
3479
3626
  };
3480
3627
  const move = (event, index) => {
3481
- const direction = orientation === "vertical" ? event.key === "ArrowDown" ? 1 : -1 : event.key === "ArrowRight" ? 1 : -1;
3482
- if (![
3483
- "ArrowLeft",
3484
- "ArrowRight",
3485
- "ArrowUp",
3486
- "ArrowDown"
3487
- ].includes(event.key)) return;
3628
+ const next = tabTarget(items, index, event.key, orientation === "vertical");
3629
+ if (next === void 0) return;
3488
3630
  event.preventDefault();
3489
- for (let step = 1; step <= items.length; step += 1) {
3490
- const next = (index + step * direction + items.length) % items.length;
3491
- if (!items[next]?.disabled) {
3492
- setValue(items[next].value);
3493
- document.getElementById(`${generatedId}-${next}`)?.focus();
3494
- return;
3495
- }
3496
- }
3631
+ setValue(items[next].value);
3632
+ document.getElementById(`${generatedId}-${next}`)?.focus();
3497
3633
  };
3498
3634
  const panelId = `${generatedId}-panel`;
3635
+ useIsoLayoutEffect(() => {
3636
+ const list = listRef.current;
3637
+ if (!list) return;
3638
+ const update = () => {
3639
+ const tab = list.querySelectorAll("[role=\"tab\"]")[activeIndex];
3640
+ if (!tab) return;
3641
+ const listRect = list.getBoundingClientRect();
3642
+ const tabRect = tab.getBoundingClientRect();
3643
+ const vertical = orientation === "vertical";
3644
+ list.style.setProperty("--sph-tabs-indicator-at", `${(vertical ? tabRect.top - listRect.top : tabRect.left - listRect.left).toFixed(2)}px`);
3645
+ list.style.setProperty("--sph-tabs-indicator-size", `${(vertical ? tabRect.height : tabRect.width).toFixed(2)}px`);
3646
+ setMeasured(true);
3647
+ };
3648
+ update();
3649
+ if (typeof ResizeObserver === "undefined") {
3650
+ window.addEventListener("resize", update);
3651
+ return () => window.removeEventListener("resize", update);
3652
+ }
3653
+ const observer = new ResizeObserver(update);
3654
+ observer.observe(list);
3655
+ for (const tab of list.querySelectorAll("[role='tab']")) observer.observe(tab);
3656
+ return () => observer.disconnect();
3657
+ }, [
3658
+ activeIndex,
3659
+ items,
3660
+ orientation
3661
+ ]);
3499
3662
  return /* @__PURE__ */ jsxs("div", {
3500
3663
  className: cn("sph-tabs", className),
3501
3664
  "data-orientation": orientation,
3502
- children: [/* @__PURE__ */ jsx("div", {
3665
+ children: [/* @__PURE__ */ jsxs("div", {
3666
+ ref: listRef,
3503
3667
  className: "sph-tabs__list",
3504
3668
  role: "tablist",
3505
3669
  "aria-label": ariaLabel,
3506
3670
  "aria-orientation": orientation,
3507
- children: items.map((item, index) => {
3671
+ "data-measured": measured || void 0,
3672
+ children: [items.map((item, index) => {
3508
3673
  const selected = item.value === activeValue;
3509
3674
  return /* @__PURE__ */ jsx("button", {
3510
3675
  id: `${generatedId}-${index}`,
@@ -3520,7 +3685,10 @@ function Tabs({ items, value, defaultValue, onValueChange, children, ariaLabel =
3520
3685
  onKeyDown: (event) => move(event, index),
3521
3686
  children: node(item.label)
3522
3687
  }, item.value);
3523
- })
3688
+ }), /* @__PURE__ */ jsx("span", {
3689
+ className: "sph-tabs__indicator",
3690
+ "aria-hidden": "true"
3691
+ })]
3524
3692
  }), activeItem && (activeItem.content !== void 0 || children !== void 0) && /* @__PURE__ */ jsx("div", {
3525
3693
  id: panelId,
3526
3694
  className: "sph-tabs__panel",
@@ -3621,6 +3789,466 @@ function Timeline({ items, label = "Timeline", className, ...props }) {
3621
3789
  });
3622
3790
  }
3623
3791
  //#endregion
3792
+ //#region src/molecules/TreeView/index.tsx
3793
+ /** Rows in display order, descending only into expanded branches. */
3794
+ function visibleRows(items, expanded) {
3795
+ const rows = [];
3796
+ const walk = (nodes, level, parent) => {
3797
+ nodes.forEach((item, index) => {
3798
+ rows.push({
3799
+ item,
3800
+ level,
3801
+ parent,
3802
+ setSize: nodes.length,
3803
+ posInSet: index + 1
3804
+ });
3805
+ if (item.children?.length && expanded.has(item.value)) walk(item.children, level + 1, item.value);
3806
+ });
3807
+ };
3808
+ walk(items, 1);
3809
+ return rows;
3810
+ }
3811
+ /** What a key press asks for at the focused row, or undefined if it does nothing. */
3812
+ function treeStep(rows, index, key, expanded) {
3813
+ const row = rows[index];
3814
+ if (!row) return void 0;
3815
+ const { value } = row.item;
3816
+ const branch = (row.item.children?.length ?? 0) > 0;
3817
+ const open = expanded.has(value);
3818
+ switch (key) {
3819
+ case "ArrowDown": return {
3820
+ type: "focus",
3821
+ index: Math.min(index + 1, rows.length - 1)
3822
+ };
3823
+ case "ArrowUp": return {
3824
+ type: "focus",
3825
+ index: Math.max(index - 1, 0)
3826
+ };
3827
+ case "Home": return {
3828
+ type: "focus",
3829
+ index: 0
3830
+ };
3831
+ case "End": return {
3832
+ type: "focus",
3833
+ index: rows.length - 1
3834
+ };
3835
+ case "ArrowRight":
3836
+ if (branch && !open) return {
3837
+ type: "expand",
3838
+ value
3839
+ };
3840
+ if (branch && open) return {
3841
+ type: "focus",
3842
+ index: index + 1
3843
+ };
3844
+ return;
3845
+ case "ArrowLeft":
3846
+ if (branch && open) return {
3847
+ type: "collapse",
3848
+ value
3849
+ };
3850
+ if (row.parent !== void 0) return {
3851
+ type: "focus",
3852
+ index: rows.findIndex((entry) => entry.item.value === row.parent)
3853
+ };
3854
+ return;
3855
+ case "Enter":
3856
+ case " ": return {
3857
+ type: "select",
3858
+ value
3859
+ };
3860
+ default: return;
3861
+ }
3862
+ }
3863
+ function TreeView({ items, label, defaultExpanded = [], selected, defaultSelected, onSelect, className, ...props }) {
3864
+ const generatedId = useId();
3865
+ const [expandedValues, setExpandedValues] = useState(defaultExpanded);
3866
+ const [uncontrolled, setUncontrolled] = useState(defaultSelected);
3867
+ const [focusValue, setFocusValue] = useState();
3868
+ const selectedValue = selected ?? uncontrolled;
3869
+ const expanded = new Set(expandedValues);
3870
+ const rows = visibleRows(items, expanded);
3871
+ const tabStop = Math.max(0, rows.findIndex((row) => row.item.value === (focusValue ?? selectedValue)));
3872
+ const focusRow = (index) => {
3873
+ const row = rows[index];
3874
+ if (!row) return;
3875
+ setFocusValue(row.item.value);
3876
+ document.getElementById(`${generatedId}-${index}`)?.focus();
3877
+ };
3878
+ const setOpen = (value, open) => setExpandedValues((current) => open ? [...current.filter((entry) => entry !== value), value] : current.filter((entry) => entry !== value));
3879
+ const choose = (value) => {
3880
+ setUncontrolled(value);
3881
+ onSelect?.(value);
3882
+ };
3883
+ const handleKey = (event, index) => {
3884
+ const step = treeStep(rows, index, event.key, expanded);
3885
+ if (!step) return;
3886
+ event.preventDefault();
3887
+ if (step.type === "focus") focusRow(step.index);
3888
+ else if (step.type === "expand") setOpen(step.value, true);
3889
+ else if (step.type === "collapse") setOpen(step.value, false);
3890
+ else if (!rows[index].item.disabled) choose(step.value);
3891
+ };
3892
+ const handleClick = (row) => {
3893
+ if (row.item.disabled) return;
3894
+ if (row.item.children?.length) setOpen(row.item.value, !expanded.has(row.item.value));
3895
+ setFocusValue(row.item.value);
3896
+ choose(row.item.value);
3897
+ };
3898
+ return /* @__PURE__ */ jsx("ul", {
3899
+ ...node(props),
3900
+ role: "tree",
3901
+ "aria-label": label,
3902
+ className: cn("sph-tree", className),
3903
+ children: rows.map((row, index) => {
3904
+ const { item } = row;
3905
+ const branch = (item.children?.length ?? 0) > 0;
3906
+ const open = expanded.has(item.value);
3907
+ const isSelected = selectedValue === item.value;
3908
+ return /* @__PURE__ */ jsx("li", {
3909
+ id: `${generatedId}-${index}`,
3910
+ role: "treeitem",
3911
+ className: "sph-tree__item",
3912
+ "aria-level": row.level,
3913
+ "aria-setsize": row.setSize,
3914
+ "aria-posinset": row.posInSet,
3915
+ "aria-expanded": branch ? open : void 0,
3916
+ "aria-selected": isSelected,
3917
+ "aria-disabled": item.disabled || void 0,
3918
+ tabIndex: index === tabStop ? 0 : -1,
3919
+ "data-selected": isSelected || void 0,
3920
+ style: { "--sph-tree-level": String(row.level - 1) },
3921
+ onKeyDown: (event) => handleKey(event, index),
3922
+ onClick: () => handleClick(row),
3923
+ children: /* @__PURE__ */ jsxs("div", {
3924
+ className: "sph-tree__row",
3925
+ children: [/* @__PURE__ */ jsx("span", {
3926
+ className: "sph-tree__chevron",
3927
+ "aria-hidden": "true",
3928
+ "data-open": open || void 0,
3929
+ children: branch && /* @__PURE__ */ jsx(CaretRightIcon, {
3930
+ size: 12,
3931
+ weight: "bold"
3932
+ })
3933
+ }), /* @__PURE__ */ jsx("span", {
3934
+ className: "sph-tree__label",
3935
+ children: node(item.label)
3936
+ })]
3937
+ })
3938
+ }, item.value);
3939
+ })
3940
+ });
3941
+ }
3942
+ //#endregion
3943
+ //#region src/molecules/Carousel/index.tsx
3944
+ /** The slide a key press moves to, or undefined if the key does nothing. Slides wrap at both ends. */
3945
+ function slideAfter(current, count, key) {
3946
+ if (count === 0) return void 0;
3947
+ if (key === "ArrowRight") return (current + 1) % count;
3948
+ if (key === "ArrowLeft") return (current - 1 + count) % count;
3949
+ if (key === "Home") return 0;
3950
+ if (key === "End") return count - 1;
3951
+ }
3952
+ function Carousel({ slides, label, index, defaultIndex = 0, onIndexChange, className, ...props }) {
3953
+ const [uncontrolled, setUncontrolled] = useState(defaultIndex);
3954
+ const count = slides.length;
3955
+ const current = count === 0 ? 0 : Math.min(Math.max(index ?? uncontrolled, 0), count - 1);
3956
+ const go = (next) => {
3957
+ setUncontrolled(next);
3958
+ onIndexChange?.(next);
3959
+ };
3960
+ const handleKey = (event) => {
3961
+ if (event.target.closest?.("input, textarea, select, [contenteditable='true']")) return;
3962
+ const next = slideAfter(current, count, event.key);
3963
+ if (next === void 0) return;
3964
+ event.preventDefault();
3965
+ go(next);
3966
+ };
3967
+ return /* @__PURE__ */ jsxs("section", {
3968
+ ...node(props),
3969
+ role: "region",
3970
+ "aria-roledescription": "carousel",
3971
+ "aria-label": label,
3972
+ className: cn("sph-carousel", className),
3973
+ onKeyDown: handleKey,
3974
+ children: [/* @__PURE__ */ jsx("div", {
3975
+ className: "sph-carousel__viewport",
3976
+ children: slides.map((slide, position) => /* @__PURE__ */ jsx("div", {
3977
+ role: "group",
3978
+ "aria-roledescription": "slide",
3979
+ "aria-label": `${position + 1} of ${count}`,
3980
+ className: "sph-carousel__slide",
3981
+ hidden: position !== current,
3982
+ children: node(slide)
3983
+ }, `slide-${position}`))
3984
+ }), /* @__PURE__ */ jsxs("div", {
3985
+ className: "sph-carousel__controls",
3986
+ children: [
3987
+ /* @__PURE__ */ jsx("button", {
3988
+ type: "button",
3989
+ className: "sph-carousel__button",
3990
+ "aria-label": "Previous slide",
3991
+ disabled: count < 2,
3992
+ onClick: () => go((current - 1 + count) % count),
3993
+ children: /* @__PURE__ */ jsx("span", {
3994
+ "aria-hidden": "true",
3995
+ children: /* @__PURE__ */ jsx(CaretLeftIcon, {
3996
+ size: 14,
3997
+ weight: "bold"
3998
+ })
3999
+ })
4000
+ }),
4001
+ /* @__PURE__ */ jsx("div", {
4002
+ className: "sph-carousel__dots",
4003
+ children: slides.map((_, position) => /* @__PURE__ */ jsx("button", {
4004
+ type: "button",
4005
+ className: "sph-carousel__dot",
4006
+ "aria-label": `Show slide ${position + 1}`,
4007
+ "aria-current": position === current ? "true" : void 0,
4008
+ "data-active": position === current || void 0,
4009
+ onClick: () => go(position)
4010
+ }, `dot-${position}`))
4011
+ }),
4012
+ /* @__PURE__ */ jsx("button", {
4013
+ type: "button",
4014
+ className: "sph-carousel__button",
4015
+ "aria-label": "Next slide",
4016
+ disabled: count < 2,
4017
+ onClick: () => go((current + 1) % count),
4018
+ children: /* @__PURE__ */ jsx("span", {
4019
+ "aria-hidden": "true",
4020
+ children: /* @__PURE__ */ jsx(CaretRightIcon, {
4021
+ size: 14,
4022
+ weight: "bold"
4023
+ })
4024
+ })
4025
+ })
4026
+ ]
4027
+ })]
4028
+ });
4029
+ }
4030
+ //#endregion
4031
+ //#region src/molecules/DateRangeField/index.tsx
4032
+ const EMPTY = {
4033
+ start: null,
4034
+ end: null
4035
+ };
4036
+ const pad = (value) => String(value).padStart(2, "0");
4037
+ /** Day, month and year text for a `YYYY-MM-DD` value, or blanks. */
4038
+ function segmentsOf(day) {
4039
+ return day ? [
4040
+ day.slice(8, 10),
4041
+ day.slice(5, 7),
4042
+ day.slice(0, 4)
4043
+ ] : [
4044
+ "",
4045
+ "",
4046
+ ""
4047
+ ];
4048
+ }
4049
+ /** The `YYYY-MM-DD` value when all three segments form a real date. */
4050
+ function dayFromSegments(parts) {
4051
+ const [dd, mm, yyyy] = parts;
4052
+ if (!/^\d{2}$/.test(dd) || !/^\d{2}$/.test(mm) || !/^\d{4}$/.test(yyyy)) return null;
4053
+ const month = Number(mm);
4054
+ const day = Number(dd);
4055
+ if (month < 1 || month > 12 || day < 1) return null;
4056
+ if (day > daysInMonth(`${yyyy}-${mm}`)) return null;
4057
+ return `${yyyy}-${mm}-${dd}`;
4058
+ }
4059
+ /**
4060
+ * Types one digit into a segment. A segment advances once it is full, or
4061
+ * when a lone first digit cannot start a longer value (4 to 9 for days,
4062
+ * 2 to 9 for months).
4063
+ */
4064
+ function typeSegment(parts, part, digit) {
4065
+ const size = part === 2 ? 4 : 2;
4066
+ const current = parts[part];
4067
+ let next = current.length >= size ? digit : `${current}${digit}`;
4068
+ let advance = next.length === size;
4069
+ const maxLeading = part === 0 ? 3 : 1;
4070
+ if (part < 2 && next.length === 1 && Number(next) > maxLeading) {
4071
+ next = `0${next}`;
4072
+ advance = true;
4073
+ }
4074
+ return {
4075
+ parts: parts.map((value, index) => index === part ? next : value),
4076
+ advance
4077
+ };
4078
+ }
4079
+ const wrap = (value, low, high) => low + ((value - low) % (high - low + 1) + (high - low + 1)) % (high - low + 1);
4080
+ /**
4081
+ * Steps one segment up or down. Days and months wrap, years move by one, and
4082
+ * the day is clamped to the length of the resulting month. Blank parts start
4083
+ * from the first day, January, or this year.
4084
+ */
4085
+ function stepSegment(parts, part, delta, today = /* @__PURE__ */ new Date()) {
4086
+ let day = parts[0].length === 2 ? Number(parts[0]) : 1;
4087
+ let month = parts[1].length === 2 ? Number(parts[1]) : 1;
4088
+ let year = parts[2].length === 4 ? Number(parts[2]) : today.getFullYear();
4089
+ if (part === 0) day = wrap(day + delta, 1, daysInMonth(`${year}-${pad(month)}`));
4090
+ if (part === 1) month = wrap(month + delta, 1, 12);
4091
+ if (part === 2) year = Math.min(9999, Math.max(1e3, year + delta));
4092
+ day = Math.min(day, daysInMonth(`${year}-${pad(month)}`));
4093
+ return [
4094
+ pad(day),
4095
+ pad(month),
4096
+ String(year)
4097
+ ];
4098
+ }
4099
+ /** Keeps the earlier date first, the way Calendar orders a picked range. */
4100
+ function orderRange(range) {
4101
+ const { start, end } = range;
4102
+ if (start && end && end < start) return {
4103
+ start: end,
4104
+ end: start
4105
+ };
4106
+ return range;
4107
+ }
4108
+ const SEGMENT_NAMES = [
4109
+ "day",
4110
+ "month",
4111
+ "year"
4112
+ ];
4113
+ const PLACEHOLDERS = [
4114
+ "DD",
4115
+ "MM",
4116
+ "YYYY"
4117
+ ];
4118
+ const ENDPOINT_NAMES = {
4119
+ start: "Start",
4120
+ end: "End"
4121
+ };
4122
+ function DateRangeField({ range, defaultRange, onRangeChange, min, max, label, layout = "split", className, ...props }) {
4123
+ const rootRef = useRef(null);
4124
+ const [uncontrolled, setUncontrolled] = useState(defaultRange ?? EMPTY);
4125
+ const [drafts, setDrafts] = useState({});
4126
+ const current = range ?? uncontrolled;
4127
+ const publish = (next) => {
4128
+ const ordered = orderRange(next);
4129
+ setUncontrolled(ordered);
4130
+ onRangeChange?.(ordered);
4131
+ };
4132
+ const focusSegment = (endpoint, part) => {
4133
+ rootRef.current?.querySelector(`[data-segment="${endpoint}-${part}"]`)?.focus();
4134
+ };
4135
+ const edit = (endpoint, parts) => {
4136
+ const day = dayFromSegments(parts);
4137
+ if (day) {
4138
+ setDrafts((all) => ({
4139
+ ...all,
4140
+ [endpoint]: void 0
4141
+ }));
4142
+ publish({
4143
+ ...current,
4144
+ [endpoint]: day
4145
+ });
4146
+ } else setDrafts((all) => ({
4147
+ ...all,
4148
+ [endpoint]: parts
4149
+ }));
4150
+ };
4151
+ const handleKey = (endpoint, part, event) => {
4152
+ const parts = drafts[endpoint] ?? segmentsOf(current[endpoint]);
4153
+ if (/^\d$/.test(event.key)) {
4154
+ event.preventDefault();
4155
+ const typed = typeSegment(parts, part, event.key);
4156
+ edit(endpoint, typed.parts);
4157
+ if (typed.advance) {
4158
+ if (part < 2) focusSegment(endpoint, part + 1);
4159
+ else if (endpoint === "start") focusSegment("end", 0);
4160
+ }
4161
+ return;
4162
+ }
4163
+ if (event.key === "ArrowUp" || event.key === "ArrowDown") {
4164
+ event.preventDefault();
4165
+ edit(endpoint, stepSegment(parts, part, event.key === "ArrowUp" ? 1 : -1));
4166
+ return;
4167
+ }
4168
+ if (event.key === "ArrowLeft" || event.key === "ArrowRight") {
4169
+ event.preventDefault();
4170
+ const next = event.key === "ArrowLeft" ? part - 1 : part + 1;
4171
+ if (next >= 0 && next <= 2) focusSegment(endpoint, next);
4172
+ return;
4173
+ }
4174
+ if (event.key === "Backspace") {
4175
+ event.preventDefault();
4176
+ edit(endpoint, parts.map((value, index) => index === part ? "" : value));
4177
+ }
4178
+ };
4179
+ const endpointField = (endpoint) => /* @__PURE__ */ jsxs("div", {
4180
+ role: "group",
4181
+ "aria-label": `${ENDPOINT_NAMES[endpoint]} date`,
4182
+ className: "sph-date-range__date",
4183
+ children: [/* @__PURE__ */ jsx("span", {
4184
+ className: "sph-date-range__endpoint",
4185
+ "aria-hidden": "true",
4186
+ children: ENDPOINT_NAMES[endpoint]
4187
+ }), (drafts[endpoint] ?? segmentsOf(current[endpoint])).map((value, part) => /* @__PURE__ */ jsxs("span", {
4188
+ className: "sph-date-range__segment-wrap",
4189
+ children: [part > 0 && /* @__PURE__ */ jsx("span", {
4190
+ className: "sph-date-range__sep",
4191
+ "aria-hidden": "true",
4192
+ children: "/"
4193
+ }), /* @__PURE__ */ jsx("input", {
4194
+ type: "text",
4195
+ inputMode: "numeric",
4196
+ autoComplete: "off",
4197
+ className: "sph-date-range__segment",
4198
+ "data-segment": `${endpoint}-${part}`,
4199
+ "data-part": part,
4200
+ "aria-label": `${ENDPOINT_NAMES[endpoint]} ${SEGMENT_NAMES[part]}`,
4201
+ placeholder: PLACEHOLDERS[part],
4202
+ value,
4203
+ readOnly: true,
4204
+ onKeyDown: (event) => handleKey(endpoint, part, event)
4205
+ })]
4206
+ }, part))]
4207
+ });
4208
+ return /* @__PURE__ */ jsxs("div", {
4209
+ ...node(props),
4210
+ ref: rootRef,
4211
+ role: "group",
4212
+ "aria-label": label,
4213
+ "data-layout": layout,
4214
+ className: cn("sph-date-range", className),
4215
+ children: [
4216
+ endpointField("start"),
4217
+ /* @__PURE__ */ jsx("span", {
4218
+ className: "sph-date-range__dash",
4219
+ "aria-hidden": "true",
4220
+ children: "–"
4221
+ }),
4222
+ endpointField("end"),
4223
+ /* @__PURE__ */ jsx(Popover, {
4224
+ ariaLabel: "Choose dates",
4225
+ placement: "end",
4226
+ trigger: /* @__PURE__ */ jsx("button", {
4227
+ type: "button",
4228
+ className: "sph-date-range__trigger",
4229
+ "aria-label": "Open calendar",
4230
+ children: /* @__PURE__ */ jsx(CalendarBlankIcon, {
4231
+ size: 16,
4232
+ "aria-hidden": "true"
4233
+ })
4234
+ }),
4235
+ children: /* @__PURE__ */ jsx(Calendar, {
4236
+ mode: "range",
4237
+ months: 2,
4238
+ range: current,
4239
+ min,
4240
+ max,
4241
+ ariaLabel: label,
4242
+ onRangeChange: (next) => {
4243
+ setDrafts({});
4244
+ publish(next);
4245
+ }
4246
+ })
4247
+ })
4248
+ ]
4249
+ });
4250
+ }
4251
+ //#endregion
3624
4252
  //#region src/molecules/Toast/index.tsx
3625
4253
  const toastIcons = {
3626
4254
  success: /* @__PURE__ */ jsx("span", {
@@ -4053,188 +4681,211 @@ function Chart({ categories, series, variant = "line", height = 160, smooth = fa
4053
4681
  ...node(props),
4054
4682
  className: cn("sph-chart", className),
4055
4683
  "data-variant": variant,
4056
- children: [showLegend && /* @__PURE__ */ jsx("figcaption", {
4057
- className: "sph-chart__legend",
4058
- "aria-label": "Series",
4059
- children: series.map((entry, index) => {
4060
- const isHidden = hidden.has(index);
4061
- return /* @__PURE__ */ jsxs("button", {
4062
- type: "button",
4063
- className: "sph-chart__legend-item",
4064
- "aria-pressed": !isHidden,
4065
- "data-hidden": isHidden || void 0,
4066
- onClick: () => toggle(index),
4067
- children: [/* @__PURE__ */ jsx("span", {
4068
- className: "sph-chart__legend-dot",
4069
- style: { background: TONE_VAR[resolved[index].tone] },
4070
- "aria-hidden": "true"
4071
- }), entry.name]
4072
- }, `legend-${entry.name}-${index}`);
4073
- })
4074
- }), /* @__PURE__ */ jsxs("div", {
4075
- className: "sph-chart__plot",
4076
- role: "img",
4077
- "aria-label": summary,
4078
- style: { gridTemplateRows: `${height}px auto` },
4079
- children: [
4080
- /* @__PURE__ */ jsx("div", {
4081
- className: "sph-chart__yaxis",
4082
- style: {
4083
- width: `calc(${longestTick}ch + 8px)`,
4084
- fontSize: "10px"
4085
- },
4086
- children: tickList.map((tick) => /* @__PURE__ */ jsx("span", {
4087
- style: { bottom: `${scale(tick)}%` },
4088
- children: format(tick)
4089
- }, `y-${tick}`))
4090
- }),
4091
- /* @__PURE__ */ jsxs("div", {
4092
- className: "sph-chart__area",
4093
- style: {
4094
- "--sph-chart-anchor": anchorName,
4095
- "--sph-chart-x": `${pointerX}%`,
4096
- "--sph-chart-y": `${anchorTop}%`
4097
- },
4098
- onPointerMove: (event) => {
4099
- const rect = event.currentTarget.getBoundingClientRect();
4100
- const ratio = rect.width > 0 ? (event.clientX - rect.left) / rect.width : 0;
4101
- setHover(Math.min(count - 1, Math.max(0, Math.floor(ratio * count))));
4102
- },
4103
- onPointerLeave: () => setHover(null),
4104
- children: [
4105
- /* @__PURE__ */ jsx("div", {
4106
- className: "sph-chart__grid",
4107
- "aria-hidden": "true",
4108
- children: tickList.map((tick) => /* @__PURE__ */ jsx("i", { style: { bottom: `${scale(tick)}%` } }, `g-${tick}`))
4109
- }),
4110
- variant === "bar" ? /* @__PURE__ */ jsx("div", {
4111
- className: "sph-chart__bands",
4112
- children: categories.map((_, band) => /* @__PURE__ */ jsx("div", {
4113
- className: "sph-chart__band",
4114
- style: { width: `${bandPct}%` },
4115
- children: shown.map((entry, position) => {
4116
- const value = entry.values[band];
4117
- if (value == null) return null;
4118
- const rect = barRect(0, position, 1, shown.length);
4119
- return /* @__PURE__ */ jsx("div", {
4120
- className: "sph-chart__bar",
4121
- style: {
4122
- left: `${rect.left}%`,
4123
- width: `${rect.width}%`,
4124
- height: `${scale(value)}%`,
4125
- background: TONE_VAR[entry.tone]
4126
- }
4127
- }, `bar-${entry.name}-${entry.tone}`);
4128
- })
4129
- }, `band-${band}`))
4130
- }) : /* @__PURE__ */ jsx("div", {
4131
- className: "sph-chart__series-layer",
4132
- children: /* @__PURE__ */ jsxs("svg", {
4133
- viewBox: "0 0 100 100",
4134
- preserveAspectRatio: "none",
4135
- children: [
4136
- variant === "area" && /* @__PURE__ */ jsx("defs", { children: shown.map((entry) => /* @__PURE__ */ jsxs("linearGradient", {
4137
- id: `${gradientId}-s${entry.index}`,
4138
- x1: "0",
4139
- y1: "0",
4140
- x2: "0",
4141
- y2: "1",
4142
- children: [/* @__PURE__ */ jsx("stop", {
4143
- offset: "0%",
4144
- style: {
4145
- stopColor: TONE_VAR[entry.tone],
4146
- stopOpacity: .32
4147
- }
4148
- }), /* @__PURE__ */ jsx("stop", {
4149
- offset: "100%",
4150
- style: {
4151
- stopColor: TONE_VAR[entry.tone],
4152
- stopOpacity: 0
4153
- }
4154
- })]
4155
- }, `grad-${entry.index}`)) }),
4156
- variant === "area" && shown.map((entry) => pointsFor(entry).map((points, segmentIndex) => /* @__PURE__ */ jsx("path", {
4157
- d: areaPath(points, 100, smooth),
4158
- fill: `url(#${gradientId}-s${entry.index})`
4159
- }, `fill-${entry.index}-${segmentIndex}`))),
4160
- shown.map((entry) => pointsFor(entry).map((points, segmentIndex) => /* @__PURE__ */ jsx("path", {
4161
- className: "sph-chart__line",
4162
- d: linePath(points, smooth),
4163
- fill: "none",
4164
- stroke: TONE_VAR[entry.tone],
4165
- strokeWidth: 1.75,
4166
- strokeLinecap: "round",
4167
- strokeLinejoin: "round",
4168
- vectorEffect: "non-scaling-stroke"
4169
- }, `line-${entry.index}-${segmentIndex}`)))
4170
- ]
4171
- })
4172
- }),
4173
- /* @__PURE__ */ jsx("span", {
4174
- className: "sph-chart__anchor",
4684
+ children: [
4685
+ showLegend && /* @__PURE__ */ jsx("figcaption", {
4686
+ className: "sph-chart__legend",
4687
+ "aria-label": "Series",
4688
+ children: series.map((entry, index) => {
4689
+ const isHidden = hidden.has(index);
4690
+ return /* @__PURE__ */ jsxs("button", {
4691
+ type: "button",
4692
+ className: "sph-chart__legend-item",
4693
+ "aria-pressed": !isHidden,
4694
+ "data-hidden": isHidden || void 0,
4695
+ onClick: () => toggle(index),
4696
+ children: [/* @__PURE__ */ jsx("span", {
4697
+ className: "sph-chart__legend-dot",
4698
+ style: { background: TONE_VAR[resolved[index].tone] },
4175
4699
  "aria-hidden": "true"
4176
- }),
4177
- hover !== null && /* @__PURE__ */ jsxs(Fragment$1, { children: [
4700
+ }), entry.name]
4701
+ }, `legend-${entry.name}-${index}`);
4702
+ })
4703
+ }),
4704
+ /* @__PURE__ */ jsxs("div", {
4705
+ className: "sph-chart__plot",
4706
+ role: "img",
4707
+ "aria-label": summary,
4708
+ style: { gridTemplateRows: `${height}px auto` },
4709
+ children: [
4710
+ /* @__PURE__ */ jsx("div", {
4711
+ className: "sph-chart__yaxis",
4712
+ style: {
4713
+ width: `calc(${longestTick}ch + 8px)`,
4714
+ fontSize: "10px"
4715
+ },
4716
+ children: tickList.map((tick) => /* @__PURE__ */ jsx("span", {
4717
+ style: { bottom: `${scale(tick)}%` },
4718
+ children: format(tick)
4719
+ }, `y-${tick}`))
4720
+ }),
4721
+ /* @__PURE__ */ jsxs("div", {
4722
+ className: "sph-chart__area",
4723
+ style: {
4724
+ "--sph-chart-anchor": anchorName,
4725
+ "--sph-chart-x": `${pointerX}%`,
4726
+ "--sph-chart-y": `${anchorTop}%`
4727
+ },
4728
+ onPointerMove: (event) => {
4729
+ const rect = event.currentTarget.getBoundingClientRect();
4730
+ const ratio = rect.width > 0 ? (event.clientX - rect.left) / rect.width : 0;
4731
+ setHover(Math.min(count - 1, Math.max(0, Math.floor(ratio * count))));
4732
+ },
4733
+ onPointerLeave: () => setHover(null),
4734
+ children: [
4735
+ /* @__PURE__ */ jsx("div", {
4736
+ className: "sph-chart__grid",
4737
+ "aria-hidden": "true",
4738
+ children: tickList.map((tick) => /* @__PURE__ */ jsx("i", { style: { bottom: `${scale(tick)}%` } }, `g-${tick}`))
4739
+ }),
4178
4740
  variant === "bar" ? /* @__PURE__ */ jsx("div", {
4179
- className: "sph-chart__band-tint",
4180
- style: {
4181
- left: `${hover * bandPct}%`,
4182
- width: `${bandPct}%`
4183
- },
4184
- "aria-hidden": "true"
4185
- }, `tint-${hover}`) : /* @__PURE__ */ jsx("div", {
4186
- className: "sph-chart__guide",
4187
- style: { left: `${xPct(hover)}%` },
4741
+ className: "sph-chart__bands",
4742
+ children: categories.map((_, band) => /* @__PURE__ */ jsx("div", {
4743
+ className: "sph-chart__band",
4744
+ style: { width: `${bandPct}%` },
4745
+ children: shown.map((entry, position) => {
4746
+ const value = entry.values[band];
4747
+ if (value == null) return null;
4748
+ const rect = barRect(0, position, 1, shown.length);
4749
+ return /* @__PURE__ */ jsx("div", {
4750
+ className: "sph-chart__bar",
4751
+ style: {
4752
+ left: `${rect.left}%`,
4753
+ width: `${rect.width}%`,
4754
+ height: `${scale(value)}%`,
4755
+ background: TONE_VAR[entry.tone]
4756
+ }
4757
+ }, `bar-${entry.name}-${entry.tone}`);
4758
+ })
4759
+ }, `band-${band}`))
4760
+ }) : /* @__PURE__ */ jsx("div", {
4761
+ className: "sph-chart__series-layer",
4762
+ children: /* @__PURE__ */ jsxs("svg", {
4763
+ viewBox: "0 0 100 100",
4764
+ preserveAspectRatio: "none",
4765
+ children: [
4766
+ variant === "area" && /* @__PURE__ */ jsx("defs", { children: shown.map((entry) => /* @__PURE__ */ jsxs("linearGradient", {
4767
+ id: `${gradientId}-s${entry.index}`,
4768
+ x1: "0",
4769
+ y1: "0",
4770
+ x2: "0",
4771
+ y2: "1",
4772
+ children: [/* @__PURE__ */ jsx("stop", {
4773
+ offset: "0%",
4774
+ style: {
4775
+ stopColor: TONE_VAR[entry.tone],
4776
+ stopOpacity: .32
4777
+ }
4778
+ }), /* @__PURE__ */ jsx("stop", {
4779
+ offset: "100%",
4780
+ style: {
4781
+ stopColor: TONE_VAR[entry.tone],
4782
+ stopOpacity: 0
4783
+ }
4784
+ })]
4785
+ }, `grad-${entry.index}`)) }),
4786
+ variant === "area" && shown.map((entry) => pointsFor(entry).map((points, segmentIndex) => /* @__PURE__ */ jsx("path", {
4787
+ d: areaPath(points, 100, smooth),
4788
+ fill: `url(#${gradientId}-s${entry.index})`
4789
+ }, `fill-${entry.index}-${segmentIndex}`))),
4790
+ shown.map((entry) => pointsFor(entry).map((points, segmentIndex) => /* @__PURE__ */ jsx("path", {
4791
+ className: "sph-chart__line",
4792
+ d: linePath(points, smooth),
4793
+ fill: "none",
4794
+ stroke: TONE_VAR[entry.tone],
4795
+ strokeWidth: 1.75,
4796
+ strokeLinecap: "round",
4797
+ strokeLinejoin: "round",
4798
+ vectorEffect: "non-scaling-stroke"
4799
+ }, `line-${entry.index}-${segmentIndex}`)))
4800
+ ]
4801
+ })
4802
+ }),
4803
+ /* @__PURE__ */ jsx("span", {
4804
+ className: "sph-chart__anchor",
4188
4805
  "aria-hidden": "true"
4189
- }, `guide-${hover}`),
4190
- variant !== "bar" && shown.map((entry) => {
4191
- const value = entry.values[hover];
4192
- if (value == null) return null;
4193
- return /* @__PURE__ */ jsx("span", {
4194
- className: "sph-chart__dot",
4806
+ }),
4807
+ hover !== null && /* @__PURE__ */ jsxs(Fragment$1, { children: [
4808
+ variant === "bar" ? /* @__PURE__ */ jsx("div", {
4809
+ className: "sph-chart__band-tint",
4195
4810
  style: {
4196
- left: `${xPct(hover)}%`,
4197
- top: `${topPct(value)}%`,
4198
- background: TONE_VAR[entry.tone]
4811
+ left: `${hover * bandPct}%`,
4812
+ width: `${bandPct}%`
4199
4813
  },
4200
4814
  "aria-hidden": "true"
4201
- }, `dot-${hover}-${entry.name}-${entry.tone}`);
4202
- }),
4203
- anchor !== void 0 && /* @__PURE__ */ jsx("div", {
4204
- className: "sph-chart__tooltip",
4205
- children: /* @__PURE__ */ jsxs("div", {
4206
- className: "sph-chart__tooltip-card",
4207
- children: [/* @__PURE__ */ jsx("span", {
4208
- className: "sph-chart__tooltip-label",
4209
- children: categories[hover]
4210
- }), shown.map((entry) => {
4211
- const value = entry.values[hover];
4212
- return /* @__PURE__ */ jsxs("span", {
4213
- className: "sph-chart__tooltip-row",
4214
- children: [
4215
- /* @__PURE__ */ jsx("i", {
4216
- style: { background: TONE_VAR[entry.tone] },
4217
- "aria-hidden": "true"
4218
- }),
4219
- /* @__PURE__ */ jsx("span", { children: entry.name }),
4220
- /* @__PURE__ */ jsx("b", { children: value == null ? "–" : format(value) })
4221
- ]
4222
- }, `tip-row-${entry.name}-${entry.tone}`);
4223
- })]
4224
- })
4225
- }, `tip-${hover}`)
4226
- ] })
4227
- ]
4228
- }),
4229
- /* @__PURE__ */ jsx("div", {
4230
- className: "sph-chart__xaxis",
4231
- children: categories.map((category, index) => /* @__PURE__ */ jsx("span", {
4232
- style: { flex: `0 0 ${bandPct}%` },
4815
+ }, `tint-${hover}`) : /* @__PURE__ */ jsx("div", {
4816
+ className: "sph-chart__guide",
4817
+ style: { left: `${xPct(hover)}%` },
4818
+ "aria-hidden": "true"
4819
+ }, `guide-${hover}`),
4820
+ variant !== "bar" && shown.map((entry) => {
4821
+ const value = entry.values[hover];
4822
+ if (value == null) return null;
4823
+ return /* @__PURE__ */ jsx("span", {
4824
+ className: "sph-chart__dot",
4825
+ style: {
4826
+ left: `${xPct(hover)}%`,
4827
+ top: `${topPct(value)}%`,
4828
+ background: TONE_VAR[entry.tone]
4829
+ },
4830
+ "aria-hidden": "true"
4831
+ }, `dot-${hover}-${entry.name}-${entry.tone}`);
4832
+ }),
4833
+ anchor !== void 0 && /* @__PURE__ */ jsx("div", {
4834
+ className: "sph-chart__tooltip",
4835
+ children: /* @__PURE__ */ jsxs("div", {
4836
+ className: "sph-chart__tooltip-card",
4837
+ children: [/* @__PURE__ */ jsx("span", {
4838
+ className: "sph-chart__tooltip-label",
4839
+ children: categories[hover]
4840
+ }), shown.map((entry) => {
4841
+ const value = entry.values[hover];
4842
+ return /* @__PURE__ */ jsxs("span", {
4843
+ className: "sph-chart__tooltip-row",
4844
+ children: [
4845
+ /* @__PURE__ */ jsx("i", {
4846
+ style: { background: TONE_VAR[entry.tone] },
4847
+ "aria-hidden": "true"
4848
+ }),
4849
+ /* @__PURE__ */ jsx("span", { children: entry.name }),
4850
+ /* @__PURE__ */ jsx("b", { children: value == null ? "–" : format(value) })
4851
+ ]
4852
+ }, `tip-row-${entry.name}-${entry.tone}`);
4853
+ })]
4854
+ })
4855
+ }, `tip-${hover}`)
4856
+ ] })
4857
+ ]
4858
+ }),
4859
+ /* @__PURE__ */ jsx("div", {
4860
+ className: "sph-chart__xaxis",
4861
+ children: categories.map((category, index) => /* @__PURE__ */ jsx("span", {
4862
+ style: { flex: `0 0 ${bandPct}%` },
4863
+ children: category
4864
+ }, `x-${category}-${index}`))
4865
+ })
4866
+ ]
4867
+ }),
4868
+ /* @__PURE__ */ jsxs("table", {
4869
+ className: "sph-visually-hidden",
4870
+ children: [
4871
+ /* @__PURE__ */ jsx("caption", { children: summary }),
4872
+ /* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsxs("tr", { children: [/* @__PURE__ */ jsx("th", {
4873
+ scope: "col",
4874
+ children: "Category"
4875
+ }), resolved.map((entry) => /* @__PURE__ */ jsx("th", {
4876
+ scope: "col",
4877
+ children: entry.name
4878
+ }, `head-${entry.index}`))] }) }),
4879
+ /* @__PURE__ */ jsx("tbody", { children: categories.map((category, row) => /* @__PURE__ */ jsxs("tr", { children: [/* @__PURE__ */ jsx("th", {
4880
+ scope: "row",
4233
4881
  children: category
4234
- }, `x-${category}-${index}`))
4235
- })
4236
- ]
4237
- })]
4882
+ }), resolved.map((entry) => {
4883
+ const value = entry.values[row];
4884
+ return /* @__PURE__ */ jsx("td", { children: value == null ? "–" : format(value) }, `cell-${entry.index}-${row}`);
4885
+ })] }, `row-${row}`)) })
4886
+ ]
4887
+ })
4888
+ ]
4238
4889
  });
4239
4890
  }
4240
4891
  //#endregion
@@ -4419,7 +5070,13 @@ function CommandPalette({ open, onOpenChange, items, onSelect, placeholder = "Ty
4419
5070
  ]);
4420
5071
  useEffect(() => {
4421
5072
  if (!visible || active < 0) return;
4422
- (trackRef.current?.querySelector("[data-active=\"true\"]"))?.scrollIntoView({ block: "nearest" });
5073
+ const option = trackRef.current?.querySelector("[data-active=\"true\"]");
5074
+ const list = innerRef.current;
5075
+ if (!option || !list) return;
5076
+ const top = option.offsetTop;
5077
+ const bottom = top + option.offsetHeight;
5078
+ if (top < list.scrollTop) list.scrollTop = top;
5079
+ else if (bottom > list.scrollTop + list.clientHeight) list.scrollTop = bottom - list.clientHeight;
4423
5080
  }, [active, visible]);
4424
5081
  useIsoLayoutEffect(() => {
4425
5082
  const indicator = indicatorRef.current;
@@ -4427,14 +5084,12 @@ function CommandPalette({ open, onOpenChange, items, onSelect, placeholder = "Ty
4427
5084
  if (!visible || !indicator || !track || active < 0) return;
4428
5085
  const option = track.querySelector(`[data-index="${active}"]`);
4429
5086
  if (!option) return;
4430
- const trackRect = track.getBoundingClientRect();
4431
- const optionRect = option.getBoundingClientRect();
4432
5087
  const first = !indicator.style.width;
4433
5088
  if (first) indicator.style.transition = "none";
4434
5089
  indicator.style.opacity = "1";
4435
- indicator.style.width = `${optionRect.width}px`;
4436
- indicator.style.height = `${optionRect.height}px`;
4437
- indicator.style.transform = `translate(${optionRect.left - trackRect.left}px, ${optionRect.top - trackRect.top}px)`;
5090
+ indicator.style.width = `${option.offsetWidth}px`;
5091
+ indicator.style.height = `${option.offsetHeight}px`;
5092
+ indicator.style.transform = `translate(${option.offsetLeft}px, ${option.offsetTop}px)`;
4438
5093
  if (first) requestAnimationFrame(() => {
4439
5094
  indicator.style.transition = "";
4440
5095
  });
@@ -4456,12 +5111,12 @@ function CommandPalette({ open, onOpenChange, items, onSelect, placeholder = "Ty
4456
5111
  body.style.height = "";
4457
5112
  return;
4458
5113
  }
4459
- const current = body.style.height ? Number.parseFloat(body.style.height) : body.getBoundingClientRect().height;
5114
+ const current = body.style.height ? Number.parseFloat(body.style.height) : body.offsetHeight;
4460
5115
  if (!body.style.height) {
4461
5116
  body.style.height = `${current}px`;
4462
5117
  return;
4463
5118
  }
4464
- const target = inner.getBoundingClientRect().height;
5119
+ const target = inner.offsetHeight;
4465
5120
  if (Math.abs(current - target) < 1) {
4466
5121
  body.style.height = `${target}px`;
4467
5122
  return;
@@ -6464,7 +7119,20 @@ function fitOverflowCount({ widths, available, gap, reserve, minVisible = 0 }) {
6464
7119
  return visible >= total ? total : visible;
6465
7120
  }
6466
7121
  const defaultLabel = (count) => `${count} more`;
6467
- function OverflowPanel({ hidden, offset, render, getKey, onEscape }) {
7122
+ const defaultRemoveLabel = (item) => `Remove ${String(item)}`;
7123
+ function OverflowRemove({ label, onClick }) {
7124
+ return /* @__PURE__ */ jsx("button", {
7125
+ type: "button",
7126
+ className: "sph-overflow-list__remove",
7127
+ "aria-label": label,
7128
+ onClick,
7129
+ children: /* @__PURE__ */ jsx(XIcon, {
7130
+ size: 13,
7131
+ "aria-hidden": "true"
7132
+ })
7133
+ });
7134
+ }
7135
+ function OverflowPanel({ hidden, offset, render, getKey, remove, onEscape }) {
6468
7136
  const panelRef = useRef(null);
6469
7137
  useFocusTrap(panelRef, true);
6470
7138
  useEffect(() => {
@@ -6482,13 +7150,13 @@ function OverflowPanel({ hidden, offset, render, getKey, onEscape }) {
6482
7150
  className: "sph-overflow-list__panel",
6483
7151
  tabIndex: -1,
6484
7152
  onKeyDown: handleKeyDown,
6485
- children: hidden.map((item, position) => /* @__PURE__ */ jsx("li", {
7153
+ children: hidden.map((item, position) => /* @__PURE__ */ jsxs("li", {
6486
7154
  className: "sph-overflow-list__panel-item",
6487
- children: node(render(item, offset + position))
7155
+ children: [node(render(item, offset + position)), remove ? node(remove(item, offset + position)) : null]
6488
7156
  }, getKey(item, offset + position)))
6489
7157
  });
6490
7158
  }
6491
- function OverflowList({ items, renderItem, renderOverflow, renderOverflowItem, getKey = (_item, index) => index, minVisible = 0, collapseFrom = "end", overflowLabel = defaultLabel, className, ...props }) {
7159
+ function OverflowList({ items, renderItem, renderOverflow, renderOverflowItem, getKey = (_item, index) => index, minVisible = 0, collapseFrom = "end", overflowLabel = defaultLabel, onRemove, removeLabel = defaultRemoveLabel, className, ...props }) {
6492
7160
  const rootRef = useRef(null);
6493
7161
  const measureRef = useRef(null);
6494
7162
  const trackRef = useRef(null);
@@ -6575,6 +7243,10 @@ function OverflowList({ items, renderItem, renderOverflow, renderOverflowItem, g
6575
7243
  const focusTrigger = () => {
6576
7244
  chipRef.current?.closest("button")?.focus();
6577
7245
  };
7246
+ const removable = onRemove ? (item, index) => /* @__PURE__ */ jsx(OverflowRemove, {
7247
+ label: removeLabel(item, index),
7248
+ onClick: () => onRemove(item, index)
7249
+ }) : void 0;
6578
7250
  const chipContent = (count, ref) => /* @__PURE__ */ jsxs("span", {
6579
7251
  ref,
6580
7252
  className: "sph-overflow-list__chip",
@@ -6601,6 +7273,7 @@ function OverflowList({ items, renderItem, renderOverflow, renderOverflowItem, g
6601
7273
  offset,
6602
7274
  render: renderOverflowItem ?? renderItem,
6603
7275
  getKey,
7276
+ remove: removable,
6604
7277
  onEscape: focusTrigger
6605
7278
  })
6606
7279
  })
@@ -6613,9 +7286,9 @@ function OverflowList({ items, renderItem, renderOverflow, renderOverflowItem, g
6613
7286
  "data-overflowing": hiddenCount > 0 || void 0,
6614
7287
  children: [
6615
7288
  collapseFrom === "start" && more,
6616
- items.slice(start, start + shown).map((item, position) => /* @__PURE__ */ jsx("li", {
7289
+ items.slice(start, start + shown).map((item, position) => /* @__PURE__ */ jsxs("li", {
6617
7290
  className: "sph-overflow-list__item",
6618
- children: node(renderItem(item, start + position))
7291
+ children: [node(renderItem(item, start + position)), removable ? node(removable(item, start + position)) : null]
6619
7292
  }, getKey(item, start + position))),
6620
7293
  collapseFrom === "end" && more,
6621
7294
  ready && /* @__PURE__ */ jsx("li", {
@@ -6625,9 +7298,9 @@ function OverflowList({ items, renderItem, renderOverflow, renderOverflowItem, g
6625
7298
  children: /* @__PURE__ */ jsxs("div", {
6626
7299
  ref: trackRef,
6627
7300
  className: "sph-overflow-list__track",
6628
- children: [items.map((item, index) => /* @__PURE__ */ jsx("div", {
7301
+ children: [items.map((item, index) => /* @__PURE__ */ jsxs("div", {
6629
7302
  className: "sph-overflow-list__item",
6630
- children: node(renderItem(item, index))
7303
+ children: [node(renderItem(item, index)), removable ? node(removable(item, index)) : null]
6631
7304
  }, getKey(item, index))), /* @__PURE__ */ jsx("div", {
6632
7305
  className: "sph-overflow-list__item",
6633
7306
  children: renderOverflow ? node(renderOverflow(items)) : chipContent(total)
@@ -7508,6 +8181,791 @@ function ChatScroller({ children, itemCount, newCount, threshold = 48, ariaLabel
7508
8181
  });
7509
8182
  }
7510
8183
  //#endregion
7511
- export { Accordion, Alert, AnimatedNumber, Attachment, Avatar, AvatarGroup, Badge, Breadcrumb, Button, Calendar, Card, Chart, ChatScroller, Checkbox, Citation, Collapsible, Combobox, CommandPalette, ContextMenu, Delta, Dialog, Drawer, EmptyState, Field, FieldMessage, HoldButton, HoverCard, IconButton, Input, Kbd, MagneticDropzone, Menu, Menubar, MetadataList, Notice, NumberInput, OTPInput, OverflowList, Pagination, PlanCard, Popover, Progress, QuestionCard, RadioGroup, ReasoningSteps, Resizable, Reveal, ScrollArea, SegmentedControl, Select, Separator, SidePanel, Sidebar, Skeleton, Slider, Spinner, Stat, StatGroup, StatusMark, Stepper, StreamingText, Surface, Table, Tabs, TaskList, Textarea, Timeline, Timestamp, Toast, ToastViewport, Toggle, ToolCalls, Toolbar, Tooltip, TooltipGroup, describeDropzoneResult, motionDurationMs, parseDurationMs, toast, usePresence, validateDropzoneFiles };
8184
+ //#region src/organisms/ChatInput/index.tsx
8185
+ function findChatInputTrigger(value, cursor) {
8186
+ const at = Math.max(0, Math.min(cursor, value.length));
8187
+ const start = value.slice(0, at).search(/\S*$/);
8188
+ const marker = value[start];
8189
+ if (marker !== "@" && marker !== "/") return null;
8190
+ let end = at;
8191
+ while (end < value.length && !/\s/.test(value[end])) end += 1;
8192
+ return {
8193
+ kind: marker === "@" ? "mention" : "command",
8194
+ query: value.slice(start + 1, at),
8195
+ start,
8196
+ end
8197
+ };
8198
+ }
8199
+ /** How many recently used entries keep their place at the top of the tray. */
8200
+ const RECENT_LIMIT = 8;
8201
+ /** A label hit always outranks the same query found in the other fields. */
8202
+ const LABEL_BONUS = 20;
8203
+ /**
8204
+ * Keeps the suggestions that match the query, ordered for the tray: recently
8205
+ * used entries first, then the strongest fuzzy match, then the caller's order.
8206
+ *
8207
+ * Labels win over ids, descriptions and keywords, and only label hits are
8208
+ * highlighted, matching CommandPalette and Combobox.
8209
+ */
8210
+ function matchChatInputSuggestions(items, query, recents = []) {
8211
+ const recentRank = new Map(recents.map((id, index) => [id, index]));
8212
+ return items.flatMap((item, order) => {
8213
+ const label = matchText(item.label, query);
8214
+ const hit = label ?? matchText(item.id, query) ?? matchText(item.description ?? "", query) ?? matchText(item.keywords ?? "", query);
8215
+ if (!hit) return [];
8216
+ return [{
8217
+ item,
8218
+ indexes: label?.indexes ?? [],
8219
+ recent: recentRank.get(item.id) ?? recents.length,
8220
+ score: label ? label.score + LABEL_BONUS : hit.score,
8221
+ order
8222
+ }];
8223
+ }).sort((a, b) => a.recent - b.recent || b.score - a.score || a.order - b.order).map(({ item, indexes }) => ({
8224
+ item,
8225
+ indexes
8226
+ }));
8227
+ }
8228
+ function filterChatInputSuggestions(items, query, recents = []) {
8229
+ return matchChatInputSuggestions(items, query, recents).map((match) => match.item);
8230
+ }
8231
+ function replaceChatInputTrigger(value, trigger, replacement) {
8232
+ const suffix = value.slice(trigger.end);
8233
+ const dedupeSpace = replacement.endsWith(" ") && suffix.startsWith(" ");
8234
+ const inserted = dedupeSpace ? replacement.slice(0, -1) : replacement;
8235
+ return {
8236
+ value: `${value.slice(0, trigger.start)}${inserted}${suffix}`,
8237
+ cursor: trigger.start + inserted.length + Number(dedupeSpace)
8238
+ };
8239
+ }
8240
+ function shouldSendOnEnter(event) {
8241
+ return event.key === "Enter" && !event.shiftKey && !event.ctrlKey && !event.metaKey && !event.altKey && !event.isComposing && event.keyCode !== 229;
8242
+ }
8243
+ function canPreviewImage(file) {
8244
+ return /^image\/(png|jpeg|gif|webp|avif|bmp)$/.test(file.type);
8245
+ }
8246
+ function FilePreview({ file, onRemove }) {
8247
+ const [url, setUrl] = useState();
8248
+ const [failed, setFailed] = useState(false);
8249
+ useEffect(() => {
8250
+ setFailed(false);
8251
+ if (!canPreviewImage(file)) {
8252
+ setUrl(void 0);
8253
+ return;
8254
+ }
8255
+ const next = URL.createObjectURL(file);
8256
+ setUrl(next);
8257
+ return () => URL.revokeObjectURL(next);
8258
+ }, [file]);
8259
+ const Icon = iconForFile(file.name);
8260
+ return /* @__PURE__ */ jsxs("li", {
8261
+ className: "sph-chat-input__file",
8262
+ title: file.name,
8263
+ children: [url && !failed ? /* @__PURE__ */ jsx("img", {
8264
+ className: "sph-chat-input__preview",
8265
+ src: url,
8266
+ alt: file.name,
8267
+ onError: () => setFailed(true)
8268
+ }) : /* @__PURE__ */ jsxs("div", {
8269
+ className: "sph-chat-input__file-info",
8270
+ children: [
8271
+ /* @__PURE__ */ jsx(Icon, {
8272
+ size: 22,
8273
+ "aria-hidden": "true"
8274
+ }),
8275
+ /* @__PURE__ */ jsx("span", { children: file.name }),
8276
+ /* @__PURE__ */ jsxs("small", { children: [Math.ceil(file.size / 1024), " KB"] })
8277
+ ]
8278
+ }), onRemove && /* @__PURE__ */ jsx(IconButton, {
8279
+ className: "sph-chat-input__remove",
8280
+ size: "sm",
8281
+ label: `Remove ${file.name}`,
8282
+ icon: /* @__PURE__ */ jsx(XIcon, {
8283
+ size: 14,
8284
+ "aria-hidden": "true"
8285
+ }),
8286
+ onClick: onRemove
8287
+ })]
8288
+ });
8289
+ }
8290
+ function ChatInput({ value, defaultValue = "", onValueChange, files, onFilesChange, onSend, onStop, state = "ready", disabled = false, placeholder = "Message the agent…", label = "Message the agent", sendLabel = "Send message", stopLabel = "Stop response", addFilesLabel = "Add files", mentions = [], commands = [], onMentionSelect, onCommandSelect, mentionLabel = "Files and context", commandLabel = "Commands", tools, hint, error, accept, maxFiles = 5, maxSize = 10485760, onReject, className, onPaste, ...props }) {
8291
+ const [draft, setDraft] = useState(defaultValue);
8292
+ const [localFiles, setLocalFiles] = useState([]);
8293
+ const [announcement, setAnnouncement] = useState("");
8294
+ const picker = useRef(null);
8295
+ const editor = useRef(null);
8296
+ const form = useRef(null);
8297
+ const composing = useRef(false);
8298
+ const [isComposing, setIsComposing] = useState(false);
8299
+ const [cursor, setCursor] = useState((value ?? defaultValue).length);
8300
+ const [activeSuggestion, setActiveSuggestion] = useState(0);
8301
+ const [suggestionsDismissed, setSuggestionsDismissed] = useState(false);
8302
+ const [recents, setRecents] = useState([]);
8303
+ const pendingCursor = useRef(null);
8304
+ const errorId = `${useId()}-error`;
8305
+ const suggestionListId = `${useId()}-suggestions`;
8306
+ const text = value ?? draft;
8307
+ const attachments = files ?? localFiles;
8308
+ const busy = state === "submitting" || state === "streaming";
8309
+ const locked = disabled || busy;
8310
+ const canSend = !locked && (text.trim().length > 0 || attachments.length > 0);
8311
+ const trigger = !isComposing ? findChatInputTrigger(text, cursor) : null;
8312
+ const recentIds = (kind) => recents.flatMap((entry) => {
8313
+ const prefix = `${kind}:`;
8314
+ return entry.startsWith(prefix) ? [entry.slice(prefix.length)] : [];
8315
+ });
8316
+ const suggestions = trigger ? matchChatInputSuggestions(trigger.kind === "mention" ? mentions : commands, trigger.query, recentIds(trigger.kind)) : [];
8317
+ const suggestionItems = suggestions.map((match) => match.item);
8318
+ const suggestionsOpen = Boolean(trigger && suggestionItems.length > 0 && !locked && !suggestionsDismissed);
8319
+ const tray = usePresence(suggestionsOpen, "fast");
8320
+ const lastTray = useRef(null);
8321
+ if (suggestionsOpen && trigger) lastTray.current = {
8322
+ kind: trigger.kind,
8323
+ label: trigger.kind === "mention" ? mentionLabel : commandLabel,
8324
+ matches: suggestions
8325
+ };
8326
+ const trayContent = tray.present ? lastTray.current : null;
8327
+ const enabledSuggestions = suggestionItems.flatMap((item, index) => item.disabled ? [] : [index]);
8328
+ const activeSuggestionIndex = enabledSuggestions.includes(activeSuggestion) ? activeSuggestion : enabledSuggestions[0] ?? -1;
8329
+ useIsoLayoutEffect(() => {
8330
+ if (pendingCursor.current === null) return;
8331
+ const next = pendingCursor.current;
8332
+ pendingCursor.current = null;
8333
+ editor.current?.setSelectionRange(next, next);
8334
+ }, [text]);
8335
+ useIsoLayoutEffect(() => {
8336
+ const textarea = editor.current;
8337
+ if (!textarea || typeof CSS !== "undefined" && CSS.supports("field-sizing", "content")) return;
8338
+ const resize = () => {
8339
+ textarea.style.height = "auto";
8340
+ textarea.style.height = `${textarea.scrollHeight}px`;
8341
+ };
8342
+ resize();
8343
+ if (typeof ResizeObserver === "undefined") return;
8344
+ let width = textarea.clientWidth;
8345
+ const observer = new ResizeObserver(() => {
8346
+ if (textarea.clientWidth !== width) {
8347
+ width = textarea.clientWidth;
8348
+ resize();
8349
+ }
8350
+ });
8351
+ observer.observe(textarea);
8352
+ return () => observer.disconnect();
8353
+ }, [text]);
8354
+ const changeFiles = (next) => {
8355
+ if (files === void 0) setLocalFiles(next);
8356
+ onFilesChange?.(next);
8357
+ };
8358
+ const addFiles = (incoming) => {
8359
+ if (locked) return;
8360
+ const result = validateDropzoneFiles(incoming, {
8361
+ accept,
8362
+ maxSize,
8363
+ maxFiles: Math.max(0, maxFiles - attachments.length)
8364
+ });
8365
+ if (result.accepted.length) changeFiles([...attachments, ...result.accepted]);
8366
+ setAnnouncement(describeDropzoneResult(result));
8367
+ for (const rejected of result.rejected) onReject?.(rejected.files, rejected.reason);
8368
+ };
8369
+ const chooseSuggestion = (item) => {
8370
+ if (!trigger || item.disabled) return;
8371
+ const mention = trigger.kind === "mention";
8372
+ const replacement = mention ? `@${item.insertText ?? item.id} ` : item.insertText ?? "";
8373
+ const next = replaceChatInputTrigger(text, trigger, replacement);
8374
+ pendingCursor.current = next.cursor;
8375
+ setCursor(next.cursor);
8376
+ if (value === void 0) setDraft(next.value);
8377
+ onValueChange?.(next.value);
8378
+ const key = `${trigger.kind}:${item.id}`;
8379
+ setRecents((previous) => [key, ...previous.filter((entry) => entry !== key)].slice(0, RECENT_LIMIT));
8380
+ if (mention) onMentionSelect?.(item);
8381
+ else onCommandSelect?.(item);
8382
+ };
8383
+ const keyDown = (event) => {
8384
+ if (suggestionsOpen && !composing.current && (event.key === "ArrowDown" || event.key === "ArrowUp")) {
8385
+ event.preventDefault();
8386
+ const current = enabledSuggestions.indexOf(activeSuggestionIndex);
8387
+ const offset = event.key === "ArrowDown" ? 1 : -1;
8388
+ const next = enabledSuggestions[(current + offset + enabledSuggestions.length) % enabledSuggestions.length];
8389
+ if (next !== void 0) setActiveSuggestion(next);
8390
+ return;
8391
+ }
8392
+ if (suggestionsOpen && !composing.current && event.key === "Escape") {
8393
+ event.preventDefault();
8394
+ setSuggestionsDismissed(true);
8395
+ return;
8396
+ }
8397
+ if (suggestionsOpen && !composing.current && event.key === "Enter" && activeSuggestionIndex >= 0) {
8398
+ event.preventDefault();
8399
+ chooseSuggestion(suggestionItems[activeSuggestionIndex]);
8400
+ return;
8401
+ }
8402
+ if (!suggestionsOpen && !composing.current && shouldSendOnEnter({
8403
+ key: event.key,
8404
+ shiftKey: event.shiftKey,
8405
+ ctrlKey: event.ctrlKey,
8406
+ metaKey: event.metaKey,
8407
+ altKey: event.altKey,
8408
+ isComposing: event.nativeEvent?.isComposing ?? event.isComposing,
8409
+ keyCode: event.keyCode
8410
+ })) {
8411
+ event.preventDefault();
8412
+ if (canSend && !event.repeat) form.current?.requestSubmit();
8413
+ }
8414
+ };
8415
+ return /* @__PURE__ */ jsxs("form", {
8416
+ ...node(props),
8417
+ ref: form,
8418
+ className: cn("sph-chat-input", className),
8419
+ "data-state": state,
8420
+ "aria-label": label,
8421
+ "data-disabled": disabled || void 0,
8422
+ onPaste: (event) => {
8423
+ onPaste?.(event);
8424
+ if (event.defaultPrevented) return;
8425
+ const incoming = Array.from(event.clipboardData?.files ?? []);
8426
+ if (!incoming.length) return;
8427
+ if (!event.clipboardData?.getData("text/plain")) event.preventDefault();
8428
+ addFiles(incoming);
8429
+ },
8430
+ onSubmit: (event) => {
8431
+ event.preventDefault();
8432
+ if (canSend) onSend({
8433
+ text,
8434
+ files: [...attachments]
8435
+ });
8436
+ },
8437
+ onDragOver: (event) => {
8438
+ if (event.dataTransfer?.types.includes("Files")) event.preventDefault();
8439
+ },
8440
+ onDrop: (event) => {
8441
+ if (!event.dataTransfer?.files.length) return;
8442
+ event.preventDefault();
8443
+ addFiles(Array.from(event.dataTransfer.files));
8444
+ },
8445
+ children: [
8446
+ /* @__PURE__ */ jsx("textarea", {
8447
+ ref: editor,
8448
+ className: "sph-chat-input__textarea",
8449
+ rows: 1,
8450
+ value: text,
8451
+ placeholder,
8452
+ "aria-label": label,
8453
+ disabled,
8454
+ readOnly: busy,
8455
+ "aria-invalid": state === "error" || void 0,
8456
+ "aria-describedby": error !== void 0 ? errorId : void 0,
8457
+ "aria-autocomplete": "list",
8458
+ "aria-haspopup": "listbox",
8459
+ "aria-expanded": suggestionsOpen,
8460
+ "aria-controls": suggestionsOpen ? suggestionListId : void 0,
8461
+ "aria-activedescendant": activeSuggestionIndex >= 0 && suggestionsOpen ? `${suggestionListId}-${activeSuggestionIndex}` : void 0,
8462
+ onSelect: (event) => {
8463
+ setSuggestionsDismissed(false);
8464
+ setActiveSuggestion(0);
8465
+ setCursor(event.currentTarget.selectionStart ?? 0);
8466
+ },
8467
+ onCompositionStart: () => {
8468
+ composing.current = true;
8469
+ setIsComposing(true);
8470
+ },
8471
+ onCompositionEnd: (event) => {
8472
+ composing.current = false;
8473
+ setSuggestionsDismissed(false);
8474
+ setIsComposing(false);
8475
+ setCursor(event.currentTarget.selectionStart ?? 0);
8476
+ },
8477
+ onKeyDown: keyDown,
8478
+ onInput: (event) => {
8479
+ const next = event.currentTarget.value;
8480
+ setSuggestionsDismissed(false);
8481
+ setActiveSuggestion(0);
8482
+ if (value === void 0) setDraft(next);
8483
+ setCursor(event.currentTarget.selectionStart ?? next.length);
8484
+ onValueChange?.(next);
8485
+ }
8486
+ }),
8487
+ trayContent && /* @__PURE__ */ jsxs("div", {
8488
+ ref: tray.ref,
8489
+ className: "sph-chat-input__suggestions",
8490
+ id: suggestionListId,
8491
+ role: "listbox",
8492
+ "data-state": tray.state,
8493
+ "data-kind": trayContent.kind,
8494
+ "aria-label": trayContent.label,
8495
+ children: [/* @__PURE__ */ jsx("span", {
8496
+ className: "sph-chat-input__suggestions-label",
8497
+ "aria-hidden": "true",
8498
+ children: trayContent.label
8499
+ }), trayContent.matches.map(({ item, indexes }, index) => {
8500
+ const mention = trayContent.kind === "mention";
8501
+ const Icon = mention ? iconForFile(item.id) : void 0;
8502
+ return /* @__PURE__ */ jsxs("div", {
8503
+ id: `${suggestionListId}-${index}`,
8504
+ role: "option",
8505
+ "aria-selected": index === activeSuggestionIndex,
8506
+ "aria-disabled": item.disabled || void 0,
8507
+ className: "sph-chat-input__suggestion",
8508
+ "data-active": index === activeSuggestionIndex || void 0,
8509
+ "data-disabled": item.disabled || void 0,
8510
+ style: { "--sph-motion-index": index },
8511
+ onMouseDown: (event) => event.preventDefault(),
8512
+ onClick: () => chooseSuggestion(item),
8513
+ children: [
8514
+ Icon && /* @__PURE__ */ jsx(Icon, {
8515
+ className: "sph-chat-input__suggestion-icon",
8516
+ size: 16,
8517
+ "aria-hidden": "true"
8518
+ }),
8519
+ /* @__PURE__ */ jsxs("span", {
8520
+ className: "sph-chat-input__suggestion-body",
8521
+ children: [/* @__PURE__ */ jsxs("span", {
8522
+ className: "sph-chat-input__suggestion-name",
8523
+ children: [/* @__PURE__ */ jsx("span", {
8524
+ className: "sph-chat-input__suggestion-token",
8525
+ "aria-hidden": "true",
8526
+ children: mention ? "@" : "/"
8527
+ }), /* @__PURE__ */ jsx(Highlight, {
8528
+ text: item.label,
8529
+ indexes
8530
+ })]
8531
+ }), item.description && /* @__PURE__ */ jsx("span", {
8532
+ className: "sph-chat-input__suggestion-description",
8533
+ children: item.description
8534
+ })]
8535
+ }),
8536
+ /* @__PURE__ */ jsx("span", {
8537
+ className: "sph-chat-input__suggestion-enter",
8538
+ "aria-hidden": "true",
8539
+ children: "↵"
8540
+ })
8541
+ ]
8542
+ }, item.id);
8543
+ })]
8544
+ }, trayContent.kind),
8545
+ attachments.length > 0 && /* @__PURE__ */ jsx("ul", {
8546
+ className: "sph-chat-input__files",
8547
+ "aria-label": "Attachments",
8548
+ children: attachments.map((file, index) => /* @__PURE__ */ jsx(FilePreview, {
8549
+ file,
8550
+ onRemove: locked ? void 0 : () => {
8551
+ changeFiles(attachments.filter((_, at) => at !== index));
8552
+ editor.current?.focus();
8553
+ }
8554
+ }, `${index}-${file.name}-${file.lastModified}`))
8555
+ }),
8556
+ /* @__PURE__ */ jsxs("div", {
8557
+ className: "sph-chat-input__rail",
8558
+ children: [
8559
+ /* @__PURE__ */ jsx("input", {
8560
+ ref: picker,
8561
+ type: "file",
8562
+ accept,
8563
+ multiple: true,
8564
+ hidden: true,
8565
+ disabled: locked,
8566
+ onChange: (event) => {
8567
+ addFiles(Array.from(event.currentTarget.files ?? []));
8568
+ event.currentTarget.value = "";
8569
+ }
8570
+ }),
8571
+ /* @__PURE__ */ jsx("div", {
8572
+ className: "sph-chat-input__tools",
8573
+ children: node(tools)
8574
+ }),
8575
+ /* @__PURE__ */ jsxs("div", {
8576
+ className: "sph-chat-input__actions",
8577
+ children: [/* @__PURE__ */ jsx(IconButton, {
8578
+ size: "md",
8579
+ label: addFilesLabel,
8580
+ disabled: locked,
8581
+ icon: /* @__PURE__ */ jsx(PlusIcon, {
8582
+ size: 20,
8583
+ "aria-hidden": "true"
8584
+ }),
8585
+ onClick: () => picker.current?.click()
8586
+ }), busy ? /* @__PURE__ */ jsx(IconButton, {
8587
+ type: "button",
8588
+ size: "md",
8589
+ variant: "solid",
8590
+ label: stopLabel,
8591
+ icon: /* @__PURE__ */ jsx(StopIcon, {
8592
+ size: 18,
8593
+ "aria-hidden": "true"
8594
+ }),
8595
+ disabled: disabled || !onStop,
8596
+ onClick: () => onStop?.()
8597
+ }, "stop") : /* @__PURE__ */ jsx(IconButton, {
8598
+ type: "submit",
8599
+ size: "md",
8600
+ variant: "solid",
8601
+ label: sendLabel,
8602
+ icon: /* @__PURE__ */ jsx(ArrowUpIcon, {
8603
+ size: 20,
8604
+ "aria-hidden": "true"
8605
+ }),
8606
+ disabled: !canSend
8607
+ }, "send")]
8608
+ })
8609
+ ]
8610
+ }),
8611
+ hint !== void 0 && /* @__PURE__ */ jsx("div", {
8612
+ className: "sph-chat-input__hint",
8613
+ children: node(hint)
8614
+ }),
8615
+ error !== void 0 && /* @__PURE__ */ jsx("div", {
8616
+ id: errorId,
8617
+ className: "sph-chat-input__error",
8618
+ role: "alert",
8619
+ children: node(error)
8620
+ }),
8621
+ /* @__PURE__ */ jsx("span", {
8622
+ className: "sph-visually-hidden",
8623
+ role: "status",
8624
+ children: announcement
8625
+ })
8626
+ ]
8627
+ });
8628
+ }
8629
+ //#endregion
8630
+ //#region src/molecules/Message/index.tsx
8631
+ const labels$2 = {
8632
+ streaming: "Responding",
8633
+ complete: "Complete",
8634
+ stopped: "Stopped",
8635
+ error: "Response failed"
8636
+ };
8637
+ function Message({ author, role = "assistant", state = "complete", children, avatar, metadata, actions, error, onRetry, retryLabel = "Retry", statusLabel, className, ...props }) {
8638
+ const heading = useId();
8639
+ return /* @__PURE__ */ jsxs("article", {
8640
+ ...node(props),
8641
+ className: cn("sph-message", className),
8642
+ "data-role": role,
8643
+ "data-state": state,
8644
+ "aria-labelledby": heading,
8645
+ children: [
8646
+ /* @__PURE__ */ jsxs("header", {
8647
+ className: "sph-message__header",
8648
+ children: [
8649
+ node(avatar),
8650
+ /* @__PURE__ */ jsx("span", {
8651
+ id: heading,
8652
+ className: "sph-message__author",
8653
+ children: author
8654
+ }),
8655
+ /* @__PURE__ */ jsx("span", {
8656
+ className: "sph-message__metadata",
8657
+ children: node(metadata)
8658
+ })
8659
+ ]
8660
+ }),
8661
+ /* @__PURE__ */ jsx("div", {
8662
+ className: "sph-message__content",
8663
+ children: node(children)
8664
+ }),
8665
+ /* @__PURE__ */ jsxs("footer", {
8666
+ className: "sph-message__footer",
8667
+ children: [
8668
+ /* @__PURE__ */ jsx("span", {
8669
+ role: "status",
8670
+ className: state === "complete" ? "sph-visually-hidden" : "sph-message__status",
8671
+ children: statusLabel ?? labels$2[state]
8672
+ }),
8673
+ node(actions),
8674
+ (state === "error" || state === "stopped") && onRetry && /* @__PURE__ */ jsx(Button, {
8675
+ size: "sm",
8676
+ variant: "quiet",
8677
+ onClick: onRetry,
8678
+ children: retryLabel
8679
+ })
8680
+ ]
8681
+ }),
8682
+ state === "error" && error !== void 0 && /* @__PURE__ */ jsx("div", {
8683
+ className: "sph-message__error",
8684
+ role: "alert",
8685
+ children: node(error)
8686
+ })
8687
+ ]
8688
+ });
8689
+ }
8690
+ //#endregion
8691
+ //#region src/molecules/ApprovalCard/index.tsx
8692
+ const labels$1 = {
8693
+ pending: "Approval required",
8694
+ submitting: "Sending decision",
8695
+ approved: "Approved",
8696
+ rejected: "Rejected",
8697
+ expired: "Approval expired",
8698
+ error: "Decision failed"
8699
+ };
8700
+ function ApprovalCard({ title, action, target, description, state = "pending", onApprove, onReject, approveLabel = "Approve action", rejectLabel = "Reject", statusLabel, error, className, ...props }) {
8701
+ const id = useId();
8702
+ const actionable = state === "pending" || state === "error";
8703
+ return /* @__PURE__ */ jsxs("div", {
8704
+ ...node(props),
8705
+ className: cn("sph-approval-card", className),
8706
+ "data-state": state,
8707
+ role: "group",
8708
+ "aria-labelledby": `${id}-title`,
8709
+ "aria-describedby": `${id}-details`,
8710
+ children: [
8711
+ /* @__PURE__ */ jsxs("div", {
8712
+ className: "sph-approval-card__header",
8713
+ children: [/* @__PURE__ */ jsx("h3", {
8714
+ id: `${id}-title`,
8715
+ className: "sph-approval-card__title",
8716
+ children: node(title)
8717
+ }), /* @__PURE__ */ jsx("span", {
8718
+ role: "status",
8719
+ className: "sph-approval-card__status",
8720
+ children: statusLabel ?? labels$1[state]
8721
+ })]
8722
+ }),
8723
+ /* @__PURE__ */ jsxs("div", {
8724
+ id: `${id}-details`,
8725
+ className: "sph-approval-card__details",
8726
+ children: [
8727
+ /* @__PURE__ */ jsx("div", {
8728
+ className: "sph-approval-card__action",
8729
+ children: node(action)
8730
+ }),
8731
+ target !== void 0 && /* @__PURE__ */ jsx("div", {
8732
+ className: "sph-approval-card__target",
8733
+ children: node(target)
8734
+ }),
8735
+ description !== void 0 && /* @__PURE__ */ jsx("div", { children: node(description) })
8736
+ ]
8737
+ }),
8738
+ state === "error" && error !== void 0 && /* @__PURE__ */ jsx("div", {
8739
+ role: "alert",
8740
+ children: node(error)
8741
+ }),
8742
+ (actionable || state === "submitting") && /* @__PURE__ */ jsxs("div", {
8743
+ className: "sph-approval-card__footer",
8744
+ children: [/* @__PURE__ */ jsx(Button, {
8745
+ size: "sm",
8746
+ variant: "quiet",
8747
+ disabled: !actionable,
8748
+ onClick: onReject,
8749
+ children: rejectLabel
8750
+ }), /* @__PURE__ */ jsx(Button, {
8751
+ size: "sm",
8752
+ variant: "primary",
8753
+ disabled: !actionable,
8754
+ loading: state === "submitting",
8755
+ onClick: onApprove,
8756
+ children: approveLabel
8757
+ })]
8758
+ })
8759
+ ]
8760
+ });
8761
+ }
8762
+ //#endregion
8763
+ //#region src/molecules/CodeBlock/index.tsx
8764
+ function CodeBlock({ code, language, filename, wrap = false, renderCode, onCopy, copyLabel = "Copy code", copiedLabel = "Copied", copyErrorLabel = "Could not copy code", className, ...props }) {
8765
+ const [copyState, setCopyState] = useState("idle");
8766
+ const copy = async () => {
8767
+ setCopyState("copying");
8768
+ try {
8769
+ if (onCopy) await onCopy(code);
8770
+ else await navigator.clipboard.writeText(code);
8771
+ setCopyState("copied");
8772
+ } catch {
8773
+ setCopyState("error");
8774
+ }
8775
+ };
8776
+ return /* @__PURE__ */ jsxs("figure", {
8777
+ ...node(props),
8778
+ className: cn("sph-code-block", className),
8779
+ "data-wrap": wrap || void 0,
8780
+ children: [
8781
+ /* @__PURE__ */ jsxs("figcaption", {
8782
+ className: "sph-code-block__header",
8783
+ children: [
8784
+ /* @__PURE__ */ jsx("span", { children: filename ?? language ?? "Code" }),
8785
+ filename && language && /* @__PURE__ */ jsx("span", {
8786
+ className: "sph-code-block__language",
8787
+ children: language
8788
+ }),
8789
+ /* @__PURE__ */ jsx(Button, {
8790
+ size: "sm",
8791
+ variant: "quiet",
8792
+ disabled: copyState === "copying",
8793
+ onClick: copy,
8794
+ children: copyLabel
8795
+ })
8796
+ ]
8797
+ }),
8798
+ /* @__PURE__ */ jsx("pre", {
8799
+ className: "sph-code-block__pre",
8800
+ tabIndex: 0,
8801
+ "aria-label": filename ?? language ?? "Code",
8802
+ children: /* @__PURE__ */ jsx("code", { children: renderCode ? node(renderCode(code, language)) : code })
8803
+ }),
8804
+ /* @__PURE__ */ jsx("span", {
8805
+ role: "status",
8806
+ className: copyState === "error" ? "sph-code-block__feedback" : "sph-visually-hidden",
8807
+ children: copyState === "copied" ? copiedLabel : copyState === "error" ? copyErrorLabel : ""
8808
+ })
8809
+ ]
8810
+ });
8811
+ }
8812
+ //#endregion
8813
+ //#region src/molecules/DiffView/index.tsx
8814
+ function diffStats(hunks) {
8815
+ let added = 0;
8816
+ let removed = 0;
8817
+ for (const hunk of hunks) for (const line of hunk.lines) {
8818
+ if (line.type === "added") added++;
8819
+ if (line.type === "removed") removed++;
8820
+ }
8821
+ return {
8822
+ added,
8823
+ removed
8824
+ };
8825
+ }
8826
+ function Hunk({ hunk, contextLimit, expandLabel, collapseLabel }) {
8827
+ const [expanded, setExpanded] = useState(false);
8828
+ const id = useId();
8829
+ const limit = Math.max(0, Math.floor(contextLimit));
8830
+ let context = 0;
8831
+ const visible = hunk.lines.filter((line) => {
8832
+ if (line.type !== "context") {
8833
+ context = 0;
8834
+ return true;
8835
+ }
8836
+ return ++context <= limit;
8837
+ });
8838
+ const hidden = hunk.lines.length - visible.length;
8839
+ const lines = expanded ? hunk.lines : visible;
8840
+ return /* @__PURE__ */ jsxs("section", {
8841
+ className: "sph-diff-view__hunk",
8842
+ "aria-label": hunk.header,
8843
+ children: [/* @__PURE__ */ jsxs("div", {
8844
+ className: "sph-diff-view__hunk-header",
8845
+ children: [/* @__PURE__ */ jsx("code", { children: hunk.header }), hidden > 0 && /* @__PURE__ */ jsx(Button, {
8846
+ size: "sm",
8847
+ variant: "quiet",
8848
+ "aria-expanded": expanded,
8849
+ "aria-controls": id,
8850
+ onClick: () => setExpanded(!expanded),
8851
+ children: expanded ? collapseLabel : `${expandLabel} (${hidden})`
8852
+ })]
8853
+ }), /* @__PURE__ */ jsx("div", {
8854
+ id,
8855
+ className: "sph-diff-view__lines",
8856
+ children: lines.map((line, index) => /* @__PURE__ */ jsxs("div", {
8857
+ className: "sph-diff-view__line",
8858
+ "data-kind": line.type,
8859
+ children: [
8860
+ /* @__PURE__ */ jsx("span", {
8861
+ className: "sph-diff-view__number",
8862
+ children: line.oldLine ?? ""
8863
+ }),
8864
+ /* @__PURE__ */ jsx("span", {
8865
+ className: "sph-diff-view__number",
8866
+ children: line.newLine ?? ""
8867
+ }),
8868
+ /* @__PURE__ */ jsx("span", {
8869
+ className: "sph-diff-view__sign",
8870
+ "aria-label": line.type,
8871
+ children: line.type === "added" ? "+" : line.type === "removed" ? "−" : " "
8872
+ }),
8873
+ /* @__PURE__ */ jsx("code", { children: line.text })
8874
+ ]
8875
+ }, index))
8876
+ })]
8877
+ });
8878
+ }
8879
+ function DiffView({ filename, hunks, contextLimit = 3, actions, emptyLabel = "No changes", expandLabel = "Show context", collapseLabel = "Hide context", className, ...props }) {
8880
+ const stats = diffStats(hunks);
8881
+ return /* @__PURE__ */ jsxs("figure", {
8882
+ ...node(props),
8883
+ className: cn("sph-diff-view", className),
8884
+ children: [/* @__PURE__ */ jsxs("figcaption", {
8885
+ className: "sph-diff-view__header",
8886
+ children: [
8887
+ /* @__PURE__ */ jsx("span", { children: filename }),
8888
+ /* @__PURE__ */ jsxs("span", {
8889
+ className: "sph-diff-view__stats",
8890
+ children: [
8891
+ stats.added,
8892
+ " added · ",
8893
+ stats.removed,
8894
+ " removed"
8895
+ ]
8896
+ }),
8897
+ node(actions)
8898
+ ]
8899
+ }), /* @__PURE__ */ jsx("div", {
8900
+ className: "sph-diff-view__viewport",
8901
+ tabIndex: 0,
8902
+ "aria-label": `Changes in ${filename}`,
8903
+ children: hunks.length ? hunks.map((hunk) => /* @__PURE__ */ jsx(Hunk, {
8904
+ hunk,
8905
+ contextLimit,
8906
+ expandLabel,
8907
+ collapseLabel
8908
+ }, hunk.id)) : /* @__PURE__ */ jsx("p", { children: emptyLabel })
8909
+ })]
8910
+ });
8911
+ }
8912
+ //#endregion
8913
+ //#region src/molecules/ArtifactCard/index.tsx
8914
+ const labels = {
8915
+ generating: "Generating",
8916
+ ready: "Ready",
8917
+ error: "Generation failed"
8918
+ };
8919
+ function ArtifactCard({ title, kind, description, version, state = "ready", children, actions, onOpen, openLabel = "Open artifact", statusLabel, className, ...props }) {
8920
+ const id = useId();
8921
+ return /* @__PURE__ */ jsxs("article", {
8922
+ ...node(props),
8923
+ className: cn("sph-artifact-card", className),
8924
+ "data-state": state,
8925
+ "aria-labelledby": id,
8926
+ children: [
8927
+ /* @__PURE__ */ jsxs("header", {
8928
+ className: "sph-artifact-card__header",
8929
+ children: [
8930
+ /* @__PURE__ */ jsxs("div", {
8931
+ className: "sph-artifact-card__meta",
8932
+ children: [node(kind), version && /* @__PURE__ */ jsx("span", { children: version })]
8933
+ }),
8934
+ /* @__PURE__ */ jsx("h3", {
8935
+ id,
8936
+ className: "sph-artifact-card__title",
8937
+ children: node(title)
8938
+ }),
8939
+ description !== void 0 && /* @__PURE__ */ jsx("p", {
8940
+ className: "sph-artifact-card__description",
8941
+ children: node(description)
8942
+ })
8943
+ ]
8944
+ }),
8945
+ children !== void 0 && /* @__PURE__ */ jsx("div", {
8946
+ className: "sph-artifact-card__content",
8947
+ children: node(children)
8948
+ }),
8949
+ /* @__PURE__ */ jsxs("footer", {
8950
+ className: "sph-artifact-card__footer",
8951
+ children: [
8952
+ /* @__PURE__ */ jsx("span", {
8953
+ role: "status",
8954
+ children: statusLabel ?? labels[state]
8955
+ }),
8956
+ node(actions),
8957
+ onOpen && /* @__PURE__ */ jsx(Button, {
8958
+ size: "sm",
8959
+ disabled: state !== "ready",
8960
+ onClick: onOpen,
8961
+ children: openLabel
8962
+ })
8963
+ ]
8964
+ })
8965
+ ]
8966
+ });
8967
+ }
8968
+ //#endregion
8969
+ export { Accordion, AnimatedNumber, ApprovalCard, ArtifactCard, Attachment, Avatar, AvatarGroup, Badge, Breadcrumb, Button, Calendar, Card, Carousel, Chart, ChatInput, ChatScroller, Checkbox, Citation, CodeBlock, Collapsible, Combobox, CommandPalette, ContextMenu, DateRangeField, Delta, Dialog, DiffView, Drawer, EmptyState, Field, FieldMessage, HoldButton, HoverCard, IconButton, Input, Kbd, MagneticDropzone, Menu, Menubar, Message, MetadataList, Notice, NumberInput, OTPInput, OverflowList, Pagination, PlanCard, Popover, Progress, QuestionCard, RadioGroup, ReasoningSteps, Resizable, Reveal, ScrollArea, SegmentedControl, Select, Separator, SidePanel, Sidebar, Skeleton, Slider, Spinner, Stat, StatGroup, StatusMark, Stepper, StreamingText, Surface, Table, Tabs, TaskList, Textarea, Timeline, Timestamp, Toast, ToastViewport, Toggle, ToolCalls, Toolbar, Tooltip, TooltipGroup, TreeView, dayFromSegments, describeDropzoneResult, filterChatInputSuggestions, findChatInputTrigger, matchChatInputSuggestions, motionDurationMs, orderRange, parseDurationMs, replaceChatInputTrigger, segmentsOf, slideAfter, stepSegment, toast, typeSegment, usePresence, validateDropzoneFiles };
7512
8970
 
7513
8971
  //# sourceMappingURL=index.js.map