@helsenorge/datepicker 13.4.0 → 13.6.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.
Files changed (33) hide show
  1. package/lib/CHANGELOG.md +40 -0
  2. package/lib/DayPicker.js +2188 -0
  3. package/lib/DayPicker.js.map +1 -0
  4. package/lib/components/DatePicker/DatePicker.d.ts +1 -1
  5. package/lib/components/DatePicker/index.js +5 -1976
  6. package/lib/components/DatePicker/index.js.map +1 -1
  7. package/lib/components/Unsafe_DatePicker/BaseDayPicker/BaseDayPicker.d.ts +31 -0
  8. package/lib/components/Unsafe_DatePicker/BaseDayPicker/BaseDayPicker.module.scss +446 -0
  9. package/lib/components/Unsafe_DatePicker/BaseDayPicker/BaseDayPicker.module.scss.d.ts +31 -0
  10. package/lib/components/Unsafe_DatePicker/BaseDayPicker/CustomComponents.d.ts +6 -0
  11. package/lib/components/Unsafe_DatePicker/BaseDayPicker/utils.d.ts +1 -0
  12. package/lib/components/Unsafe_DatePicker/DateInputInternal.d.ts +28 -0
  13. package/lib/components/Unsafe_DatePicker/DatePicker.module.scss +277 -0
  14. package/lib/components/Unsafe_DatePicker/DatePicker.module.scss.d.ts +24 -0
  15. package/lib/components/Unsafe_DatePicker/RangeDatePickers.module.scss +9 -0
  16. package/lib/components/Unsafe_DatePicker/RangeDatePickers.module.scss.d.ts +9 -0
  17. package/lib/components/Unsafe_DatePicker/TimeInput/TimeInputInternal.d.ts +23 -0
  18. package/lib/components/Unsafe_DatePicker/TimeInput/Unsafe_TimeInput.d.ts +25 -0
  19. package/lib/components/Unsafe_DatePicker/Unsafe_DateAndTime.d.ts +16 -0
  20. package/lib/components/Unsafe_DatePicker/Unsafe_DateAndTime.module.scss +18 -0
  21. package/lib/components/Unsafe_DatePicker/Unsafe_DateAndTime.module.scss.d.ts +10 -0
  22. package/lib/components/Unsafe_DatePicker/Unsafe_DatePicker.d.ts +26 -0
  23. package/lib/components/Unsafe_DatePicker/Unsafe_ISODatePicker.d.ts +9 -0
  24. package/lib/components/Unsafe_DatePicker/Unsafe_RangeDatePickers.d.ts +12 -0
  25. package/lib/components/Unsafe_DatePicker/index.d.ts +11 -0
  26. package/lib/components/Unsafe_DatePicker/index.js +3702 -0
  27. package/lib/components/Unsafe_DatePicker/index.js.map +1 -0
  28. package/lib/components/Unsafe_DatePicker/resourceHelper.d.ts +3 -0
  29. package/lib/components/Unsafe_DatePicker/validate.d.ts +1 -0
  30. package/lib/resources/HN.Designsystem.DatePicker.en-GB.json.d.ts +1 -4
  31. package/lib/resources/HN.Designsystem.DatePicker.nb-NO.json.d.ts +1 -6
  32. package/lib/resources/HN.Designsystem.Unsafe_DatePicker.nb-NO.json.d.ts +32 -0
  33. package/package.json +2 -1
@@ -0,0 +1,3702 @@
1
+ import { i as CaptionLabel, n as useDayPicker, r as MonthGrid, t as DayPicker } from "../../DayPicker.js";
2
+ import * as React$1 from "react";
3
+ import React, { cloneElement, useEffect, useLayoutEffect, useRef, useState } from "react";
4
+ import { format, formatISO, isSameDay, isValid, parse } from "date-fns";
5
+ import { nb } from "date-fns/locale";
6
+ import Button from "@helsenorge/designsystem-react/components/Button";
7
+ import Icon, { IconSize } from "@helsenorge/designsystem-react/components/Icon";
8
+ import Calendar from "@helsenorge/designsystem-react/components/Icons/Calendar";
9
+ import { useLanguage } from "@helsenorge/designsystem-react/utils/language";
10
+ import { mergeRefs } from "@helsenorge/designsystem-react/utils/refs";
11
+ import classNames from "classnames";
12
+ import reactdaypickerstyles from "react-day-picker/dist/style.module.css";
13
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
14
+ import { IconSize as IconSize$1, KeyboardEventKey, LanguageLocales, useKeyboardEvent, useOutsideEvent, usePseudoClasses, useToggle } from "@helsenorge/designsystem-react";
15
+ import ErrorWrapper from "@helsenorge/designsystem-react/components/ErrorWrapper";
16
+ import { isComponent } from "@helsenorge/designsystem-react/utils/component";
17
+ import Loader from "@helsenorge/designsystem-react/components/Loader";
18
+ import ChevronDown from "@helsenorge/designsystem-react/components/Icons/ChevronDown";
19
+ import ChevronLeft from "@helsenorge/designsystem-react/components/Icons/ChevronLeft";
20
+ import ChevronRight from "@helsenorge/designsystem-react/components/Icons/ChevronRight";
21
+ import { useIsMobileBreakpoint } from "@helsenorge/designsystem-react/hooks/useIsMobileBreakpoint";
22
+ import customstyles from "./BaseDayPicker/BaseDayPicker.module.scss";
23
+ import Label from "@helsenorge/designsystem-react/components/Label";
24
+ import X from "@helsenorge/designsystem-react/components/Icons/X";
25
+ import styles from "./DatePicker.module.scss";
26
+ import * as ReactDOM from "react-dom";
27
+ import styles$1 from "./Unsafe_DateAndTime.module.scss";
28
+ const CustomPreviousButton = (props) => {
29
+ const buttonRef = React.useRef(null);
30
+ const { isHovered } = usePseudoClasses(buttonRef);
31
+ const isMobile = useIsMobileBreakpoint();
32
+ return /* @__PURE__ */ jsx("button", {
33
+ ...props,
34
+ ref: buttonRef,
35
+ className: classNames(props.className, customstyles["custom_nav_button"]),
36
+ children: /* @__PURE__ */ jsx("div", {
37
+ className: customstyles["custom_nav_button__circle"],
38
+ children: /* @__PURE__ */ jsx(Icon, {
39
+ svgIcon: ChevronLeft,
40
+ isHovered: !props.disabled && !props["aria-disabled"] && isHovered,
41
+ className: classNames(customstyles["custom_chevron"]),
42
+ size: isMobile ? IconSize$1.XXSmall : IconSize$1.XSmall
43
+ })
44
+ })
45
+ });
46
+ };
47
+ const CustomNextButton = (props) => {
48
+ const buttonRef = React.useRef(null);
49
+ const { isHovered } = usePseudoClasses(buttonRef);
50
+ const isMobile = useIsMobileBreakpoint();
51
+ return /* @__PURE__ */ jsx("button", {
52
+ ...props,
53
+ ref: buttonRef,
54
+ className: classNames(props.className, customstyles["custom_nav_button"]),
55
+ children: /* @__PURE__ */ jsx("div", {
56
+ className: customstyles["custom_nav_button__circle"],
57
+ children: /* @__PURE__ */ jsx(Icon, {
58
+ svgIcon: ChevronRight,
59
+ isHovered: !props.disabled && !props["aria-disabled"] && isHovered,
60
+ className: classNames(customstyles["custom_chevron"]),
61
+ size: isMobile ? IconSize$1.XXSmall : IconSize$1.XSmall
62
+ })
63
+ })
64
+ });
65
+ };
66
+ const CustomDropdown = (props) => {
67
+ const { options, classNames: rdpClassnameProp, ...dropdownProps } = props;
68
+ const { components, classNames: rdpClassnames } = useDayPicker();
69
+ const ref = useRef(null);
70
+ const { isHovered } = usePseudoClasses(ref);
71
+ const selectedOption = options?.find(({ value }) => value === dropdownProps.value);
72
+ return /* @__PURE__ */ jsxs("span", {
73
+ "data-disabled": dropdownProps.disabled,
74
+ className: classNames(rdpClassnames["dropdown_root"], customstyles["dropdown_root_custom"]),
75
+ ref,
76
+ children: [/* @__PURE__ */ jsx(components.Select, {
77
+ ...dropdownProps,
78
+ className: classNames(rdpClassnames["dropdown"]),
79
+ children: options?.map(({ value, label, disabled }) => /* @__PURE__ */ jsx(components.Option, {
80
+ value,
81
+ disabled,
82
+ children: label
83
+ }, value))
84
+ }), /* @__PURE__ */ jsxs("span", {
85
+ className: classNames(rdpClassnames["caption_label"], customstyles["dropdown_container"]),
86
+ "aria-hidden": true,
87
+ children: [/* @__PURE__ */ jsx("span", {
88
+ className: customstyles["dropdown_label"],
89
+ children: selectedOption?.label
90
+ }), /* @__PURE__ */ jsx(Icon, {
91
+ svgIcon: ChevronDown,
92
+ isHovered,
93
+ size: IconSize$1.XSmall,
94
+ className: customstyles["dropdown_chevron"]
95
+ })]
96
+ })]
97
+ });
98
+ };
99
+ const CustomCaptionLabel = (props) => {
100
+ const { classNames: rdpClassnames } = useDayPicker();
101
+ return /* @__PURE__ */ jsx(CaptionLabel, {
102
+ ...props,
103
+ className: classNames(rdpClassnames["caption_label"], customstyles["custom_caption-label"])
104
+ });
105
+ };
106
+ var HN_Designsystem_Unsafe_DatePicker_nb_NO_default = {
107
+ dateButtonAriaLabel: "Åpne datovelger",
108
+ dayButtonBase: "{date}",
109
+ dayButtonToday: "I dag, {date}",
110
+ dayButtonSelected: "{date} valgt",
111
+ nextMonth: "Neste måned",
112
+ previousMonth: "Forrige måned",
113
+ monthDropdown: "Velg måned",
114
+ yearDropdown: "Velg år",
115
+ goToToday: "Gå til i dag",
116
+ loadingText: "Henter info. Vennligst vent.",
117
+ dayFormatPlaceholder: "dd",
118
+ monthFormatPlaceholder: "mm",
119
+ yearFormatPlaceholder: "åååå",
120
+ calendarButtonAriaLabel: "Åpne datovelger",
121
+ validateDefaultMessageYear: "År må være et tall med 4 siffer",
122
+ validateDefaultMessageMonth: "Måned må være et tall mellom 01 og 12",
123
+ validateDefaultMessageDay: "Dag må være et tall mellom 01 og 31",
124
+ clearButtonAriaLabel: "Nullstill dato",
125
+ ariaLabelInputDay: "Dag",
126
+ ariaLabelInputMonth: "Måned",
127
+ ariaLabelInputYear: "År",
128
+ validateDefaultMessageHour: "Time må være et tall mellom 00 og 23",
129
+ validateDefaultMessageMinute: "Minutt må være et tall mellom 00 og 59",
130
+ hourFormatPlaceholder: "tt",
131
+ minuteFormatPlaceholder: "mm",
132
+ ariaLabelInputHour: "Time",
133
+ ariaLabelInputMinute: "Minutt"
134
+ };
135
+ const getResources = (language) => {
136
+ switch (language) {
137
+ case LanguageLocales.NORWEGIAN:
138
+ default: return HN_Designsystem_Unsafe_DatePicker_nb_NO_default;
139
+ }
140
+ };
141
+ var BaseDayPicker = (props) => {
142
+ const { selectedDate, onDateChange, isLoading, modifiers, showGoToTodayButton = false, footer, resources, localeForCalendar = nb, labelsForCalendar, ...rdpProps } = props;
143
+ const { language } = useLanguage(LanguageLocales.NORWEGIAN);
144
+ const mergedResources = {
145
+ ...getResources(language),
146
+ ...resources
147
+ };
148
+ const customLocale = {
149
+ ...localeForCalendar,
150
+ localize: {
151
+ ...localeForCalendar.localize,
152
+ month: (n, options) => localeForCalendar.localize.month(n, {
153
+ ...options,
154
+ width: rdpProps.captionLayout === "dropdown" ? "abbreviated" : "wide"
155
+ })
156
+ }
157
+ };
158
+ const datePickerClassNames = {
159
+ ...reactdaypickerstyles,
160
+ ...customstyles,
161
+ root: classNames(reactdaypickerstyles.root, customstyles["root_override"]),
162
+ day: classNames(reactdaypickerstyles.day, customstyles["date--default"]),
163
+ month_caption: classNames(reactdaypickerstyles["month_caption"], customstyles["custom_month_caption"])
164
+ };
165
+ const [selected, setSelected] = useState(selectedDate);
166
+ const [month, setMonth$1] = useState(selectedDate || /* @__PURE__ */ new Date());
167
+ React.useEffect(() => {
168
+ setSelected(selectedDate);
169
+ }, [selectedDate]);
170
+ const handleSelect = (date) => {
171
+ if (date && selected && isSameDay(date, selected)) {
172
+ setSelected(void 0);
173
+ onDateChange?.(void 0);
174
+ return;
175
+ }
176
+ setSelected(date);
177
+ onDateChange?.(date);
178
+ };
179
+ const modifiersExtended = { ...modifiers };
180
+ const handleDayButtonClick = (day, modifiers$1) => {
181
+ if (modifiers$1.selected) {
182
+ setSelected(void 0);
183
+ onDateChange?.(void 0);
184
+ } else if (!modifiers$1.disabled) {
185
+ setSelected(day.date);
186
+ onDateChange?.(day.date);
187
+ }
188
+ };
189
+ return /* @__PURE__ */ jsx(DayPicker, {
190
+ ...rdpProps,
191
+ navLayout: "around",
192
+ mode: "single",
193
+ selected,
194
+ month,
195
+ onMonthChange: setMonth$1,
196
+ onSelect: handleSelect,
197
+ classNames: datePickerClassNames,
198
+ locale: customLocale,
199
+ modifiers: modifiersExtended,
200
+ labels: labelsForCalendar,
201
+ footer: showGoToTodayButton ? /* @__PURE__ */ jsxs("div", {
202
+ className: classNames(customstyles["datepicker-footer"], customstyles["datepicker-footer--with-today-button"]),
203
+ children: [/* @__PURE__ */ jsx(Button, {
204
+ variant: "borderless",
205
+ onClick: () => {
206
+ setMonth$1(/* @__PURE__ */ new Date());
207
+ },
208
+ children: mergedResources.goToToday
209
+ }), footer]
210
+ }) : footer && /* @__PURE__ */ jsx("div", {
211
+ className: classNames(customstyles["datepicker-footer"]),
212
+ children: footer
213
+ }),
214
+ modifiersClassNames: {
215
+ emphasized: customstyles["date--emphasized"],
216
+ disabled: customstyles["date--disabled"],
217
+ today: customstyles["date--today"],
218
+ selected: customstyles["date--selected"],
219
+ partiallyBooked: customstyles["date--partial"],
220
+ fullyBooked: customstyles["date--fully"]
221
+ },
222
+ components: {
223
+ DayButton: (props$1) => {
224
+ const { day, modifiers: modifiers$1, ...buttonProps } = props$1;
225
+ const { classNames: rdpClassnames } = useDayPicker();
226
+ const buttonRef = React.useRef(null);
227
+ const handleClick = () => {
228
+ handleDayButtonClick(day, modifiers$1);
229
+ };
230
+ React.useEffect(() => {
231
+ if (modifiers$1.focused) buttonRef.current?.focus();
232
+ }, [modifiers$1.focused]);
233
+ return /* @__PURE__ */ jsx(Fragment, { children: /* @__PURE__ */ jsx("button", {
234
+ ...buttonProps,
235
+ disabled: buttonProps.disabled,
236
+ className: classNames(rdpClassnames["day_button"], customstyles["custom_day_button"]),
237
+ ref: buttonRef,
238
+ onClick: handleClick
239
+ }) });
240
+ },
241
+ NextMonthButton: (props$1) => /* @__PURE__ */ jsx(CustomNextButton, { ...props$1 }),
242
+ PreviousMonthButton: (props$1) => /* @__PURE__ */ jsx(CustomPreviousButton, { ...props$1 }),
243
+ MonthGrid: isLoading ? (props$1) => /* @__PURE__ */ jsxs("div", {
244
+ style: { position: "relative" },
245
+ children: [/* @__PURE__ */ jsx(MonthGrid, { ...props$1 }), /* @__PURE__ */ jsxs("div", {
246
+ className: customstyles["loading-overlay"],
247
+ children: [/* @__PURE__ */ jsx(Loader, {
248
+ size: "small",
249
+ color: "blueberry"
250
+ }), /* @__PURE__ */ jsx("p", {
251
+ style: { whiteSpace: "pre-line" },
252
+ "aria-live": "polite",
253
+ children: mergedResources.loadingText
254
+ })]
255
+ })]
256
+ }) : MonthGrid,
257
+ Dropdown: CustomDropdown,
258
+ CaptionLabel: CustomCaptionLabel
259
+ }
260
+ });
261
+ };
262
+ var BaseDayPicker_default = BaseDayPicker;
263
+ var TimeInputInternal = ({ value, onChange, onBlur, id, setErrorText, resources, withClearButton, ["aria-describedby"]: ariaDescribedBy, ["aria-labelledby"]: ariaLabelledBy }) => {
264
+ const [errorTextHh, setErrorTextHh] = useState("");
265
+ const [errorTextMm, setErrorTextMm] = useState("");
266
+ const [hh, setHh] = useState("");
267
+ const [mm, setMm] = useState("");
268
+ const hasValue = hh !== "" || mm !== "";
269
+ const hhRef = useRef(null);
270
+ const mmRef = useRef(null);
271
+ const inputRefs = [hhRef, mmRef];
272
+ const clearButtonRef = useRef(null);
273
+ const [isClearButtonFocused, setIsClearButtonFocused] = useState(false);
274
+ useEffect(() => {
275
+ if (!value || value === "") return;
276
+ const match = value.match(/^(\d{2}):(\d{2})$/);
277
+ if (match) {
278
+ const [_, newDd, newMm] = match;
279
+ if (hh !== newDd) setHh(newDd);
280
+ if (mm !== newMm) setMm(newMm);
281
+ }
282
+ }, [value]);
283
+ const combinedValue = hh && mm ? `${hh}:${mm}` : "";
284
+ useEffect(() => {
285
+ if (onChange) onChange(combinedValue);
286
+ }, [combinedValue]);
287
+ const validateHh = (newHh) => {
288
+ if (newHh === "") {
289
+ setErrorTextHh("");
290
+ return true;
291
+ }
292
+ if (/^\d{0,2}$/.test(newHh)) {
293
+ const hourNum = parseInt(newHh, 10);
294
+ if (hourNum < 0 || hourNum >= 24) {
295
+ setErrorTextHh(resources?.validateDefaultMessageHour || "Time må være et tall mellom 00 og 23");
296
+ return false;
297
+ } else {
298
+ setErrorTextHh("");
299
+ return true;
300
+ }
301
+ } else {
302
+ setErrorTextHh(resources?.validateDefaultMessageHour || "Time må være et tall mellom 00 og 23");
303
+ return false;
304
+ }
305
+ };
306
+ const handleHhChange = (e) => {
307
+ const newHh = e.target.value;
308
+ setHh(newHh);
309
+ if (validateHh(newHh)) {
310
+ if (newHh.length === 2) mmRef.current?.focus();
311
+ }
312
+ };
313
+ const validateMm = (newMm) => {
314
+ if (newMm === "") {
315
+ setErrorTextMm("");
316
+ return true;
317
+ }
318
+ if (/^\d{0,2}$/.test(newMm)) {
319
+ const minNum = parseInt(newMm, 10);
320
+ if (minNum < 0 || minNum >= 60) {
321
+ setErrorTextMm(resources?.validateDefaultMessageMinute || "Minutter må være et tall mellom 00 og 59");
322
+ return false;
323
+ } else {
324
+ setErrorTextMm("");
325
+ return true;
326
+ }
327
+ } else {
328
+ setErrorTextMm(resources?.validateDefaultMessageMinute || "Minutter må være et tall mellom 00 og 59");
329
+ return false;
330
+ }
331
+ };
332
+ const handleMmChange = (e) => {
333
+ const newMm = e.target.value;
334
+ setMm(newMm);
335
+ validateMm(newMm);
336
+ };
337
+ const handleBlurOnSegment = () => {
338
+ validateHh(hh);
339
+ validateMm(mm);
340
+ };
341
+ useEffect(() => {
342
+ const combinedErrors = [errorTextHh, errorTextMm].filter((err) => err !== "").join(". ");
343
+ if (setErrorText) setErrorText(combinedErrors);
344
+ }, [errorTextHh, errorTextMm]);
345
+ const segmentClass = styles["date-segment"];
346
+ const errorClass = styles["date-segment--error"];
347
+ const hourSegmentClassNames = classNames(segmentClass, errorTextHh && errorClass);
348
+ const minuteSegmentClassNames = classNames(segmentClass, errorTextMm && errorClass);
349
+ const handleGroupBlur = () => {
350
+ setTimeout(() => {
351
+ if (!inputRefs.some((ref) => ref.current && ref.current === document.activeElement)) onBlur?.(combinedValue);
352
+ }, 0);
353
+ };
354
+ const handleGroupClick = () => {
355
+ if (hhRef.current && document.activeElement !== hhRef.current && mmRef.current && document.activeElement !== mmRef.current && document.activeElement !== clearButtonRef.current) {
356
+ if (hh === "") hhRef.current.focus();
357
+ else if (mm === "") mmRef.current.focus();
358
+ }
359
+ };
360
+ const handleClear = () => {
361
+ setHh("");
362
+ setMm("");
363
+ setErrorTextHh("");
364
+ setErrorTextMm("");
365
+ if (onChange) onChange("");
366
+ hhRef.current?.focus();
367
+ };
368
+ const moveFocusLeft = () => {
369
+ const activeElement$1 = document.activeElement;
370
+ if (!activeElement$1) return;
371
+ if (mmRef.current === activeElement$1) {
372
+ if (activeElement$1.selectionStart === 0 && activeElement$1.selectionEnd === 0) setTimeout(() => {
373
+ hhRef.current?.focus();
374
+ }, 0);
375
+ }
376
+ };
377
+ const moveFocusRight = () => {
378
+ const activeElement$1 = document.activeElement;
379
+ if (!activeElement$1) return;
380
+ if (hhRef.current === activeElement$1) {
381
+ if (activeElement$1.selectionStart === activeElement$1.value.length && activeElement$1.selectionEnd === activeElement$1.value.length) setTimeout(() => {
382
+ mmRef.current?.focus();
383
+ }, 0);
384
+ }
385
+ };
386
+ const moveFocusOnBackspaceInEmptyField = () => {
387
+ if (mmRef.current === document.activeElement && mm === "") setTimeout(() => {
388
+ hhRef.current?.focus();
389
+ }, 0);
390
+ };
391
+ useKeyboardEvent(mmRef, moveFocusOnBackspaceInEmptyField, [KeyboardEventKey.Backspace]);
392
+ useKeyboardEvent(mmRef, moveFocusLeft, [KeyboardEventKey.ArrowLeft]);
393
+ useKeyboardEvent(hhRef, moveFocusRight, [KeyboardEventKey.ArrowRight]);
394
+ return /* @__PURE__ */ jsxs("div", {
395
+ role: "group",
396
+ className: classNames(styles["date-picker"], styles["date-picker--time"], {
397
+ [styles["date-picker--time--with-clear-button"]]: withClearButton,
398
+ [styles["date-picker--clear-button-focused"]]: isClearButtonFocused
399
+ }),
400
+ id,
401
+ "aria-labelledby": ariaLabelledBy,
402
+ "aria-describedby": ariaDescribedBy,
403
+ onBlurCapture: handleGroupBlur,
404
+ onClickCapture: handleGroupClick,
405
+ children: [/* @__PURE__ */ jsxs("span", {
406
+ className: styles["date-picker__inputs"],
407
+ children: [
408
+ /* @__PURE__ */ jsx("input", {
409
+ ref: hhRef,
410
+ type: "text",
411
+ enterKeyHint: "next",
412
+ inputMode: "numeric",
413
+ pattern: "[0-9]*",
414
+ maxLength: 2,
415
+ value: hh,
416
+ onChange: handleHhChange,
417
+ onBlur: handleBlurOnSegment,
418
+ placeholder: resources?.hourFormatPlaceholder || "tt",
419
+ "aria-label": resources?.ariaLabelInputHour || "Time",
420
+ className: hourSegmentClassNames
421
+ }),
422
+ /* @__PURE__ */ jsx("span", {
423
+ "aria-hidden": true,
424
+ children: ":"
425
+ }),
426
+ /* @__PURE__ */ jsx("input", {
427
+ ref: mmRef,
428
+ type: "text",
429
+ enterKeyHint: "next",
430
+ inputMode: "numeric",
431
+ pattern: "[0-9]*",
432
+ maxLength: 2,
433
+ value: mm,
434
+ onChange: handleMmChange,
435
+ onBlur: handleBlurOnSegment,
436
+ placeholder: resources?.minuteFormatPlaceholder || "mm",
437
+ "aria-label": resources?.ariaLabelInputMinute || "Minutt",
438
+ className: minuteSegmentClassNames
439
+ })
440
+ ]
441
+ }), withClearButton && (hasValue ? /* @__PURE__ */ jsx("button", {
442
+ type: "button",
443
+ onClick: handleClear,
444
+ onFocus: () => setIsClearButtonFocused(true),
445
+ onBlur: () => setIsClearButtonFocused(false),
446
+ ref: clearButtonRef,
447
+ className: styles["clear-button"],
448
+ "aria-label": resources?.clearButtonAriaLabel || "Nullstill dato",
449
+ children: /* @__PURE__ */ jsx(Icon, {
450
+ svgIcon: X,
451
+ size: IconSize.XXSmall
452
+ })
453
+ }) : /* @__PURE__ */ jsx("div", { className: styles["clear-button__placeholder"] }))]
454
+ });
455
+ };
456
+ var TimeInputInternal_default = TimeInputInternal;
457
+ var Unsafe_TimeInput = ({ value, onChange, onBlur, errorText, id, label, resources, withClearButton = true, ["aria-describedby"]: ariaDescribedBy, ["aria-labelledby"]: ariaLabelledBy }) => {
458
+ const [softErrorText, setSoftErrorText] = useState("");
459
+ const labelGivenAsPropIsValidLabelComponent = isComponent(label, Label);
460
+ const legend = label && labelGivenAsPropIsValidLabelComponent ? cloneElement(label, {
461
+ htmlMarkup: "legend",
462
+ labelId: label.props.labelId || "date-legend"
463
+ }) : null;
464
+ const legendId = labelGivenAsPropIsValidLabelComponent && label.props.labelId ? label.props.labelId : "date-legend";
465
+ return /* @__PURE__ */ jsx(ErrorWrapper, {
466
+ errorText,
467
+ children: /* @__PURE__ */ jsxs("fieldset", {
468
+ className: styles["date-field"],
469
+ "aria-labelledby": legendId,
470
+ children: [
471
+ legend,
472
+ /* @__PURE__ */ jsx(TimeInputInternal_default, {
473
+ id,
474
+ value,
475
+ onChange,
476
+ withClearButton,
477
+ resources,
478
+ "aria-labelledby": ariaLabelledBy,
479
+ "aria-describedby": ariaDescribedBy,
480
+ onBlur,
481
+ setErrorText: setSoftErrorText
482
+ }),
483
+ /* @__PURE__ */ jsx("div", {
484
+ className: styles["date-field__soft-error-text"],
485
+ role: "status",
486
+ children: softErrorText
487
+ })
488
+ ]
489
+ })
490
+ });
491
+ };
492
+ var Unsafe_TimeInput_default = Unsafe_TimeInput;
493
+ function hasWindow() {
494
+ return typeof window !== "undefined";
495
+ }
496
+ function getNodeName(node) {
497
+ if (isNode(node)) return (node.nodeName || "").toLowerCase();
498
+ return "#document";
499
+ }
500
+ function getWindow(node) {
501
+ var _node$ownerDocument;
502
+ return (node == null || (_node$ownerDocument = node.ownerDocument) == null ? void 0 : _node$ownerDocument.defaultView) || window;
503
+ }
504
+ function getDocumentElement(node) {
505
+ var _ref;
506
+ return (_ref = (isNode(node) ? node.ownerDocument : node.document) || window.document) == null ? void 0 : _ref.documentElement;
507
+ }
508
+ function isNode(value) {
509
+ if (!hasWindow()) return false;
510
+ return value instanceof Node || value instanceof getWindow(value).Node;
511
+ }
512
+ function isElement(value) {
513
+ if (!hasWindow()) return false;
514
+ return value instanceof Element || value instanceof getWindow(value).Element;
515
+ }
516
+ function isHTMLElement(value) {
517
+ if (!hasWindow()) return false;
518
+ return value instanceof HTMLElement || value instanceof getWindow(value).HTMLElement;
519
+ }
520
+ function isShadowRoot(value) {
521
+ if (!hasWindow() || typeof ShadowRoot === "undefined") return false;
522
+ return value instanceof ShadowRoot || value instanceof getWindow(value).ShadowRoot;
523
+ }
524
+ var invalidOverflowDisplayValues = /* @__PURE__ */ new Set(["inline", "contents"]);
525
+ function isOverflowElement(element) {
526
+ const { overflow, overflowX, overflowY, display } = getComputedStyle$1(element);
527
+ return /auto|scroll|overlay|hidden|clip/.test(overflow + overflowY + overflowX) && !invalidOverflowDisplayValues.has(display);
528
+ }
529
+ var tableElements = /* @__PURE__ */ new Set([
530
+ "table",
531
+ "td",
532
+ "th"
533
+ ]);
534
+ function isTableElement(element) {
535
+ return tableElements.has(getNodeName(element));
536
+ }
537
+ var topLayerSelectors = [":popover-open", ":modal"];
538
+ function isTopLayer(element) {
539
+ return topLayerSelectors.some((selector) => {
540
+ try {
541
+ return element.matches(selector);
542
+ } catch (_e) {
543
+ return false;
544
+ }
545
+ });
546
+ }
547
+ var transformProperties = [
548
+ "transform",
549
+ "translate",
550
+ "scale",
551
+ "rotate",
552
+ "perspective"
553
+ ];
554
+ var willChangeValues = [
555
+ "transform",
556
+ "translate",
557
+ "scale",
558
+ "rotate",
559
+ "perspective",
560
+ "filter"
561
+ ];
562
+ var containValues = [
563
+ "paint",
564
+ "layout",
565
+ "strict",
566
+ "content"
567
+ ];
568
+ function isContainingBlock(elementOrCss) {
569
+ const webkit = isWebKit();
570
+ const css = isElement(elementOrCss) ? getComputedStyle$1(elementOrCss) : elementOrCss;
571
+ return transformProperties.some((value) => css[value] ? css[value] !== "none" : false) || (css.containerType ? css.containerType !== "normal" : false) || !webkit && (css.backdropFilter ? css.backdropFilter !== "none" : false) || !webkit && (css.filter ? css.filter !== "none" : false) || willChangeValues.some((value) => (css.willChange || "").includes(value)) || containValues.some((value) => (css.contain || "").includes(value));
572
+ }
573
+ function getContainingBlock(element) {
574
+ let currentNode = getParentNode(element);
575
+ while (isHTMLElement(currentNode) && !isLastTraversableNode(currentNode)) {
576
+ if (isContainingBlock(currentNode)) return currentNode;
577
+ else if (isTopLayer(currentNode)) return null;
578
+ currentNode = getParentNode(currentNode);
579
+ }
580
+ return null;
581
+ }
582
+ function isWebKit() {
583
+ if (typeof CSS === "undefined" || !CSS.supports) return false;
584
+ return CSS.supports("-webkit-backdrop-filter", "none");
585
+ }
586
+ var lastTraversableNodeNames = /* @__PURE__ */ new Set([
587
+ "html",
588
+ "body",
589
+ "#document"
590
+ ]);
591
+ function isLastTraversableNode(node) {
592
+ return lastTraversableNodeNames.has(getNodeName(node));
593
+ }
594
+ function getComputedStyle$1(element) {
595
+ return getWindow(element).getComputedStyle(element);
596
+ }
597
+ function getNodeScroll(element) {
598
+ if (isElement(element)) return {
599
+ scrollLeft: element.scrollLeft,
600
+ scrollTop: element.scrollTop
601
+ };
602
+ return {
603
+ scrollLeft: element.scrollX,
604
+ scrollTop: element.scrollY
605
+ };
606
+ }
607
+ function getParentNode(node) {
608
+ if (getNodeName(node) === "html") return node;
609
+ const result = node.assignedSlot || node.parentNode || isShadowRoot(node) && node.host || getDocumentElement(node);
610
+ return isShadowRoot(result) ? result.host : result;
611
+ }
612
+ function getNearestOverflowAncestor(node) {
613
+ const parentNode = getParentNode(node);
614
+ if (isLastTraversableNode(parentNode)) return node.ownerDocument ? node.ownerDocument.body : node.body;
615
+ if (isHTMLElement(parentNode) && isOverflowElement(parentNode)) return parentNode;
616
+ return getNearestOverflowAncestor(parentNode);
617
+ }
618
+ function getOverflowAncestors(node, list, traverseIframes) {
619
+ var _node$ownerDocument2;
620
+ if (list === void 0) list = [];
621
+ if (traverseIframes === void 0) traverseIframes = true;
622
+ const scrollableAncestor = getNearestOverflowAncestor(node);
623
+ const isBody = scrollableAncestor === ((_node$ownerDocument2 = node.ownerDocument) == null ? void 0 : _node$ownerDocument2.body);
624
+ const win = getWindow(scrollableAncestor);
625
+ if (isBody) {
626
+ const frameElement = getFrameElement(win);
627
+ return list.concat(win, win.visualViewport || [], isOverflowElement(scrollableAncestor) ? scrollableAncestor : [], frameElement && traverseIframes ? getOverflowAncestors(frameElement) : []);
628
+ }
629
+ return list.concat(scrollableAncestor, getOverflowAncestors(scrollableAncestor, [], traverseIframes));
630
+ }
631
+ function getFrameElement(win) {
632
+ return win.parent && Object.getPrototypeOf(win.parent) ? win.frameElement : null;
633
+ }
634
+ var min$1 = Math.min;
635
+ var max$1 = Math.max;
636
+ var round = Math.round;
637
+ var floor = Math.floor;
638
+ var createCoords = (v) => ({
639
+ x: v,
640
+ y: v
641
+ });
642
+ function clamp(start, value, end) {
643
+ return max$1(start, min$1(value, end));
644
+ }
645
+ function evaluate(value, param) {
646
+ return typeof value === "function" ? value(param) : value;
647
+ }
648
+ function getSide(placement) {
649
+ return placement.split("-")[0];
650
+ }
651
+ function getAlignment(placement) {
652
+ return placement.split("-")[1];
653
+ }
654
+ function getOppositeAxis(axis) {
655
+ return axis === "x" ? "y" : "x";
656
+ }
657
+ function getAxisLength(axis) {
658
+ return axis === "y" ? "height" : "width";
659
+ }
660
+ var yAxisSides = /* @__PURE__ */ new Set(["top", "bottom"]);
661
+ function getSideAxis(placement) {
662
+ return yAxisSides.has(getSide(placement)) ? "y" : "x";
663
+ }
664
+ function getAlignmentAxis(placement) {
665
+ return getOppositeAxis(getSideAxis(placement));
666
+ }
667
+ function expandPaddingObject(padding) {
668
+ return {
669
+ top: 0,
670
+ right: 0,
671
+ bottom: 0,
672
+ left: 0,
673
+ ...padding
674
+ };
675
+ }
676
+ function getPaddingObject(padding) {
677
+ return typeof padding !== "number" ? expandPaddingObject(padding) : {
678
+ top: padding,
679
+ right: padding,
680
+ bottom: padding,
681
+ left: padding
682
+ };
683
+ }
684
+ function rectToClientRect(rect) {
685
+ const { x, y, width, height } = rect;
686
+ return {
687
+ width,
688
+ height,
689
+ top: y,
690
+ left: x,
691
+ right: x + width,
692
+ bottom: y + height,
693
+ x,
694
+ y
695
+ };
696
+ }
697
+ var candidateSelector = /* @__PURE__ */ [
698
+ "input:not([inert]):not([inert] *)",
699
+ "select:not([inert]):not([inert] *)",
700
+ "textarea:not([inert]):not([inert] *)",
701
+ "a[href]:not([inert]):not([inert] *)",
702
+ "button:not([inert]):not([inert] *)",
703
+ "[tabindex]:not(slot):not([inert]):not([inert] *)",
704
+ "audio[controls]:not([inert]):not([inert] *)",
705
+ "video[controls]:not([inert]):not([inert] *)",
706
+ "[contenteditable]:not([contenteditable=\"false\"]):not([inert]):not([inert] *)",
707
+ "details>summary:first-of-type:not([inert]):not([inert] *)",
708
+ "details:not([inert]):not([inert] *)"
709
+ ].join(",");
710
+ var NoElement = typeof Element === "undefined";
711
+ var matches = NoElement ? function() {} : Element.prototype.matches || Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector;
712
+ var getRootNode = !NoElement && Element.prototype.getRootNode ? function(element) {
713
+ var _element$getRootNode;
714
+ return element === null || element === void 0 ? void 0 : (_element$getRootNode = element.getRootNode) === null || _element$getRootNode === void 0 ? void 0 : _element$getRootNode.call(element);
715
+ } : function(element) {
716
+ return element === null || element === void 0 ? void 0 : element.ownerDocument;
717
+ };
718
+ var _isInert = function isInert(node, lookUp) {
719
+ var _node$getAttribute;
720
+ if (lookUp === void 0) lookUp = true;
721
+ var inertAtt = node === null || node === void 0 ? void 0 : (_node$getAttribute = node.getAttribute) === null || _node$getAttribute === void 0 ? void 0 : _node$getAttribute.call(node, "inert");
722
+ return inertAtt === "" || inertAtt === "true" || lookUp && node && (typeof node.closest === "function" ? node.closest("[inert]") : _isInert(node.parentNode));
723
+ };
724
+ var isContentEditable = function isContentEditable$1(node) {
725
+ var _node$getAttribute2;
726
+ var attValue = node === null || node === void 0 ? void 0 : (_node$getAttribute2 = node.getAttribute) === null || _node$getAttribute2 === void 0 ? void 0 : _node$getAttribute2.call(node, "contenteditable");
727
+ return attValue === "" || attValue === "true";
728
+ };
729
+ var getCandidates = function getCandidates$1(el, includeContainer, filter) {
730
+ if (_isInert(el)) return [];
731
+ var candidates = Array.prototype.slice.apply(el.querySelectorAll(candidateSelector));
732
+ if (includeContainer && matches.call(el, candidateSelector)) candidates.unshift(el);
733
+ candidates = candidates.filter(filter);
734
+ return candidates;
735
+ };
736
+ var _getCandidatesIteratively = function getCandidatesIteratively(elements, includeContainer, options) {
737
+ var candidates = [];
738
+ var elementsToCheck = Array.from(elements);
739
+ while (elementsToCheck.length) {
740
+ var element = elementsToCheck.shift();
741
+ if (_isInert(element, false)) continue;
742
+ if (element.tagName === "SLOT") {
743
+ var assigned = element.assignedElements();
744
+ var nestedCandidates = _getCandidatesIteratively(assigned.length ? assigned : element.children, true, options);
745
+ if (options.flatten) candidates.push.apply(candidates, nestedCandidates);
746
+ else candidates.push({
747
+ scopeParent: element,
748
+ candidates: nestedCandidates
749
+ });
750
+ } else {
751
+ if (matches.call(element, candidateSelector) && options.filter(element) && (includeContainer || !elements.includes(element))) candidates.push(element);
752
+ var shadowRoot = element.shadowRoot || typeof options.getShadowRoot === "function" && options.getShadowRoot(element);
753
+ var validShadowRoot = !_isInert(shadowRoot, false) && (!options.shadowRootFilter || options.shadowRootFilter(element));
754
+ if (shadowRoot && validShadowRoot) {
755
+ var _nestedCandidates = _getCandidatesIteratively(shadowRoot === true ? element.children : shadowRoot.children, true, options);
756
+ if (options.flatten) candidates.push.apply(candidates, _nestedCandidates);
757
+ else candidates.push({
758
+ scopeParent: element,
759
+ candidates: _nestedCandidates
760
+ });
761
+ } else elementsToCheck.unshift.apply(elementsToCheck, element.children);
762
+ }
763
+ }
764
+ return candidates;
765
+ };
766
+ var hasTabIndex = function hasTabIndex$1(node) {
767
+ return !isNaN(parseInt(node.getAttribute("tabindex"), 10));
768
+ };
769
+ var getTabIndex = function getTabIndex$1(node) {
770
+ if (!node) throw new Error("No node provided");
771
+ if (node.tabIndex < 0) {
772
+ if ((/^(AUDIO|VIDEO|DETAILS)$/.test(node.tagName) || isContentEditable(node)) && !hasTabIndex(node)) return 0;
773
+ }
774
+ return node.tabIndex;
775
+ };
776
+ var getSortOrderTabIndex = function getSortOrderTabIndex$1(node, isScope) {
777
+ var tabIndex = getTabIndex(node);
778
+ if (tabIndex < 0 && isScope && !hasTabIndex(node)) return 0;
779
+ return tabIndex;
780
+ };
781
+ var sortOrderedTabbables = function sortOrderedTabbables$1(a, b) {
782
+ return a.tabIndex === b.tabIndex ? a.documentOrder - b.documentOrder : a.tabIndex - b.tabIndex;
783
+ };
784
+ var isInput = function isInput$1(node) {
785
+ return node.tagName === "INPUT";
786
+ };
787
+ var isHiddenInput = function isHiddenInput$1(node) {
788
+ return isInput(node) && node.type === "hidden";
789
+ };
790
+ var isDetailsWithSummary = function isDetailsWithSummary$1(node) {
791
+ return node.tagName === "DETAILS" && Array.prototype.slice.apply(node.children).some(function(child) {
792
+ return child.tagName === "SUMMARY";
793
+ });
794
+ };
795
+ var getCheckedRadio = function getCheckedRadio$1(nodes, form) {
796
+ for (var i = 0; i < nodes.length; i++) if (nodes[i].checked && nodes[i].form === form) return nodes[i];
797
+ };
798
+ var isTabbableRadio = function isTabbableRadio$1(node) {
799
+ if (!node.name) return true;
800
+ var radioScope = node.form || getRootNode(node);
801
+ var queryRadios = function queryRadios$1(name) {
802
+ return radioScope.querySelectorAll("input[type=\"radio\"][name=\"" + name + "\"]");
803
+ };
804
+ var radioSet;
805
+ if (typeof window !== "undefined" && typeof window.CSS !== "undefined" && typeof window.CSS.escape === "function") radioSet = queryRadios(window.CSS.escape(node.name));
806
+ else try {
807
+ radioSet = queryRadios(node.name);
808
+ } catch (err) {
809
+ console.error("Looks like you have a radio button with a name attribute containing invalid CSS selector characters and need the CSS.escape polyfill: %s", err.message);
810
+ return false;
811
+ }
812
+ var checked = getCheckedRadio(radioSet, node.form);
813
+ return !checked || checked === node;
814
+ };
815
+ var isRadio = function isRadio$1(node) {
816
+ return isInput(node) && node.type === "radio";
817
+ };
818
+ var isNonTabbableRadio = function isNonTabbableRadio$1(node) {
819
+ return isRadio(node) && !isTabbableRadio(node);
820
+ };
821
+ var isNodeAttached = function isNodeAttached$1(node) {
822
+ var _nodeRoot;
823
+ var nodeRoot = node && getRootNode(node);
824
+ var nodeRootHost = (_nodeRoot = nodeRoot) === null || _nodeRoot === void 0 ? void 0 : _nodeRoot.host;
825
+ var attached = false;
826
+ if (nodeRoot && nodeRoot !== node) {
827
+ var _nodeRootHost, _nodeRootHost$ownerDo, _node$ownerDocument;
828
+ attached = !!((_nodeRootHost = nodeRootHost) !== null && _nodeRootHost !== void 0 && (_nodeRootHost$ownerDo = _nodeRootHost.ownerDocument) !== null && _nodeRootHost$ownerDo !== void 0 && _nodeRootHost$ownerDo.contains(nodeRootHost) || node !== null && node !== void 0 && (_node$ownerDocument = node.ownerDocument) !== null && _node$ownerDocument !== void 0 && _node$ownerDocument.contains(node));
829
+ while (!attached && nodeRootHost) {
830
+ var _nodeRoot2, _nodeRootHost2, _nodeRootHost2$ownerD;
831
+ nodeRoot = getRootNode(nodeRootHost);
832
+ nodeRootHost = (_nodeRoot2 = nodeRoot) === null || _nodeRoot2 === void 0 ? void 0 : _nodeRoot2.host;
833
+ attached = !!((_nodeRootHost2 = nodeRootHost) !== null && _nodeRootHost2 !== void 0 && (_nodeRootHost2$ownerD = _nodeRootHost2.ownerDocument) !== null && _nodeRootHost2$ownerD !== void 0 && _nodeRootHost2$ownerD.contains(nodeRootHost));
834
+ }
835
+ }
836
+ return attached;
837
+ };
838
+ var isZeroArea = function isZeroArea$1(node) {
839
+ var _node$getBoundingClie = node.getBoundingClientRect(), width = _node$getBoundingClie.width, height = _node$getBoundingClie.height;
840
+ return width === 0 && height === 0;
841
+ };
842
+ var isHidden = function isHidden$1(node, _ref) {
843
+ var displayCheck = _ref.displayCheck, getShadowRoot = _ref.getShadowRoot;
844
+ if (displayCheck === "full-native") {
845
+ if ("checkVisibility" in node) return !node.checkVisibility({
846
+ checkOpacity: false,
847
+ opacityProperty: false,
848
+ contentVisibilityAuto: true,
849
+ visibilityProperty: true,
850
+ checkVisibilityCSS: true
851
+ });
852
+ }
853
+ if (getComputedStyle(node).visibility === "hidden") return true;
854
+ var nodeUnderDetails = matches.call(node, "details>summary:first-of-type") ? node.parentElement : node;
855
+ if (matches.call(nodeUnderDetails, "details:not([open]) *")) return true;
856
+ if (!displayCheck || displayCheck === "full" || displayCheck === "full-native" || displayCheck === "legacy-full") {
857
+ if (typeof getShadowRoot === "function") {
858
+ var originalNode = node;
859
+ while (node) {
860
+ var parentElement = node.parentElement;
861
+ var rootNode = getRootNode(node);
862
+ if (parentElement && !parentElement.shadowRoot && getShadowRoot(parentElement) === true) return isZeroArea(node);
863
+ else if (node.assignedSlot) node = node.assignedSlot;
864
+ else if (!parentElement && rootNode !== node.ownerDocument) node = rootNode.host;
865
+ else node = parentElement;
866
+ }
867
+ node = originalNode;
868
+ }
869
+ if (isNodeAttached(node)) return !node.getClientRects().length;
870
+ if (displayCheck !== "legacy-full") return true;
871
+ } else if (displayCheck === "non-zero-area") return isZeroArea(node);
872
+ return false;
873
+ };
874
+ var isDisabledFromFieldset = function isDisabledFromFieldset$1(node) {
875
+ if (/^(INPUT|BUTTON|SELECT|TEXTAREA)$/.test(node.tagName)) {
876
+ var parentNode = node.parentElement;
877
+ while (parentNode) {
878
+ if (parentNode.tagName === "FIELDSET" && parentNode.disabled) {
879
+ for (var i = 0; i < parentNode.children.length; i++) {
880
+ var child = parentNode.children.item(i);
881
+ if (child.tagName === "LEGEND") return matches.call(parentNode, "fieldset[disabled] *") ? true : !child.contains(node);
882
+ }
883
+ return true;
884
+ }
885
+ parentNode = parentNode.parentElement;
886
+ }
887
+ }
888
+ return false;
889
+ };
890
+ var isNodeMatchingSelectorFocusable = function isNodeMatchingSelectorFocusable$1(options, node) {
891
+ if (node.disabled || isHiddenInput(node) || isHidden(node, options) || isDetailsWithSummary(node) || isDisabledFromFieldset(node)) return false;
892
+ return true;
893
+ };
894
+ var isNodeMatchingSelectorTabbable = function isNodeMatchingSelectorTabbable$1(options, node) {
895
+ if (isNonTabbableRadio(node) || getTabIndex(node) < 0 || !isNodeMatchingSelectorFocusable(options, node)) return false;
896
+ return true;
897
+ };
898
+ var isShadowRootTabbable = function isShadowRootTabbable$1(shadowHostNode) {
899
+ var tabIndex = parseInt(shadowHostNode.getAttribute("tabindex"), 10);
900
+ if (isNaN(tabIndex) || tabIndex >= 0) return true;
901
+ return false;
902
+ };
903
+ var _sortByOrder = function sortByOrder(candidates) {
904
+ var regularTabbables = [];
905
+ var orderedTabbables = [];
906
+ candidates.forEach(function(item, i) {
907
+ var isScope = !!item.scopeParent;
908
+ var element = isScope ? item.scopeParent : item;
909
+ var candidateTabindex = getSortOrderTabIndex(element, isScope);
910
+ var elements = isScope ? _sortByOrder(item.candidates) : element;
911
+ if (candidateTabindex === 0) isScope ? regularTabbables.push.apply(regularTabbables, elements) : regularTabbables.push(element);
912
+ else orderedTabbables.push({
913
+ documentOrder: i,
914
+ tabIndex: candidateTabindex,
915
+ item,
916
+ isScope,
917
+ content: elements
918
+ });
919
+ });
920
+ return orderedTabbables.sort(sortOrderedTabbables).reduce(function(acc, sortable) {
921
+ sortable.isScope ? acc.push.apply(acc, sortable.content) : acc.push(sortable.content);
922
+ return acc;
923
+ }, []).concat(regularTabbables);
924
+ };
925
+ var tabbable = function tabbable$1(container, options) {
926
+ options = options || {};
927
+ var candidates;
928
+ if (options.getShadowRoot) candidates = _getCandidatesIteratively([container], options.includeContainer, {
929
+ filter: isNodeMatchingSelectorTabbable.bind(null, options),
930
+ flatten: false,
931
+ getShadowRoot: options.getShadowRoot,
932
+ shadowRootFilter: isShadowRootTabbable
933
+ });
934
+ else candidates = getCandidates(container, options.includeContainer, isNodeMatchingSelectorTabbable.bind(null, options));
935
+ return _sortByOrder(candidates);
936
+ };
937
+ var focusable = function focusable$1(container, options) {
938
+ options = options || {};
939
+ var candidates;
940
+ if (options.getShadowRoot) candidates = _getCandidatesIteratively([container], options.includeContainer, {
941
+ filter: isNodeMatchingSelectorFocusable.bind(null, options),
942
+ flatten: true,
943
+ getShadowRoot: options.getShadowRoot
944
+ });
945
+ else candidates = getCandidates(container, options.includeContainer, isNodeMatchingSelectorFocusable.bind(null, options));
946
+ return candidates;
947
+ };
948
+ var isTabbable = function isTabbable$1(node, options) {
949
+ options = options || {};
950
+ if (!node) throw new Error("No node provided");
951
+ if (matches.call(node, candidateSelector) === false) return false;
952
+ return isNodeMatchingSelectorTabbable(options, node);
953
+ };
954
+ function getPlatform() {
955
+ const uaData = navigator.userAgentData;
956
+ if (uaData != null && uaData.platform) return uaData.platform;
957
+ return navigator.platform;
958
+ }
959
+ function getUserAgent() {
960
+ const uaData = navigator.userAgentData;
961
+ if (uaData && Array.isArray(uaData.brands)) return uaData.brands.map((_ref) => {
962
+ let { brand, version } = _ref;
963
+ return brand + "/" + version;
964
+ }).join(" ");
965
+ return navigator.userAgent;
966
+ }
967
+ function isSafari() {
968
+ return /apple/i.test(navigator.vendor);
969
+ }
970
+ function isAndroid() {
971
+ const re = /android/i;
972
+ return re.test(getPlatform()) || re.test(getUserAgent());
973
+ }
974
+ function isJSDOM() {
975
+ return getUserAgent().includes("jsdom/");
976
+ }
977
+ var FOCUSABLE_ATTRIBUTE$1 = "data-floating-ui-focusable";
978
+ var TYPEABLE_SELECTOR = "input:not([type='hidden']):not([disabled]),[contenteditable]:not([contenteditable='false']),textarea:not([disabled])";
979
+ function activeElement(doc) {
980
+ let activeElement$1 = doc.activeElement;
981
+ while (((_activeElement = activeElement$1) == null || (_activeElement = _activeElement.shadowRoot) == null ? void 0 : _activeElement.activeElement) != null) {
982
+ var _activeElement;
983
+ activeElement$1 = activeElement$1.shadowRoot.activeElement;
984
+ }
985
+ return activeElement$1;
986
+ }
987
+ function contains(parent, child) {
988
+ if (!parent || !child) return false;
989
+ const rootNode = child.getRootNode == null ? void 0 : child.getRootNode();
990
+ if (parent.contains(child)) return true;
991
+ if (rootNode && isShadowRoot(rootNode)) {
992
+ let next = child;
993
+ while (next) {
994
+ if (parent === next) return true;
995
+ next = next.parentNode || next.host;
996
+ }
997
+ }
998
+ return false;
999
+ }
1000
+ function getTarget(event) {
1001
+ if ("composedPath" in event) return event.composedPath()[0];
1002
+ return event.target;
1003
+ }
1004
+ function isEventTargetWithin(event, node) {
1005
+ if (node == null) return false;
1006
+ if ("composedPath" in event) return event.composedPath().includes(node);
1007
+ const e = event;
1008
+ return e.target != null && node.contains(e.target);
1009
+ }
1010
+ function isRootElement(element) {
1011
+ return element.matches("html,body");
1012
+ }
1013
+ function getDocument(node) {
1014
+ return (node == null ? void 0 : node.ownerDocument) || document;
1015
+ }
1016
+ function isTypeableElement(element) {
1017
+ return isHTMLElement(element) && element.matches(TYPEABLE_SELECTOR);
1018
+ }
1019
+ function isTypeableCombobox(element) {
1020
+ if (!element) return false;
1021
+ return element.getAttribute("role") === "combobox" && isTypeableElement(element);
1022
+ }
1023
+ function getFloatingFocusElement(floatingElement) {
1024
+ if (!floatingElement) return null;
1025
+ return floatingElement.hasAttribute(FOCUSABLE_ATTRIBUTE$1) ? floatingElement : floatingElement.querySelector("[" + FOCUSABLE_ATTRIBUTE$1 + "]") || floatingElement;
1026
+ }
1027
+ function getNodeChildren(nodes, id, onlyOpenChildren) {
1028
+ if (onlyOpenChildren === void 0) onlyOpenChildren = true;
1029
+ return nodes.filter((node) => {
1030
+ var _node$context;
1031
+ return node.parentId === id && (!onlyOpenChildren || ((_node$context = node.context) == null ? void 0 : _node$context.open));
1032
+ }).flatMap((child) => [child, ...getNodeChildren(nodes, child.id, onlyOpenChildren)]);
1033
+ }
1034
+ function getNodeAncestors(nodes, id) {
1035
+ var _nodes$find;
1036
+ let allAncestors = [];
1037
+ let currentParentId = (_nodes$find = nodes.find((node) => node.id === id)) == null ? void 0 : _nodes$find.parentId;
1038
+ while (currentParentId) {
1039
+ const currentNode = nodes.find((node) => node.id === currentParentId);
1040
+ currentParentId = currentNode == null ? void 0 : currentNode.parentId;
1041
+ if (currentNode) allAncestors = allAncestors.concat(currentNode);
1042
+ }
1043
+ return allAncestors;
1044
+ }
1045
+ function stopEvent(event) {
1046
+ event.preventDefault();
1047
+ event.stopPropagation();
1048
+ }
1049
+ function isReactEvent(event) {
1050
+ return "nativeEvent" in event;
1051
+ }
1052
+ function isVirtualClick(event) {
1053
+ if (event.mozInputSource === 0 && event.isTrusted) return true;
1054
+ if (isAndroid() && event.pointerType) return event.type === "click" && event.buttons === 1;
1055
+ return event.detail === 0 && !event.pointerType;
1056
+ }
1057
+ function isVirtualPointerEvent(event) {
1058
+ if (isJSDOM()) return false;
1059
+ return !isAndroid() && event.width === 0 && event.height === 0 || isAndroid() && event.width === 1 && event.height === 1 && event.pressure === 0 && event.detail === 0 && event.pointerType === "mouse" || event.width < 1 && event.height < 1 && event.pressure === 0 && event.detail === 0 && event.pointerType === "touch";
1060
+ }
1061
+ function isMouseLikePointerType(pointerType, strict) {
1062
+ const values = ["mouse", "pen"];
1063
+ if (!strict) values.push("", void 0);
1064
+ return values.includes(pointerType);
1065
+ }
1066
+ var index = typeof document !== "undefined" ? useLayoutEffect : function noop() {};
1067
+ var SafeReact$1 = { ...React$1 };
1068
+ function useLatestRef(value) {
1069
+ const ref = React$1.useRef(value);
1070
+ index(() => {
1071
+ ref.current = value;
1072
+ });
1073
+ return ref;
1074
+ }
1075
+ var useSafeInsertionEffect = SafeReact$1.useInsertionEffect || ((fn) => fn());
1076
+ function useEffectEvent(callback) {
1077
+ const ref = React$1.useRef(() => {
1078
+ if (process.env.NODE_ENV !== "production") throw new Error("Cannot call an event handler while rendering.");
1079
+ });
1080
+ useSafeInsertionEffect(() => {
1081
+ ref.current = callback;
1082
+ });
1083
+ return React$1.useCallback(function() {
1084
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key];
1085
+ return ref.current == null ? void 0 : ref.current(...args);
1086
+ }, []);
1087
+ }
1088
+ var getTabbableOptions = () => ({
1089
+ getShadowRoot: true,
1090
+ displayCheck: typeof ResizeObserver === "function" && ResizeObserver.toString().includes("[native code]") ? "full" : "none"
1091
+ });
1092
+ function getTabbableIn(container, dir) {
1093
+ const list = tabbable(container, getTabbableOptions());
1094
+ const len = list.length;
1095
+ if (len === 0) return;
1096
+ const active = activeElement(getDocument(container));
1097
+ const index$2 = list.indexOf(active);
1098
+ return list[index$2 === -1 ? dir === 1 ? 0 : len - 1 : index$2 + dir];
1099
+ }
1100
+ function getNextTabbable(referenceElement) {
1101
+ return getTabbableIn(getDocument(referenceElement).body, 1) || referenceElement;
1102
+ }
1103
+ function getPreviousTabbable(referenceElement) {
1104
+ return getTabbableIn(getDocument(referenceElement).body, -1) || referenceElement;
1105
+ }
1106
+ function isOutsideEvent(event, container) {
1107
+ const containerElement = container || event.currentTarget;
1108
+ const relatedTarget = event.relatedTarget;
1109
+ return !relatedTarget || !contains(containerElement, relatedTarget);
1110
+ }
1111
+ function computeCoordsFromPlacement(_ref, placement, rtl) {
1112
+ let { reference, floating } = _ref;
1113
+ const sideAxis = getSideAxis(placement);
1114
+ const alignmentAxis = getAlignmentAxis(placement);
1115
+ const alignLength = getAxisLength(alignmentAxis);
1116
+ const side = getSide(placement);
1117
+ const isVertical = sideAxis === "y";
1118
+ const commonX = reference.x + reference.width / 2 - floating.width / 2;
1119
+ const commonY = reference.y + reference.height / 2 - floating.height / 2;
1120
+ const commonAlign = reference[alignLength] / 2 - floating[alignLength] / 2;
1121
+ let coords;
1122
+ switch (side) {
1123
+ case "top":
1124
+ coords = {
1125
+ x: commonX,
1126
+ y: reference.y - floating.height
1127
+ };
1128
+ break;
1129
+ case "bottom":
1130
+ coords = {
1131
+ x: commonX,
1132
+ y: reference.y + reference.height
1133
+ };
1134
+ break;
1135
+ case "right":
1136
+ coords = {
1137
+ x: reference.x + reference.width,
1138
+ y: commonY
1139
+ };
1140
+ break;
1141
+ case "left":
1142
+ coords = {
1143
+ x: reference.x - floating.width,
1144
+ y: commonY
1145
+ };
1146
+ break;
1147
+ default: coords = {
1148
+ x: reference.x,
1149
+ y: reference.y
1150
+ };
1151
+ }
1152
+ switch (getAlignment(placement)) {
1153
+ case "start":
1154
+ coords[alignmentAxis] -= commonAlign * (rtl && isVertical ? -1 : 1);
1155
+ break;
1156
+ case "end":
1157
+ coords[alignmentAxis] += commonAlign * (rtl && isVertical ? -1 : 1);
1158
+ break;
1159
+ }
1160
+ return coords;
1161
+ }
1162
+ async function detectOverflow$1(state, options) {
1163
+ var _await$platform$isEle;
1164
+ if (options === void 0) options = {};
1165
+ const { x, y, platform: platform$1, rects, elements, strategy } = state;
1166
+ const { boundary = "clippingAncestors", rootBoundary = "viewport", elementContext = "floating", altBoundary = false, padding = 0 } = evaluate(options, state);
1167
+ const paddingObject = getPaddingObject(padding);
1168
+ const element = elements[altBoundary ? elementContext === "floating" ? "reference" : "floating" : elementContext];
1169
+ const clippingClientRect = rectToClientRect(await platform$1.getClippingRect({
1170
+ element: ((_await$platform$isEle = await (platform$1.isElement == null ? void 0 : platform$1.isElement(element))) != null ? _await$platform$isEle : true) ? element : element.contextElement || await (platform$1.getDocumentElement == null ? void 0 : platform$1.getDocumentElement(elements.floating)),
1171
+ boundary,
1172
+ rootBoundary,
1173
+ strategy
1174
+ }));
1175
+ const rect = elementContext === "floating" ? {
1176
+ x,
1177
+ y,
1178
+ width: rects.floating.width,
1179
+ height: rects.floating.height
1180
+ } : rects.reference;
1181
+ const offsetParent = await (platform$1.getOffsetParent == null ? void 0 : platform$1.getOffsetParent(elements.floating));
1182
+ const offsetScale = await (platform$1.isElement == null ? void 0 : platform$1.isElement(offsetParent)) ? await (platform$1.getScale == null ? void 0 : platform$1.getScale(offsetParent)) || {
1183
+ x: 1,
1184
+ y: 1
1185
+ } : {
1186
+ x: 1,
1187
+ y: 1
1188
+ };
1189
+ const elementClientRect = rectToClientRect(platform$1.convertOffsetParentRelativeRectToViewportRelativeRect ? await platform$1.convertOffsetParentRelativeRectToViewportRelativeRect({
1190
+ elements,
1191
+ rect,
1192
+ offsetParent,
1193
+ strategy
1194
+ }) : rect);
1195
+ return {
1196
+ top: (clippingClientRect.top - elementClientRect.top + paddingObject.top) / offsetScale.y,
1197
+ bottom: (elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom) / offsetScale.y,
1198
+ left: (clippingClientRect.left - elementClientRect.left + paddingObject.left) / offsetScale.x,
1199
+ right: (elementClientRect.right - clippingClientRect.right + paddingObject.right) / offsetScale.x
1200
+ };
1201
+ }
1202
+ var computePosition$1 = async (reference, floating, config) => {
1203
+ const { placement = "bottom", strategy = "absolute", middleware = [], platform: platform$1 } = config;
1204
+ const validMiddleware = middleware.filter(Boolean);
1205
+ const rtl = await (platform$1.isRTL == null ? void 0 : platform$1.isRTL(floating));
1206
+ let rects = await platform$1.getElementRects({
1207
+ reference,
1208
+ floating,
1209
+ strategy
1210
+ });
1211
+ let { x, y } = computeCoordsFromPlacement(rects, placement, rtl);
1212
+ let statefulPlacement = placement;
1213
+ let middlewareData = {};
1214
+ let resetCount = 0;
1215
+ for (let i = 0; i < validMiddleware.length; i++) {
1216
+ var _platform$detectOverf;
1217
+ const { name, fn } = validMiddleware[i];
1218
+ const { x: nextX, y: nextY, data, reset } = await fn({
1219
+ x,
1220
+ y,
1221
+ initialPlacement: placement,
1222
+ placement: statefulPlacement,
1223
+ strategy,
1224
+ middlewareData,
1225
+ rects,
1226
+ platform: {
1227
+ ...platform$1,
1228
+ detectOverflow: (_platform$detectOverf = platform$1.detectOverflow) != null ? _platform$detectOverf : detectOverflow$1
1229
+ },
1230
+ elements: {
1231
+ reference,
1232
+ floating
1233
+ }
1234
+ });
1235
+ x = nextX != null ? nextX : x;
1236
+ y = nextY != null ? nextY : y;
1237
+ middlewareData = {
1238
+ ...middlewareData,
1239
+ [name]: {
1240
+ ...middlewareData[name],
1241
+ ...data
1242
+ }
1243
+ };
1244
+ if (reset && resetCount <= 50) {
1245
+ resetCount++;
1246
+ if (typeof reset === "object") {
1247
+ if (reset.placement) statefulPlacement = reset.placement;
1248
+ if (reset.rects) rects = reset.rects === true ? await platform$1.getElementRects({
1249
+ reference,
1250
+ floating,
1251
+ strategy
1252
+ }) : reset.rects;
1253
+ ({x, y} = computeCoordsFromPlacement(rects, statefulPlacement, rtl));
1254
+ }
1255
+ i = -1;
1256
+ }
1257
+ }
1258
+ return {
1259
+ x,
1260
+ y,
1261
+ placement: statefulPlacement,
1262
+ strategy,
1263
+ middlewareData
1264
+ };
1265
+ };
1266
+ var originSides = /* @__PURE__ */ new Set(["left", "top"]);
1267
+ async function convertValueToCoords(state, options) {
1268
+ const { placement, platform: platform$1, elements } = state;
1269
+ const rtl = await (platform$1.isRTL == null ? void 0 : platform$1.isRTL(elements.floating));
1270
+ const side = getSide(placement);
1271
+ const alignment = getAlignment(placement);
1272
+ const isVertical = getSideAxis(placement) === "y";
1273
+ const mainAxisMulti = originSides.has(side) ? -1 : 1;
1274
+ const crossAxisMulti = rtl && isVertical ? -1 : 1;
1275
+ const rawValue = evaluate(options, state);
1276
+ let { mainAxis, crossAxis, alignmentAxis } = typeof rawValue === "number" ? {
1277
+ mainAxis: rawValue,
1278
+ crossAxis: 0,
1279
+ alignmentAxis: null
1280
+ } : {
1281
+ mainAxis: rawValue.mainAxis || 0,
1282
+ crossAxis: rawValue.crossAxis || 0,
1283
+ alignmentAxis: rawValue.alignmentAxis
1284
+ };
1285
+ if (alignment && typeof alignmentAxis === "number") crossAxis = alignment === "end" ? alignmentAxis * -1 : alignmentAxis;
1286
+ return isVertical ? {
1287
+ x: crossAxis * crossAxisMulti,
1288
+ y: mainAxis * mainAxisMulti
1289
+ } : {
1290
+ x: mainAxis * mainAxisMulti,
1291
+ y: crossAxis * crossAxisMulti
1292
+ };
1293
+ }
1294
+ var offset$2 = function(options) {
1295
+ if (options === void 0) options = 0;
1296
+ return {
1297
+ name: "offset",
1298
+ options,
1299
+ async fn(state) {
1300
+ var _middlewareData$offse, _middlewareData$arrow;
1301
+ const { x, y, placement, middlewareData } = state;
1302
+ const diffCoords = await convertValueToCoords(state, options);
1303
+ if (placement === ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse.placement) && (_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) return {};
1304
+ return {
1305
+ x: x + diffCoords.x,
1306
+ y: y + diffCoords.y,
1307
+ data: {
1308
+ ...diffCoords,
1309
+ placement
1310
+ }
1311
+ };
1312
+ }
1313
+ };
1314
+ };
1315
+ var shift$2 = function(options) {
1316
+ if (options === void 0) options = {};
1317
+ return {
1318
+ name: "shift",
1319
+ options,
1320
+ async fn(state) {
1321
+ const { x, y, placement, platform: platform$1 } = state;
1322
+ const { mainAxis: checkMainAxis = true, crossAxis: checkCrossAxis = false, limiter = { fn: (_ref) => {
1323
+ let { x: x$1, y: y$1 } = _ref;
1324
+ return {
1325
+ x: x$1,
1326
+ y: y$1
1327
+ };
1328
+ } }, ...detectOverflowOptions } = evaluate(options, state);
1329
+ const coords = {
1330
+ x,
1331
+ y
1332
+ };
1333
+ const overflow = await platform$1.detectOverflow(state, detectOverflowOptions);
1334
+ const crossAxis = getSideAxis(getSide(placement));
1335
+ const mainAxis = getOppositeAxis(crossAxis);
1336
+ let mainAxisCoord = coords[mainAxis];
1337
+ let crossAxisCoord = coords[crossAxis];
1338
+ if (checkMainAxis) {
1339
+ const minSide = mainAxis === "y" ? "top" : "left";
1340
+ const maxSide = mainAxis === "y" ? "bottom" : "right";
1341
+ const min$2 = mainAxisCoord + overflow[minSide];
1342
+ const max$2 = mainAxisCoord - overflow[maxSide];
1343
+ mainAxisCoord = clamp(min$2, mainAxisCoord, max$2);
1344
+ }
1345
+ if (checkCrossAxis) {
1346
+ const minSide = crossAxis === "y" ? "top" : "left";
1347
+ const maxSide = crossAxis === "y" ? "bottom" : "right";
1348
+ const min$2 = crossAxisCoord + overflow[minSide];
1349
+ const max$2 = crossAxisCoord - overflow[maxSide];
1350
+ crossAxisCoord = clamp(min$2, crossAxisCoord, max$2);
1351
+ }
1352
+ const limitedCoords = limiter.fn({
1353
+ ...state,
1354
+ [mainAxis]: mainAxisCoord,
1355
+ [crossAxis]: crossAxisCoord
1356
+ });
1357
+ return {
1358
+ ...limitedCoords,
1359
+ data: {
1360
+ x: limitedCoords.x - x,
1361
+ y: limitedCoords.y - y,
1362
+ enabled: {
1363
+ [mainAxis]: checkMainAxis,
1364
+ [crossAxis]: checkCrossAxis
1365
+ }
1366
+ }
1367
+ };
1368
+ }
1369
+ };
1370
+ };
1371
+ function getCssDimensions(element) {
1372
+ const css = getComputedStyle$1(element);
1373
+ let width = parseFloat(css.width) || 0;
1374
+ let height = parseFloat(css.height) || 0;
1375
+ const hasOffset = isHTMLElement(element);
1376
+ const offsetWidth = hasOffset ? element.offsetWidth : width;
1377
+ const offsetHeight = hasOffset ? element.offsetHeight : height;
1378
+ const shouldFallback = round(width) !== offsetWidth || round(height) !== offsetHeight;
1379
+ if (shouldFallback) {
1380
+ width = offsetWidth;
1381
+ height = offsetHeight;
1382
+ }
1383
+ return {
1384
+ width,
1385
+ height,
1386
+ $: shouldFallback
1387
+ };
1388
+ }
1389
+ function unwrapElement(element) {
1390
+ return !isElement(element) ? element.contextElement : element;
1391
+ }
1392
+ function getScale(element) {
1393
+ const domElement = unwrapElement(element);
1394
+ if (!isHTMLElement(domElement)) return createCoords(1);
1395
+ const rect = domElement.getBoundingClientRect();
1396
+ const { width, height, $ } = getCssDimensions(domElement);
1397
+ let x = ($ ? round(rect.width) : rect.width) / width;
1398
+ let y = ($ ? round(rect.height) : rect.height) / height;
1399
+ if (!x || !Number.isFinite(x)) x = 1;
1400
+ if (!y || !Number.isFinite(y)) y = 1;
1401
+ return {
1402
+ x,
1403
+ y
1404
+ };
1405
+ }
1406
+ var noOffsets = /* @__PURE__ */ createCoords(0);
1407
+ function getVisualOffsets(element) {
1408
+ const win = getWindow(element);
1409
+ if (!isWebKit() || !win.visualViewport) return noOffsets;
1410
+ return {
1411
+ x: win.visualViewport.offsetLeft,
1412
+ y: win.visualViewport.offsetTop
1413
+ };
1414
+ }
1415
+ function shouldAddVisualOffsets(element, isFixed, floatingOffsetParent) {
1416
+ if (isFixed === void 0) isFixed = false;
1417
+ if (!floatingOffsetParent || isFixed && floatingOffsetParent !== getWindow(element)) return false;
1418
+ return isFixed;
1419
+ }
1420
+ function getBoundingClientRect(element, includeScale, isFixedStrategy, offsetParent) {
1421
+ if (includeScale === void 0) includeScale = false;
1422
+ if (isFixedStrategy === void 0) isFixedStrategy = false;
1423
+ const clientRect = element.getBoundingClientRect();
1424
+ const domElement = unwrapElement(element);
1425
+ let scale = createCoords(1);
1426
+ if (includeScale) if (offsetParent) {
1427
+ if (isElement(offsetParent)) scale = getScale(offsetParent);
1428
+ } else scale = getScale(element);
1429
+ const visualOffsets = shouldAddVisualOffsets(domElement, isFixedStrategy, offsetParent) ? getVisualOffsets(domElement) : createCoords(0);
1430
+ let x = (clientRect.left + visualOffsets.x) / scale.x;
1431
+ let y = (clientRect.top + visualOffsets.y) / scale.y;
1432
+ let width = clientRect.width / scale.x;
1433
+ let height = clientRect.height / scale.y;
1434
+ if (domElement) {
1435
+ const win = getWindow(domElement);
1436
+ const offsetWin = offsetParent && isElement(offsetParent) ? getWindow(offsetParent) : offsetParent;
1437
+ let currentWin = win;
1438
+ let currentIFrame = getFrameElement(currentWin);
1439
+ while (currentIFrame && offsetParent && offsetWin !== currentWin) {
1440
+ const iframeScale = getScale(currentIFrame);
1441
+ const iframeRect = currentIFrame.getBoundingClientRect();
1442
+ const css = getComputedStyle$1(currentIFrame);
1443
+ const left = iframeRect.left + (currentIFrame.clientLeft + parseFloat(css.paddingLeft)) * iframeScale.x;
1444
+ const top = iframeRect.top + (currentIFrame.clientTop + parseFloat(css.paddingTop)) * iframeScale.y;
1445
+ x *= iframeScale.x;
1446
+ y *= iframeScale.y;
1447
+ width *= iframeScale.x;
1448
+ height *= iframeScale.y;
1449
+ x += left;
1450
+ y += top;
1451
+ currentWin = getWindow(currentIFrame);
1452
+ currentIFrame = getFrameElement(currentWin);
1453
+ }
1454
+ }
1455
+ return rectToClientRect({
1456
+ width,
1457
+ height,
1458
+ x,
1459
+ y
1460
+ });
1461
+ }
1462
+ function getWindowScrollBarX(element, rect) {
1463
+ const leftScroll = getNodeScroll(element).scrollLeft;
1464
+ if (!rect) return getBoundingClientRect(getDocumentElement(element)).left + leftScroll;
1465
+ return rect.left + leftScroll;
1466
+ }
1467
+ function getHTMLOffset(documentElement, scroll) {
1468
+ const htmlRect = documentElement.getBoundingClientRect();
1469
+ return {
1470
+ x: htmlRect.left + scroll.scrollLeft - getWindowScrollBarX(documentElement, htmlRect),
1471
+ y: htmlRect.top + scroll.scrollTop
1472
+ };
1473
+ }
1474
+ function convertOffsetParentRelativeRectToViewportRelativeRect(_ref) {
1475
+ let { elements, rect, offsetParent, strategy } = _ref;
1476
+ const isFixed = strategy === "fixed";
1477
+ const documentElement = getDocumentElement(offsetParent);
1478
+ const topLayer = elements ? isTopLayer(elements.floating) : false;
1479
+ if (offsetParent === documentElement || topLayer && isFixed) return rect;
1480
+ let scroll = {
1481
+ scrollLeft: 0,
1482
+ scrollTop: 0
1483
+ };
1484
+ let scale = createCoords(1);
1485
+ const offsets = createCoords(0);
1486
+ const isOffsetParentAnElement = isHTMLElement(offsetParent);
1487
+ if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {
1488
+ if (getNodeName(offsetParent) !== "body" || isOverflowElement(documentElement)) scroll = getNodeScroll(offsetParent);
1489
+ if (isHTMLElement(offsetParent)) {
1490
+ const offsetRect = getBoundingClientRect(offsetParent);
1491
+ scale = getScale(offsetParent);
1492
+ offsets.x = offsetRect.x + offsetParent.clientLeft;
1493
+ offsets.y = offsetRect.y + offsetParent.clientTop;
1494
+ }
1495
+ }
1496
+ const htmlOffset = documentElement && !isOffsetParentAnElement && !isFixed ? getHTMLOffset(documentElement, scroll) : createCoords(0);
1497
+ return {
1498
+ width: rect.width * scale.x,
1499
+ height: rect.height * scale.y,
1500
+ x: rect.x * scale.x - scroll.scrollLeft * scale.x + offsets.x + htmlOffset.x,
1501
+ y: rect.y * scale.y - scroll.scrollTop * scale.y + offsets.y + htmlOffset.y
1502
+ };
1503
+ }
1504
+ function getClientRects(element) {
1505
+ return Array.from(element.getClientRects());
1506
+ }
1507
+ function getDocumentRect(element) {
1508
+ const html = getDocumentElement(element);
1509
+ const scroll = getNodeScroll(element);
1510
+ const body = element.ownerDocument.body;
1511
+ const width = max$1(html.scrollWidth, html.clientWidth, body.scrollWidth, body.clientWidth);
1512
+ const height = max$1(html.scrollHeight, html.clientHeight, body.scrollHeight, body.clientHeight);
1513
+ let x = -scroll.scrollLeft + getWindowScrollBarX(element);
1514
+ const y = -scroll.scrollTop;
1515
+ if (getComputedStyle$1(body).direction === "rtl") x += max$1(html.clientWidth, body.clientWidth) - width;
1516
+ return {
1517
+ width,
1518
+ height,
1519
+ x,
1520
+ y
1521
+ };
1522
+ }
1523
+ var SCROLLBAR_MAX = 25;
1524
+ function getViewportRect(element, strategy) {
1525
+ const win = getWindow(element);
1526
+ const html = getDocumentElement(element);
1527
+ const visualViewport = win.visualViewport;
1528
+ let width = html.clientWidth;
1529
+ let height = html.clientHeight;
1530
+ let x = 0;
1531
+ let y = 0;
1532
+ if (visualViewport) {
1533
+ width = visualViewport.width;
1534
+ height = visualViewport.height;
1535
+ const visualViewportBased = isWebKit();
1536
+ if (!visualViewportBased || visualViewportBased && strategy === "fixed") {
1537
+ x = visualViewport.offsetLeft;
1538
+ y = visualViewport.offsetTop;
1539
+ }
1540
+ }
1541
+ const windowScrollbarX = getWindowScrollBarX(html);
1542
+ if (windowScrollbarX <= 0) {
1543
+ const doc = html.ownerDocument;
1544
+ const body = doc.body;
1545
+ const bodyStyles = getComputedStyle(body);
1546
+ const bodyMarginInline = doc.compatMode === "CSS1Compat" ? parseFloat(bodyStyles.marginLeft) + parseFloat(bodyStyles.marginRight) || 0 : 0;
1547
+ const clippingStableScrollbarWidth = Math.abs(html.clientWidth - body.clientWidth - bodyMarginInline);
1548
+ if (clippingStableScrollbarWidth <= SCROLLBAR_MAX) width -= clippingStableScrollbarWidth;
1549
+ } else if (windowScrollbarX <= SCROLLBAR_MAX) width += windowScrollbarX;
1550
+ return {
1551
+ width,
1552
+ height,
1553
+ x,
1554
+ y
1555
+ };
1556
+ }
1557
+ var absoluteOrFixed = /* @__PURE__ */ new Set(["absolute", "fixed"]);
1558
+ function getInnerBoundingClientRect(element, strategy) {
1559
+ const clientRect = getBoundingClientRect(element, true, strategy === "fixed");
1560
+ const top = clientRect.top + element.clientTop;
1561
+ const left = clientRect.left + element.clientLeft;
1562
+ const scale = isHTMLElement(element) ? getScale(element) : createCoords(1);
1563
+ return {
1564
+ width: element.clientWidth * scale.x,
1565
+ height: element.clientHeight * scale.y,
1566
+ x: left * scale.x,
1567
+ y: top * scale.y
1568
+ };
1569
+ }
1570
+ function getClientRectFromClippingAncestor(element, clippingAncestor, strategy) {
1571
+ let rect;
1572
+ if (clippingAncestor === "viewport") rect = getViewportRect(element, strategy);
1573
+ else if (clippingAncestor === "document") rect = getDocumentRect(getDocumentElement(element));
1574
+ else if (isElement(clippingAncestor)) rect = getInnerBoundingClientRect(clippingAncestor, strategy);
1575
+ else {
1576
+ const visualOffsets = getVisualOffsets(element);
1577
+ rect = {
1578
+ x: clippingAncestor.x - visualOffsets.x,
1579
+ y: clippingAncestor.y - visualOffsets.y,
1580
+ width: clippingAncestor.width,
1581
+ height: clippingAncestor.height
1582
+ };
1583
+ }
1584
+ return rectToClientRect(rect);
1585
+ }
1586
+ function hasFixedPositionAncestor(element, stopNode) {
1587
+ const parentNode = getParentNode(element);
1588
+ if (parentNode === stopNode || !isElement(parentNode) || isLastTraversableNode(parentNode)) return false;
1589
+ return getComputedStyle$1(parentNode).position === "fixed" || hasFixedPositionAncestor(parentNode, stopNode);
1590
+ }
1591
+ function getClippingElementAncestors(element, cache) {
1592
+ const cachedResult = cache.get(element);
1593
+ if (cachedResult) return cachedResult;
1594
+ let result = getOverflowAncestors(element, [], false).filter((el) => isElement(el) && getNodeName(el) !== "body");
1595
+ let currentContainingBlockComputedStyle = null;
1596
+ const elementIsFixed = getComputedStyle$1(element).position === "fixed";
1597
+ let currentNode = elementIsFixed ? getParentNode(element) : element;
1598
+ while (isElement(currentNode) && !isLastTraversableNode(currentNode)) {
1599
+ const computedStyle = getComputedStyle$1(currentNode);
1600
+ const currentNodeIsContaining = isContainingBlock(currentNode);
1601
+ if (!currentNodeIsContaining && computedStyle.position === "fixed") currentContainingBlockComputedStyle = null;
1602
+ if (elementIsFixed ? !currentNodeIsContaining && !currentContainingBlockComputedStyle : !currentNodeIsContaining && computedStyle.position === "static" && !!currentContainingBlockComputedStyle && absoluteOrFixed.has(currentContainingBlockComputedStyle.position) || isOverflowElement(currentNode) && !currentNodeIsContaining && hasFixedPositionAncestor(element, currentNode)) result = result.filter((ancestor) => ancestor !== currentNode);
1603
+ else currentContainingBlockComputedStyle = computedStyle;
1604
+ currentNode = getParentNode(currentNode);
1605
+ }
1606
+ cache.set(element, result);
1607
+ return result;
1608
+ }
1609
+ function getClippingRect(_ref) {
1610
+ let { element, boundary, rootBoundary, strategy } = _ref;
1611
+ const clippingAncestors = [...boundary === "clippingAncestors" ? isTopLayer(element) ? [] : getClippingElementAncestors(element, this._c) : [].concat(boundary), rootBoundary];
1612
+ const firstClippingAncestor = clippingAncestors[0];
1613
+ const clippingRect = clippingAncestors.reduce((accRect, clippingAncestor) => {
1614
+ const rect = getClientRectFromClippingAncestor(element, clippingAncestor, strategy);
1615
+ accRect.top = max$1(rect.top, accRect.top);
1616
+ accRect.right = min$1(rect.right, accRect.right);
1617
+ accRect.bottom = min$1(rect.bottom, accRect.bottom);
1618
+ accRect.left = max$1(rect.left, accRect.left);
1619
+ return accRect;
1620
+ }, getClientRectFromClippingAncestor(element, firstClippingAncestor, strategy));
1621
+ return {
1622
+ width: clippingRect.right - clippingRect.left,
1623
+ height: clippingRect.bottom - clippingRect.top,
1624
+ x: clippingRect.left,
1625
+ y: clippingRect.top
1626
+ };
1627
+ }
1628
+ function getDimensions(element) {
1629
+ const { width, height } = getCssDimensions(element);
1630
+ return {
1631
+ width,
1632
+ height
1633
+ };
1634
+ }
1635
+ function getRectRelativeToOffsetParent(element, offsetParent, strategy) {
1636
+ const isOffsetParentAnElement = isHTMLElement(offsetParent);
1637
+ const documentElement = getDocumentElement(offsetParent);
1638
+ const isFixed = strategy === "fixed";
1639
+ const rect = getBoundingClientRect(element, true, isFixed, offsetParent);
1640
+ let scroll = {
1641
+ scrollLeft: 0,
1642
+ scrollTop: 0
1643
+ };
1644
+ const offsets = createCoords(0);
1645
+ function setLeftRTLScrollbarOffset() {
1646
+ offsets.x = getWindowScrollBarX(documentElement);
1647
+ }
1648
+ if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {
1649
+ if (getNodeName(offsetParent) !== "body" || isOverflowElement(documentElement)) scroll = getNodeScroll(offsetParent);
1650
+ if (isOffsetParentAnElement) {
1651
+ const offsetRect = getBoundingClientRect(offsetParent, true, isFixed, offsetParent);
1652
+ offsets.x = offsetRect.x + offsetParent.clientLeft;
1653
+ offsets.y = offsetRect.y + offsetParent.clientTop;
1654
+ } else if (documentElement) setLeftRTLScrollbarOffset();
1655
+ }
1656
+ if (isFixed && !isOffsetParentAnElement && documentElement) setLeftRTLScrollbarOffset();
1657
+ const htmlOffset = documentElement && !isOffsetParentAnElement && !isFixed ? getHTMLOffset(documentElement, scroll) : createCoords(0);
1658
+ return {
1659
+ x: rect.left + scroll.scrollLeft - offsets.x - htmlOffset.x,
1660
+ y: rect.top + scroll.scrollTop - offsets.y - htmlOffset.y,
1661
+ width: rect.width,
1662
+ height: rect.height
1663
+ };
1664
+ }
1665
+ function isStaticPositioned(element) {
1666
+ return getComputedStyle$1(element).position === "static";
1667
+ }
1668
+ function getTrueOffsetParent(element, polyfill) {
1669
+ if (!isHTMLElement(element) || getComputedStyle$1(element).position === "fixed") return null;
1670
+ if (polyfill) return polyfill(element);
1671
+ let rawOffsetParent = element.offsetParent;
1672
+ if (getDocumentElement(element) === rawOffsetParent) rawOffsetParent = rawOffsetParent.ownerDocument.body;
1673
+ return rawOffsetParent;
1674
+ }
1675
+ function getOffsetParent(element, polyfill) {
1676
+ const win = getWindow(element);
1677
+ if (isTopLayer(element)) return win;
1678
+ if (!isHTMLElement(element)) {
1679
+ let svgOffsetParent = getParentNode(element);
1680
+ while (svgOffsetParent && !isLastTraversableNode(svgOffsetParent)) {
1681
+ if (isElement(svgOffsetParent) && !isStaticPositioned(svgOffsetParent)) return svgOffsetParent;
1682
+ svgOffsetParent = getParentNode(svgOffsetParent);
1683
+ }
1684
+ return win;
1685
+ }
1686
+ let offsetParent = getTrueOffsetParent(element, polyfill);
1687
+ while (offsetParent && isTableElement(offsetParent) && isStaticPositioned(offsetParent)) offsetParent = getTrueOffsetParent(offsetParent, polyfill);
1688
+ if (offsetParent && isLastTraversableNode(offsetParent) && isStaticPositioned(offsetParent) && !isContainingBlock(offsetParent)) return win;
1689
+ return offsetParent || getContainingBlock(element) || win;
1690
+ }
1691
+ var getElementRects = async function(data) {
1692
+ const getOffsetParentFn = this.getOffsetParent || getOffsetParent;
1693
+ const getDimensionsFn = this.getDimensions;
1694
+ const floatingDimensions = await getDimensionsFn(data.floating);
1695
+ return {
1696
+ reference: getRectRelativeToOffsetParent(data.reference, await getOffsetParentFn(data.floating), data.strategy),
1697
+ floating: {
1698
+ x: 0,
1699
+ y: 0,
1700
+ width: floatingDimensions.width,
1701
+ height: floatingDimensions.height
1702
+ }
1703
+ };
1704
+ };
1705
+ function isRTL(element) {
1706
+ return getComputedStyle$1(element).direction === "rtl";
1707
+ }
1708
+ var platform = {
1709
+ convertOffsetParentRelativeRectToViewportRelativeRect,
1710
+ getDocumentElement,
1711
+ getClippingRect,
1712
+ getOffsetParent,
1713
+ getElementRects,
1714
+ getClientRects,
1715
+ getDimensions,
1716
+ getScale,
1717
+ isElement,
1718
+ isRTL
1719
+ };
1720
+ function rectsAreEqual(a, b) {
1721
+ return a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height;
1722
+ }
1723
+ function observeMove(element, onMove) {
1724
+ let io = null;
1725
+ let timeoutId;
1726
+ const root = getDocumentElement(element);
1727
+ function cleanup() {
1728
+ var _io;
1729
+ clearTimeout(timeoutId);
1730
+ (_io = io) == null || _io.disconnect();
1731
+ io = null;
1732
+ }
1733
+ function refresh(skip, threshold) {
1734
+ if (skip === void 0) skip = false;
1735
+ if (threshold === void 0) threshold = 1;
1736
+ cleanup();
1737
+ const elementRectForRootMargin = element.getBoundingClientRect();
1738
+ const { left, top, width, height } = elementRectForRootMargin;
1739
+ if (!skip) onMove();
1740
+ if (!width || !height) return;
1741
+ const insetTop = floor(top);
1742
+ const insetRight = floor(root.clientWidth - (left + width));
1743
+ const insetBottom = floor(root.clientHeight - (top + height));
1744
+ const insetLeft = floor(left);
1745
+ const options = {
1746
+ rootMargin: -insetTop + "px " + -insetRight + "px " + -insetBottom + "px " + -insetLeft + "px",
1747
+ threshold: max$1(0, min$1(1, threshold)) || 1
1748
+ };
1749
+ let isFirstUpdate = true;
1750
+ function handleObserve(entries) {
1751
+ const ratio = entries[0].intersectionRatio;
1752
+ if (ratio !== threshold) {
1753
+ if (!isFirstUpdate) return refresh();
1754
+ if (!ratio) timeoutId = setTimeout(() => {
1755
+ refresh(false, 1e-7);
1756
+ }, 1e3);
1757
+ else refresh(false, ratio);
1758
+ }
1759
+ if (ratio === 1 && !rectsAreEqual(elementRectForRootMargin, element.getBoundingClientRect())) refresh();
1760
+ isFirstUpdate = false;
1761
+ }
1762
+ try {
1763
+ io = new IntersectionObserver(handleObserve, {
1764
+ ...options,
1765
+ root: root.ownerDocument
1766
+ });
1767
+ } catch (_e) {
1768
+ io = new IntersectionObserver(handleObserve, options);
1769
+ }
1770
+ io.observe(element);
1771
+ }
1772
+ refresh(true);
1773
+ return cleanup;
1774
+ }
1775
+ function autoUpdate(reference, floating, update, options) {
1776
+ if (options === void 0) options = {};
1777
+ const { ancestorScroll = true, ancestorResize = true, elementResize = typeof ResizeObserver === "function", layoutShift = typeof IntersectionObserver === "function", animationFrame = false } = options;
1778
+ const referenceEl = unwrapElement(reference);
1779
+ const ancestors = ancestorScroll || ancestorResize ? [...referenceEl ? getOverflowAncestors(referenceEl) : [], ...getOverflowAncestors(floating)] : [];
1780
+ ancestors.forEach((ancestor) => {
1781
+ ancestorScroll && ancestor.addEventListener("scroll", update, { passive: true });
1782
+ ancestorResize && ancestor.addEventListener("resize", update);
1783
+ });
1784
+ const cleanupIo = referenceEl && layoutShift ? observeMove(referenceEl, update) : null;
1785
+ let reobserveFrame = -1;
1786
+ let resizeObserver = null;
1787
+ if (elementResize) {
1788
+ resizeObserver = new ResizeObserver((_ref) => {
1789
+ let [firstEntry] = _ref;
1790
+ if (firstEntry && firstEntry.target === referenceEl && resizeObserver) {
1791
+ resizeObserver.unobserve(floating);
1792
+ cancelAnimationFrame(reobserveFrame);
1793
+ reobserveFrame = requestAnimationFrame(() => {
1794
+ var _resizeObserver;
1795
+ (_resizeObserver = resizeObserver) == null || _resizeObserver.observe(floating);
1796
+ });
1797
+ }
1798
+ update();
1799
+ });
1800
+ if (referenceEl && !animationFrame) resizeObserver.observe(referenceEl);
1801
+ resizeObserver.observe(floating);
1802
+ }
1803
+ let frameId;
1804
+ let prevRefRect = animationFrame ? getBoundingClientRect(reference) : null;
1805
+ if (animationFrame) frameLoop();
1806
+ function frameLoop() {
1807
+ const nextRefRect = getBoundingClientRect(reference);
1808
+ if (prevRefRect && !rectsAreEqual(prevRefRect, nextRefRect)) update();
1809
+ prevRefRect = nextRefRect;
1810
+ frameId = requestAnimationFrame(frameLoop);
1811
+ }
1812
+ update();
1813
+ return () => {
1814
+ var _resizeObserver2;
1815
+ ancestors.forEach((ancestor) => {
1816
+ ancestorScroll && ancestor.removeEventListener("scroll", update);
1817
+ ancestorResize && ancestor.removeEventListener("resize", update);
1818
+ });
1819
+ cleanupIo?.();
1820
+ (_resizeObserver2 = resizeObserver) == null || _resizeObserver2.disconnect();
1821
+ resizeObserver = null;
1822
+ if (animationFrame) cancelAnimationFrame(frameId);
1823
+ };
1824
+ }
1825
+ var offset$1 = offset$2;
1826
+ var shift$1 = shift$2;
1827
+ var computePosition = (reference, floating, options) => {
1828
+ const cache = /* @__PURE__ */ new Map();
1829
+ const mergedOptions = {
1830
+ platform,
1831
+ ...options
1832
+ };
1833
+ const platformWithCache = {
1834
+ ...mergedOptions.platform,
1835
+ _c: cache
1836
+ };
1837
+ return computePosition$1(reference, floating, {
1838
+ ...mergedOptions,
1839
+ platform: platformWithCache
1840
+ });
1841
+ };
1842
+ var index$1 = typeof document !== "undefined" ? useLayoutEffect : function noop() {};
1843
+ function deepEqual(a, b) {
1844
+ if (a === b) return true;
1845
+ if (typeof a !== typeof b) return false;
1846
+ if (typeof a === "function" && a.toString() === b.toString()) return true;
1847
+ let length;
1848
+ let i;
1849
+ let keys;
1850
+ if (a && b && typeof a === "object") {
1851
+ if (Array.isArray(a)) {
1852
+ length = a.length;
1853
+ if (length !== b.length) return false;
1854
+ for (i = length; i-- !== 0;) if (!deepEqual(a[i], b[i])) return false;
1855
+ return true;
1856
+ }
1857
+ keys = Object.keys(a);
1858
+ length = keys.length;
1859
+ if (length !== Object.keys(b).length) return false;
1860
+ for (i = length; i-- !== 0;) if (!{}.hasOwnProperty.call(b, keys[i])) return false;
1861
+ for (i = length; i-- !== 0;) {
1862
+ const key = keys[i];
1863
+ if (key === "_owner" && a.$$typeof) continue;
1864
+ if (!deepEqual(a[key], b[key])) return false;
1865
+ }
1866
+ return true;
1867
+ }
1868
+ return a !== a && b !== b;
1869
+ }
1870
+ function getDPR(element) {
1871
+ if (typeof window === "undefined") return 1;
1872
+ return (element.ownerDocument.defaultView || window).devicePixelRatio || 1;
1873
+ }
1874
+ function roundByDPR(element, value) {
1875
+ const dpr = getDPR(element);
1876
+ return Math.round(value * dpr) / dpr;
1877
+ }
1878
+ function useLatestRef$1(value) {
1879
+ const ref = React$1.useRef(value);
1880
+ index$1(() => {
1881
+ ref.current = value;
1882
+ });
1883
+ return ref;
1884
+ }
1885
+ function useFloating$1(options) {
1886
+ if (options === void 0) options = {};
1887
+ const { placement = "bottom", strategy = "absolute", middleware = [], platform: platform$1, elements: { reference: externalReference, floating: externalFloating } = {}, transform = true, whileElementsMounted, open } = options;
1888
+ const [data, setData] = React$1.useState({
1889
+ x: 0,
1890
+ y: 0,
1891
+ strategy,
1892
+ placement,
1893
+ middlewareData: {},
1894
+ isPositioned: false
1895
+ });
1896
+ const [latestMiddleware, setLatestMiddleware] = React$1.useState(middleware);
1897
+ if (!deepEqual(latestMiddleware, middleware)) setLatestMiddleware(middleware);
1898
+ const [_reference, _setReference] = React$1.useState(null);
1899
+ const [_floating, _setFloating] = React$1.useState(null);
1900
+ const setReference = React$1.useCallback((node) => {
1901
+ if (node !== referenceRef.current) {
1902
+ referenceRef.current = node;
1903
+ _setReference(node);
1904
+ }
1905
+ }, []);
1906
+ const setFloating = React$1.useCallback((node) => {
1907
+ if (node !== floatingRef.current) {
1908
+ floatingRef.current = node;
1909
+ _setFloating(node);
1910
+ }
1911
+ }, []);
1912
+ const referenceEl = externalReference || _reference;
1913
+ const floatingEl = externalFloating || _floating;
1914
+ const referenceRef = React$1.useRef(null);
1915
+ const floatingRef = React$1.useRef(null);
1916
+ const dataRef = React$1.useRef(data);
1917
+ const hasWhileElementsMounted = whileElementsMounted != null;
1918
+ const whileElementsMountedRef = useLatestRef$1(whileElementsMounted);
1919
+ const platformRef = useLatestRef$1(platform$1);
1920
+ const openRef = useLatestRef$1(open);
1921
+ const update = React$1.useCallback(() => {
1922
+ if (!referenceRef.current || !floatingRef.current) return;
1923
+ const config = {
1924
+ placement,
1925
+ strategy,
1926
+ middleware: latestMiddleware
1927
+ };
1928
+ if (platformRef.current) config.platform = platformRef.current;
1929
+ computePosition(referenceRef.current, floatingRef.current, config).then((data$1) => {
1930
+ const fullData = {
1931
+ ...data$1,
1932
+ isPositioned: openRef.current !== false
1933
+ };
1934
+ if (isMountedRef.current && !deepEqual(dataRef.current, fullData)) {
1935
+ dataRef.current = fullData;
1936
+ ReactDOM.flushSync(() => {
1937
+ setData(fullData);
1938
+ });
1939
+ }
1940
+ });
1941
+ }, [
1942
+ latestMiddleware,
1943
+ placement,
1944
+ strategy,
1945
+ platformRef,
1946
+ openRef
1947
+ ]);
1948
+ index$1(() => {
1949
+ if (open === false && dataRef.current.isPositioned) {
1950
+ dataRef.current.isPositioned = false;
1951
+ setData((data$1) => ({
1952
+ ...data$1,
1953
+ isPositioned: false
1954
+ }));
1955
+ }
1956
+ }, [open]);
1957
+ const isMountedRef = React$1.useRef(false);
1958
+ index$1(() => {
1959
+ isMountedRef.current = true;
1960
+ return () => {
1961
+ isMountedRef.current = false;
1962
+ };
1963
+ }, []);
1964
+ index$1(() => {
1965
+ if (referenceEl) referenceRef.current = referenceEl;
1966
+ if (floatingEl) floatingRef.current = floatingEl;
1967
+ if (referenceEl && floatingEl) {
1968
+ if (whileElementsMountedRef.current) return whileElementsMountedRef.current(referenceEl, floatingEl, update);
1969
+ update();
1970
+ }
1971
+ }, [
1972
+ referenceEl,
1973
+ floatingEl,
1974
+ update,
1975
+ whileElementsMountedRef,
1976
+ hasWhileElementsMounted
1977
+ ]);
1978
+ const refs = React$1.useMemo(() => ({
1979
+ reference: referenceRef,
1980
+ floating: floatingRef,
1981
+ setReference,
1982
+ setFloating
1983
+ }), [setReference, setFloating]);
1984
+ const elements = React$1.useMemo(() => ({
1985
+ reference: referenceEl,
1986
+ floating: floatingEl
1987
+ }), [referenceEl, floatingEl]);
1988
+ const floatingStyles = React$1.useMemo(() => {
1989
+ const initialStyles = {
1990
+ position: strategy,
1991
+ left: 0,
1992
+ top: 0
1993
+ };
1994
+ if (!elements.floating) return initialStyles;
1995
+ const x = roundByDPR(elements.floating, data.x);
1996
+ const y = roundByDPR(elements.floating, data.y);
1997
+ if (transform) return {
1998
+ ...initialStyles,
1999
+ transform: "translate(" + x + "px, " + y + "px)",
2000
+ ...getDPR(elements.floating) >= 1.5 && { willChange: "transform" }
2001
+ };
2002
+ return {
2003
+ position: strategy,
2004
+ left: x,
2005
+ top: y
2006
+ };
2007
+ }, [
2008
+ strategy,
2009
+ transform,
2010
+ elements.floating,
2011
+ data.x,
2012
+ data.y
2013
+ ]);
2014
+ return React$1.useMemo(() => ({
2015
+ ...data,
2016
+ update,
2017
+ refs,
2018
+ elements,
2019
+ floatingStyles
2020
+ }), [
2021
+ data,
2022
+ update,
2023
+ refs,
2024
+ elements,
2025
+ floatingStyles
2026
+ ]);
2027
+ }
2028
+ var offset = (options, deps) => ({
2029
+ ...offset$1(options),
2030
+ options: [options, deps]
2031
+ });
2032
+ var shift = (options, deps) => ({
2033
+ ...shift$1(options),
2034
+ options: [options, deps]
2035
+ });
2036
+ var FOCUSABLE_ATTRIBUTE = "data-floating-ui-focusable";
2037
+ var ACTIVE_KEY = "active";
2038
+ var SELECTED_KEY = "selected";
2039
+ var ARROW_LEFT = "ArrowLeft";
2040
+ var ARROW_RIGHT = "ArrowRight";
2041
+ var ARROW_UP = "ArrowUp";
2042
+ var ARROW_DOWN = "ArrowDown";
2043
+ var horizontalKeys = [ARROW_LEFT, ARROW_RIGHT];
2044
+ var verticalKeys = [ARROW_UP, ARROW_DOWN];
2045
+ [...horizontalKeys, ...verticalKeys];
2046
+ var SafeReact = { ...React$1 };
2047
+ var serverHandoffComplete = false;
2048
+ var count = 0;
2049
+ var genId = () => "floating-ui-" + Math.random().toString(36).slice(2, 6) + count++;
2050
+ function useFloatingId() {
2051
+ const [id, setId] = React$1.useState(() => serverHandoffComplete ? genId() : void 0);
2052
+ index(() => {
2053
+ if (id == null) setId(genId());
2054
+ }, []);
2055
+ React$1.useEffect(() => {
2056
+ serverHandoffComplete = true;
2057
+ }, []);
2058
+ return id;
2059
+ }
2060
+ var useId$1 = SafeReact.useId || useFloatingId;
2061
+ var devMessageSet;
2062
+ if (process.env.NODE_ENV !== "production") devMessageSet = /* @__PURE__ */ new Set();
2063
+ function error() {
2064
+ var _devMessageSet3;
2065
+ for (var _len2 = arguments.length, messages = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) messages[_key2] = arguments[_key2];
2066
+ const message = "Floating UI: " + messages.join(" ");
2067
+ if (!((_devMessageSet3 = devMessageSet) != null && _devMessageSet3.has(message))) {
2068
+ var _devMessageSet4;
2069
+ (_devMessageSet4 = devMessageSet) == null || _devMessageSet4.add(message);
2070
+ console.error(message);
2071
+ }
2072
+ }
2073
+ function createEventEmitter() {
2074
+ const map = /* @__PURE__ */ new Map();
2075
+ return {
2076
+ emit(event, data) {
2077
+ var _map$get;
2078
+ (_map$get = map.get(event)) == null || _map$get.forEach((listener) => listener(data));
2079
+ },
2080
+ on(event, listener) {
2081
+ if (!map.has(event)) map.set(event, /* @__PURE__ */ new Set());
2082
+ map.get(event).add(listener);
2083
+ },
2084
+ off(event, listener) {
2085
+ var _map$get2;
2086
+ (_map$get2 = map.get(event)) == null || _map$get2.delete(listener);
2087
+ }
2088
+ };
2089
+ }
2090
+ var FloatingNodeContext = /* @__PURE__ */ React$1.createContext(null);
2091
+ var FloatingTreeContext = /* @__PURE__ */ React$1.createContext(null);
2092
+ var useFloatingParentNodeId = () => {
2093
+ var _React$useContext;
2094
+ return ((_React$useContext = React$1.useContext(FloatingNodeContext)) == null ? void 0 : _React$useContext.id) || null;
2095
+ };
2096
+ var useFloatingTree = () => React$1.useContext(FloatingTreeContext);
2097
+ function createAttribute(name) {
2098
+ return "data-floating-ui-" + name;
2099
+ }
2100
+ function clearTimeoutIfSet(timeoutRef) {
2101
+ if (timeoutRef.current !== -1) {
2102
+ clearTimeout(timeoutRef.current);
2103
+ timeoutRef.current = -1;
2104
+ }
2105
+ }
2106
+ var rafId = 0;
2107
+ function enqueueFocus(el, options) {
2108
+ if (options === void 0) options = {};
2109
+ const { preventScroll = false, cancelPrevious = true, sync = false } = options;
2110
+ cancelPrevious && cancelAnimationFrame(rafId);
2111
+ const exec = () => el == null ? void 0 : el.focus({ preventScroll });
2112
+ if (sync) exec();
2113
+ else rafId = requestAnimationFrame(exec);
2114
+ }
2115
+ function getDocument$1(node) {
2116
+ return (node == null ? void 0 : node.ownerDocument) || document;
2117
+ }
2118
+ var counters = {
2119
+ inert: /* @__PURE__ */ new WeakMap(),
2120
+ "aria-hidden": /* @__PURE__ */ new WeakMap(),
2121
+ none: /* @__PURE__ */ new WeakMap()
2122
+ };
2123
+ function getCounterMap(control) {
2124
+ if (control === "inert") return counters.inert;
2125
+ if (control === "aria-hidden") return counters["aria-hidden"];
2126
+ return counters.none;
2127
+ }
2128
+ var uncontrolledElementsSet = /* @__PURE__ */ new WeakSet();
2129
+ var markerMap = {};
2130
+ var lockCount$1 = 0;
2131
+ var supportsInert = () => typeof HTMLElement !== "undefined" && "inert" in HTMLElement.prototype;
2132
+ var unwrapHost = (node) => node && (node.host || unwrapHost(node.parentNode));
2133
+ var correctElements = (parent, targets) => targets.map((target) => {
2134
+ if (parent.contains(target)) return target;
2135
+ const correctedTarget = unwrapHost(target);
2136
+ if (parent.contains(correctedTarget)) return correctedTarget;
2137
+ return null;
2138
+ }).filter((x) => x != null);
2139
+ function applyAttributeToOthers(uncorrectedAvoidElements, body, ariaHidden, inert) {
2140
+ const markerName = "data-floating-ui-inert";
2141
+ const controlAttribute = inert ? "inert" : ariaHidden ? "aria-hidden" : null;
2142
+ const avoidElements = correctElements(body, uncorrectedAvoidElements);
2143
+ const elementsToKeep = /* @__PURE__ */ new Set();
2144
+ const elementsToStop = new Set(avoidElements);
2145
+ const hiddenElements = [];
2146
+ if (!markerMap[markerName]) markerMap[markerName] = /* @__PURE__ */ new WeakMap();
2147
+ const markerCounter = markerMap[markerName];
2148
+ avoidElements.forEach(keep);
2149
+ deep(body);
2150
+ elementsToKeep.clear();
2151
+ function keep(el) {
2152
+ if (!el || elementsToKeep.has(el)) return;
2153
+ elementsToKeep.add(el);
2154
+ el.parentNode && keep(el.parentNode);
2155
+ }
2156
+ function deep(parent) {
2157
+ if (!parent || elementsToStop.has(parent)) return;
2158
+ [].forEach.call(parent.children, (node) => {
2159
+ if (getNodeName(node) === "script") return;
2160
+ if (elementsToKeep.has(node)) deep(node);
2161
+ else {
2162
+ const attr = controlAttribute ? node.getAttribute(controlAttribute) : null;
2163
+ const alreadyHidden = attr !== null && attr !== "false";
2164
+ const counterMap = getCounterMap(controlAttribute);
2165
+ const counterValue = (counterMap.get(node) || 0) + 1;
2166
+ const markerValue = (markerCounter.get(node) || 0) + 1;
2167
+ counterMap.set(node, counterValue);
2168
+ markerCounter.set(node, markerValue);
2169
+ hiddenElements.push(node);
2170
+ if (counterValue === 1 && alreadyHidden) uncontrolledElementsSet.add(node);
2171
+ if (markerValue === 1) node.setAttribute(markerName, "");
2172
+ if (!alreadyHidden && controlAttribute) node.setAttribute(controlAttribute, controlAttribute === "inert" ? "" : "true");
2173
+ }
2174
+ });
2175
+ }
2176
+ lockCount$1++;
2177
+ return () => {
2178
+ hiddenElements.forEach((element) => {
2179
+ const counterMap = getCounterMap(controlAttribute);
2180
+ const counterValue = (counterMap.get(element) || 0) - 1;
2181
+ const markerValue = (markerCounter.get(element) || 0) - 1;
2182
+ counterMap.set(element, counterValue);
2183
+ markerCounter.set(element, markerValue);
2184
+ if (!counterValue) {
2185
+ if (!uncontrolledElementsSet.has(element) && controlAttribute) element.removeAttribute(controlAttribute);
2186
+ uncontrolledElementsSet.delete(element);
2187
+ }
2188
+ if (!markerValue) element.removeAttribute(markerName);
2189
+ });
2190
+ lockCount$1--;
2191
+ if (!lockCount$1) {
2192
+ counters.inert = /* @__PURE__ */ new WeakMap();
2193
+ counters["aria-hidden"] = /* @__PURE__ */ new WeakMap();
2194
+ counters.none = /* @__PURE__ */ new WeakMap();
2195
+ uncontrolledElementsSet = /* @__PURE__ */ new WeakSet();
2196
+ markerMap = {};
2197
+ }
2198
+ };
2199
+ }
2200
+ function markOthers(avoidElements, ariaHidden, inert) {
2201
+ if (ariaHidden === void 0) ariaHidden = false;
2202
+ if (inert === void 0) inert = false;
2203
+ const body = getDocument$1(avoidElements[0]).body;
2204
+ return applyAttributeToOthers(avoidElements.concat(Array.from(body.querySelectorAll("[aria-live],[role=\"status\"],output"))), body, ariaHidden, inert);
2205
+ }
2206
+ var HIDDEN_STYLES = {
2207
+ border: 0,
2208
+ clip: "rect(0 0 0 0)",
2209
+ height: "1px",
2210
+ margin: "-1px",
2211
+ overflow: "hidden",
2212
+ padding: 0,
2213
+ position: "fixed",
2214
+ whiteSpace: "nowrap",
2215
+ width: "1px",
2216
+ top: 0,
2217
+ left: 0
2218
+ };
2219
+ var FocusGuard = /* @__PURE__ */ React$1.forwardRef(function FocusGuard$1(props, ref) {
2220
+ const [role, setRole] = React$1.useState();
2221
+ index(() => {
2222
+ if (isSafari()) setRole("button");
2223
+ }, []);
2224
+ const restProps = {
2225
+ ref,
2226
+ tabIndex: 0,
2227
+ role,
2228
+ "aria-hidden": role ? void 0 : true,
2229
+ [createAttribute("focus-guard")]: "",
2230
+ style: HIDDEN_STYLES
2231
+ };
2232
+ return /* @__PURE__ */ jsx("span", {
2233
+ ...props,
2234
+ ...restProps
2235
+ });
2236
+ });
2237
+ var PortalContext = /* @__PURE__ */ React$1.createContext(null);
2238
+ var usePortalContext = () => React$1.useContext(PortalContext);
2239
+ function useLiteMergeRefs(refs) {
2240
+ return React$1.useMemo(() => {
2241
+ return (value) => {
2242
+ refs.forEach((ref) => {
2243
+ if (ref) ref.current = value;
2244
+ });
2245
+ };
2246
+ }, refs);
2247
+ }
2248
+ var LIST_LIMIT = 20;
2249
+ var previouslyFocusedElements = [];
2250
+ function clearDisconnectedPreviouslyFocusedElements() {
2251
+ previouslyFocusedElements = previouslyFocusedElements.filter((el) => el.isConnected);
2252
+ }
2253
+ function addPreviouslyFocusedElement(element) {
2254
+ clearDisconnectedPreviouslyFocusedElements();
2255
+ if (element && getNodeName(element) !== "body") {
2256
+ previouslyFocusedElements.push(element);
2257
+ if (previouslyFocusedElements.length > LIST_LIMIT) previouslyFocusedElements = previouslyFocusedElements.slice(-20);
2258
+ }
2259
+ }
2260
+ function getPreviouslyFocusedElement() {
2261
+ clearDisconnectedPreviouslyFocusedElements();
2262
+ return previouslyFocusedElements[previouslyFocusedElements.length - 1];
2263
+ }
2264
+ function getFirstTabbableElement(container) {
2265
+ const tabbableOptions = getTabbableOptions();
2266
+ if (isTabbable(container, tabbableOptions)) return container;
2267
+ return tabbable(container, tabbableOptions)[0] || container;
2268
+ }
2269
+ function handleTabIndex(floatingFocusElement, orderRef) {
2270
+ var _floatingFocusElement;
2271
+ if (!orderRef.current.includes("floating") && !((_floatingFocusElement = floatingFocusElement.getAttribute("role")) != null && _floatingFocusElement.includes("dialog"))) return;
2272
+ const options = getTabbableOptions();
2273
+ const tabbableContent = focusable(floatingFocusElement, options).filter((element) => {
2274
+ const dataTabIndex = element.getAttribute("data-tabindex") || "";
2275
+ return isTabbable(element, options) || element.hasAttribute("data-tabindex") && !dataTabIndex.startsWith("-");
2276
+ });
2277
+ const tabIndex = floatingFocusElement.getAttribute("tabindex");
2278
+ if (orderRef.current.includes("floating") || tabbableContent.length === 0) {
2279
+ if (tabIndex !== "0") floatingFocusElement.setAttribute("tabindex", "0");
2280
+ } else if (tabIndex !== "-1" || floatingFocusElement.hasAttribute("data-tabindex") && floatingFocusElement.getAttribute("data-tabindex") !== "-1") {
2281
+ floatingFocusElement.setAttribute("tabindex", "-1");
2282
+ floatingFocusElement.setAttribute("data-tabindex", "-1");
2283
+ }
2284
+ }
2285
+ var VisuallyHiddenDismiss = /* @__PURE__ */ React$1.forwardRef(function VisuallyHiddenDismiss$1(props, ref) {
2286
+ return /* @__PURE__ */ jsx("button", {
2287
+ ...props,
2288
+ type: "button",
2289
+ ref,
2290
+ tabIndex: -1,
2291
+ style: HIDDEN_STYLES
2292
+ });
2293
+ });
2294
+ function FloatingFocusManager(props) {
2295
+ const { context, children, disabled = false, order = ["content"], guards: _guards = true, initialFocus = 0, returnFocus = true, restoreFocus = false, modal = true, visuallyHiddenDismiss = false, closeOnFocusOut = true, outsideElementsInert = false, getInsideElements: _getInsideElements = () => [] } = props;
2296
+ const { open, onOpenChange, events, dataRef, elements: { domReference, floating } } = context;
2297
+ const getNodeId = useEffectEvent(() => {
2298
+ var _dataRef$current$floa;
2299
+ return (_dataRef$current$floa = dataRef.current.floatingContext) == null ? void 0 : _dataRef$current$floa.nodeId;
2300
+ });
2301
+ const getInsideElements = useEffectEvent(_getInsideElements);
2302
+ const ignoreInitialFocus = typeof initialFocus === "number" && initialFocus < 0;
2303
+ const isUntrappedTypeableCombobox = isTypeableCombobox(domReference) && ignoreInitialFocus;
2304
+ const inertSupported = supportsInert();
2305
+ const guards = inertSupported ? _guards : true;
2306
+ const useInert = !guards || inertSupported && outsideElementsInert;
2307
+ const orderRef = useLatestRef(order);
2308
+ const initialFocusRef = useLatestRef(initialFocus);
2309
+ const returnFocusRef = useLatestRef(returnFocus);
2310
+ const tree = useFloatingTree();
2311
+ const portalContext = usePortalContext();
2312
+ const startDismissButtonRef = React$1.useRef(null);
2313
+ const endDismissButtonRef = React$1.useRef(null);
2314
+ const preventReturnFocusRef = React$1.useRef(false);
2315
+ const isPointerDownRef = React$1.useRef(false);
2316
+ const tabbableIndexRef = React$1.useRef(-1);
2317
+ const blurTimeoutRef = React$1.useRef(-1);
2318
+ const isInsidePortal = portalContext != null;
2319
+ const floatingFocusElement = getFloatingFocusElement(floating);
2320
+ const getTabbableContent = useEffectEvent(function(container) {
2321
+ if (container === void 0) container = floatingFocusElement;
2322
+ return container ? tabbable(container, getTabbableOptions()) : [];
2323
+ });
2324
+ const getTabbableElements = useEffectEvent((container) => {
2325
+ const content = getTabbableContent(container);
2326
+ return orderRef.current.map((type) => {
2327
+ if (domReference && type === "reference") return domReference;
2328
+ if (floatingFocusElement && type === "floating") return floatingFocusElement;
2329
+ return content;
2330
+ }).filter(Boolean).flat();
2331
+ });
2332
+ React$1.useEffect(() => {
2333
+ if (disabled) return;
2334
+ if (!modal) return;
2335
+ function onKeyDown(event) {
2336
+ if (event.key === "Tab") {
2337
+ if (contains(floatingFocusElement, activeElement(getDocument(floatingFocusElement))) && getTabbableContent().length === 0 && !isUntrappedTypeableCombobox) stopEvent(event);
2338
+ const els = getTabbableElements();
2339
+ const target = getTarget(event);
2340
+ if (orderRef.current[0] === "reference" && target === domReference) {
2341
+ stopEvent(event);
2342
+ if (event.shiftKey) enqueueFocus(els[els.length - 1]);
2343
+ else enqueueFocus(els[1]);
2344
+ }
2345
+ if (orderRef.current[1] === "floating" && target === floatingFocusElement && event.shiftKey) {
2346
+ stopEvent(event);
2347
+ enqueueFocus(els[0]);
2348
+ }
2349
+ }
2350
+ }
2351
+ const doc = getDocument(floatingFocusElement);
2352
+ doc.addEventListener("keydown", onKeyDown);
2353
+ return () => {
2354
+ doc.removeEventListener("keydown", onKeyDown);
2355
+ };
2356
+ }, [
2357
+ disabled,
2358
+ domReference,
2359
+ floatingFocusElement,
2360
+ modal,
2361
+ orderRef,
2362
+ isUntrappedTypeableCombobox,
2363
+ getTabbableContent,
2364
+ getTabbableElements
2365
+ ]);
2366
+ React$1.useEffect(() => {
2367
+ if (disabled) return;
2368
+ if (!floating) return;
2369
+ function handleFocusIn(event) {
2370
+ const target = getTarget(event);
2371
+ const tabbableIndex = getTabbableContent().indexOf(target);
2372
+ if (tabbableIndex !== -1) tabbableIndexRef.current = tabbableIndex;
2373
+ }
2374
+ floating.addEventListener("focusin", handleFocusIn);
2375
+ return () => {
2376
+ floating.removeEventListener("focusin", handleFocusIn);
2377
+ };
2378
+ }, [
2379
+ disabled,
2380
+ floating,
2381
+ getTabbableContent
2382
+ ]);
2383
+ React$1.useEffect(() => {
2384
+ if (disabled) return;
2385
+ if (!closeOnFocusOut) return;
2386
+ function handlePointerDown() {
2387
+ isPointerDownRef.current = true;
2388
+ setTimeout(() => {
2389
+ isPointerDownRef.current = false;
2390
+ });
2391
+ }
2392
+ function handleFocusOutside(event) {
2393
+ const relatedTarget = event.relatedTarget;
2394
+ const currentTarget = event.currentTarget;
2395
+ const target = getTarget(event);
2396
+ queueMicrotask(() => {
2397
+ const nodeId = getNodeId();
2398
+ const movedToUnrelatedNode = !(contains(domReference, relatedTarget) || contains(floating, relatedTarget) || contains(relatedTarget, floating) || contains(portalContext == null ? void 0 : portalContext.portalNode, relatedTarget) || relatedTarget != null && relatedTarget.hasAttribute(createAttribute("focus-guard")) || tree && (getNodeChildren(tree.nodesRef.current, nodeId).find((node) => {
2399
+ var _node$context, _node$context2;
2400
+ return contains((_node$context = node.context) == null ? void 0 : _node$context.elements.floating, relatedTarget) || contains((_node$context2 = node.context) == null ? void 0 : _node$context2.elements.domReference, relatedTarget);
2401
+ }) || getNodeAncestors(tree.nodesRef.current, nodeId).find((node) => {
2402
+ var _node$context3, _node$context4, _node$context5;
2403
+ return [(_node$context3 = node.context) == null ? void 0 : _node$context3.elements.floating, getFloatingFocusElement((_node$context4 = node.context) == null ? void 0 : _node$context4.elements.floating)].includes(relatedTarget) || ((_node$context5 = node.context) == null ? void 0 : _node$context5.elements.domReference) === relatedTarget;
2404
+ })));
2405
+ if (currentTarget === domReference && floatingFocusElement) handleTabIndex(floatingFocusElement, orderRef);
2406
+ if (restoreFocus && currentTarget !== domReference && !(target != null && target.isConnected) && activeElement(getDocument(floatingFocusElement)) === getDocument(floatingFocusElement).body) {
2407
+ if (isHTMLElement(floatingFocusElement)) floatingFocusElement.focus();
2408
+ const prevTabbableIndex = tabbableIndexRef.current;
2409
+ const tabbableContent = getTabbableContent();
2410
+ const nodeToFocus = tabbableContent[prevTabbableIndex] || tabbableContent[tabbableContent.length - 1] || floatingFocusElement;
2411
+ if (isHTMLElement(nodeToFocus)) nodeToFocus.focus();
2412
+ }
2413
+ if (dataRef.current.insideReactTree) {
2414
+ dataRef.current.insideReactTree = false;
2415
+ return;
2416
+ }
2417
+ if ((isUntrappedTypeableCombobox ? true : !modal) && relatedTarget && movedToUnrelatedNode && !isPointerDownRef.current && relatedTarget !== getPreviouslyFocusedElement()) {
2418
+ preventReturnFocusRef.current = true;
2419
+ onOpenChange(false, event, "focus-out");
2420
+ }
2421
+ });
2422
+ }
2423
+ const shouldHandleBlurCapture = Boolean(!tree && portalContext);
2424
+ function markInsideReactTree() {
2425
+ clearTimeoutIfSet(blurTimeoutRef);
2426
+ dataRef.current.insideReactTree = true;
2427
+ blurTimeoutRef.current = window.setTimeout(() => {
2428
+ dataRef.current.insideReactTree = false;
2429
+ });
2430
+ }
2431
+ if (floating && isHTMLElement(domReference)) {
2432
+ domReference.addEventListener("focusout", handleFocusOutside);
2433
+ domReference.addEventListener("pointerdown", handlePointerDown);
2434
+ floating.addEventListener("focusout", handleFocusOutside);
2435
+ if (shouldHandleBlurCapture) floating.addEventListener("focusout", markInsideReactTree, true);
2436
+ return () => {
2437
+ domReference.removeEventListener("focusout", handleFocusOutside);
2438
+ domReference.removeEventListener("pointerdown", handlePointerDown);
2439
+ floating.removeEventListener("focusout", handleFocusOutside);
2440
+ if (shouldHandleBlurCapture) floating.removeEventListener("focusout", markInsideReactTree, true);
2441
+ };
2442
+ }
2443
+ }, [
2444
+ disabled,
2445
+ domReference,
2446
+ floating,
2447
+ floatingFocusElement,
2448
+ modal,
2449
+ tree,
2450
+ portalContext,
2451
+ onOpenChange,
2452
+ closeOnFocusOut,
2453
+ restoreFocus,
2454
+ getTabbableContent,
2455
+ isUntrappedTypeableCombobox,
2456
+ getNodeId,
2457
+ orderRef,
2458
+ dataRef
2459
+ ]);
2460
+ const beforeGuardRef = React$1.useRef(null);
2461
+ const afterGuardRef = React$1.useRef(null);
2462
+ const mergedBeforeGuardRef = useLiteMergeRefs([beforeGuardRef, portalContext == null ? void 0 : portalContext.beforeInsideRef]);
2463
+ const mergedAfterGuardRef = useLiteMergeRefs([afterGuardRef, portalContext == null ? void 0 : portalContext.afterInsideRef]);
2464
+ React$1.useEffect(() => {
2465
+ var _portalContext$portal, _ancestors$find;
2466
+ if (disabled) return;
2467
+ if (!floating) return;
2468
+ const portalNodes = Array.from((portalContext == null || (_portalContext$portal = portalContext.portalNode) == null ? void 0 : _portalContext$portal.querySelectorAll("[" + createAttribute("portal") + "]")) || []);
2469
+ const insideElements = [
2470
+ floating,
2471
+ (_ancestors$find = (tree ? getNodeAncestors(tree.nodesRef.current, getNodeId()) : []).find((node) => {
2472
+ var _node$context6;
2473
+ return isTypeableCombobox(((_node$context6 = node.context) == null ? void 0 : _node$context6.elements.domReference) || null);
2474
+ })) == null || (_ancestors$find = _ancestors$find.context) == null ? void 0 : _ancestors$find.elements.domReference,
2475
+ ...portalNodes,
2476
+ ...getInsideElements(),
2477
+ startDismissButtonRef.current,
2478
+ endDismissButtonRef.current,
2479
+ beforeGuardRef.current,
2480
+ afterGuardRef.current,
2481
+ portalContext == null ? void 0 : portalContext.beforeOutsideRef.current,
2482
+ portalContext == null ? void 0 : portalContext.afterOutsideRef.current,
2483
+ orderRef.current.includes("reference") || isUntrappedTypeableCombobox ? domReference : null
2484
+ ].filter((x) => x != null);
2485
+ const cleanup = modal || isUntrappedTypeableCombobox ? markOthers(insideElements, !useInert, useInert) : markOthers(insideElements);
2486
+ return () => {
2487
+ cleanup();
2488
+ };
2489
+ }, [
2490
+ disabled,
2491
+ domReference,
2492
+ floating,
2493
+ modal,
2494
+ orderRef,
2495
+ portalContext,
2496
+ isUntrappedTypeableCombobox,
2497
+ guards,
2498
+ useInert,
2499
+ tree,
2500
+ getNodeId,
2501
+ getInsideElements
2502
+ ]);
2503
+ index(() => {
2504
+ if (disabled || !isHTMLElement(floatingFocusElement)) return;
2505
+ const previouslyFocusedElement = activeElement(getDocument(floatingFocusElement));
2506
+ queueMicrotask(() => {
2507
+ const focusableElements = getTabbableElements(floatingFocusElement);
2508
+ const initialFocusValue = initialFocusRef.current;
2509
+ const elToFocus = (typeof initialFocusValue === "number" ? focusableElements[initialFocusValue] : initialFocusValue.current) || floatingFocusElement;
2510
+ const focusAlreadyInsideFloatingEl = contains(floatingFocusElement, previouslyFocusedElement);
2511
+ if (!ignoreInitialFocus && !focusAlreadyInsideFloatingEl && open) enqueueFocus(elToFocus, { preventScroll: elToFocus === floatingFocusElement });
2512
+ });
2513
+ }, [
2514
+ disabled,
2515
+ open,
2516
+ floatingFocusElement,
2517
+ ignoreInitialFocus,
2518
+ getTabbableElements,
2519
+ initialFocusRef
2520
+ ]);
2521
+ index(() => {
2522
+ if (disabled || !floatingFocusElement) return;
2523
+ const doc = getDocument(floatingFocusElement);
2524
+ addPreviouslyFocusedElement(activeElement(doc));
2525
+ function onOpenChange$1(_ref) {
2526
+ let { reason, event, nested } = _ref;
2527
+ if (["hover", "safe-polygon"].includes(reason) && event.type === "mouseleave") preventReturnFocusRef.current = true;
2528
+ if (reason !== "outside-press") return;
2529
+ if (nested) preventReturnFocusRef.current = false;
2530
+ else if (isVirtualClick(event) || isVirtualPointerEvent(event)) preventReturnFocusRef.current = false;
2531
+ else {
2532
+ let isPreventScrollSupported = false;
2533
+ document.createElement("div").focus({ get preventScroll() {
2534
+ isPreventScrollSupported = true;
2535
+ return false;
2536
+ } });
2537
+ if (isPreventScrollSupported) preventReturnFocusRef.current = false;
2538
+ else preventReturnFocusRef.current = true;
2539
+ }
2540
+ }
2541
+ events.on("openchange", onOpenChange$1);
2542
+ const fallbackEl = doc.createElement("span");
2543
+ fallbackEl.setAttribute("tabindex", "-1");
2544
+ fallbackEl.setAttribute("aria-hidden", "true");
2545
+ Object.assign(fallbackEl.style, HIDDEN_STYLES);
2546
+ if (isInsidePortal && domReference) domReference.insertAdjacentElement("afterend", fallbackEl);
2547
+ function getReturnElement() {
2548
+ if (typeof returnFocusRef.current === "boolean") {
2549
+ const el = domReference || getPreviouslyFocusedElement();
2550
+ return el && el.isConnected ? el : fallbackEl;
2551
+ }
2552
+ return returnFocusRef.current.current || fallbackEl;
2553
+ }
2554
+ return () => {
2555
+ events.off("openchange", onOpenChange$1);
2556
+ const activeEl = activeElement(doc);
2557
+ const isFocusInsideFloatingTree = contains(floating, activeEl) || tree && getNodeChildren(tree.nodesRef.current, getNodeId(), false).some((node) => {
2558
+ var _node$context7;
2559
+ return contains((_node$context7 = node.context) == null ? void 0 : _node$context7.elements.floating, activeEl);
2560
+ });
2561
+ const returnElement = getReturnElement();
2562
+ queueMicrotask(() => {
2563
+ const tabbableReturnElement = getFirstTabbableElement(returnElement);
2564
+ if (returnFocusRef.current && !preventReturnFocusRef.current && isHTMLElement(tabbableReturnElement) && (tabbableReturnElement !== activeEl && activeEl !== doc.body ? isFocusInsideFloatingTree : true)) tabbableReturnElement.focus({ preventScroll: true });
2565
+ fallbackEl.remove();
2566
+ });
2567
+ };
2568
+ }, [
2569
+ disabled,
2570
+ floating,
2571
+ floatingFocusElement,
2572
+ returnFocusRef,
2573
+ dataRef,
2574
+ events,
2575
+ tree,
2576
+ isInsidePortal,
2577
+ domReference,
2578
+ getNodeId
2579
+ ]);
2580
+ React$1.useEffect(() => {
2581
+ queueMicrotask(() => {
2582
+ preventReturnFocusRef.current = false;
2583
+ });
2584
+ return () => {
2585
+ queueMicrotask(clearDisconnectedPreviouslyFocusedElements);
2586
+ };
2587
+ }, [disabled]);
2588
+ index(() => {
2589
+ if (disabled) return;
2590
+ if (!portalContext) return;
2591
+ portalContext.setFocusManagerState({
2592
+ modal,
2593
+ closeOnFocusOut,
2594
+ open,
2595
+ onOpenChange,
2596
+ domReference
2597
+ });
2598
+ return () => {
2599
+ portalContext.setFocusManagerState(null);
2600
+ };
2601
+ }, [
2602
+ disabled,
2603
+ portalContext,
2604
+ modal,
2605
+ open,
2606
+ onOpenChange,
2607
+ closeOnFocusOut,
2608
+ domReference
2609
+ ]);
2610
+ index(() => {
2611
+ if (disabled) return;
2612
+ if (!floatingFocusElement) return;
2613
+ handleTabIndex(floatingFocusElement, orderRef);
2614
+ }, [
2615
+ disabled,
2616
+ floatingFocusElement,
2617
+ orderRef
2618
+ ]);
2619
+ function renderDismissButton(location) {
2620
+ if (disabled || !visuallyHiddenDismiss || !modal) return null;
2621
+ return /* @__PURE__ */ jsx(VisuallyHiddenDismiss, {
2622
+ ref: location === "start" ? startDismissButtonRef : endDismissButtonRef,
2623
+ onClick: (event) => onOpenChange(false, event.nativeEvent),
2624
+ children: typeof visuallyHiddenDismiss === "string" ? visuallyHiddenDismiss : "Dismiss"
2625
+ });
2626
+ }
2627
+ const shouldRenderGuards = !disabled && guards && (modal ? !isUntrappedTypeableCombobox : true) && (isInsidePortal || modal);
2628
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
2629
+ shouldRenderGuards && /* @__PURE__ */ jsx(FocusGuard, {
2630
+ "data-type": "inside",
2631
+ ref: mergedBeforeGuardRef,
2632
+ onFocus: (event) => {
2633
+ if (modal) {
2634
+ const els = getTabbableElements();
2635
+ enqueueFocus(order[0] === "reference" ? els[0] : els[els.length - 1]);
2636
+ } else if (portalContext != null && portalContext.preserveTabOrder && portalContext.portalNode) {
2637
+ preventReturnFocusRef.current = false;
2638
+ if (isOutsideEvent(event, portalContext.portalNode)) getNextTabbable(domReference)?.focus();
2639
+ else {
2640
+ var _portalContext$before;
2641
+ (_portalContext$before = portalContext.beforeOutsideRef.current) == null || _portalContext$before.focus();
2642
+ }
2643
+ }
2644
+ }
2645
+ }),
2646
+ !isUntrappedTypeableCombobox && renderDismissButton("start"),
2647
+ children,
2648
+ renderDismissButton("end"),
2649
+ shouldRenderGuards && /* @__PURE__ */ jsx(FocusGuard, {
2650
+ "data-type": "inside",
2651
+ ref: mergedAfterGuardRef,
2652
+ onFocus: (event) => {
2653
+ if (modal) enqueueFocus(getTabbableElements()[0]);
2654
+ else if (portalContext != null && portalContext.preserveTabOrder && portalContext.portalNode) {
2655
+ if (closeOnFocusOut) preventReturnFocusRef.current = true;
2656
+ if (isOutsideEvent(event, portalContext.portalNode)) getPreviousTabbable(domReference)?.focus();
2657
+ else {
2658
+ var _portalContext$afterO;
2659
+ (_portalContext$afterO = portalContext.afterOutsideRef.current) == null || _portalContext$afterO.focus();
2660
+ }
2661
+ }
2662
+ }
2663
+ })
2664
+ ] });
2665
+ }
2666
+ function isButtonTarget(event) {
2667
+ return isHTMLElement(event.target) && event.target.tagName === "BUTTON";
2668
+ }
2669
+ function isAnchorTarget(event) {
2670
+ return isHTMLElement(event.target) && event.target.tagName === "A";
2671
+ }
2672
+ function isSpaceIgnored(element) {
2673
+ return isTypeableElement(element);
2674
+ }
2675
+ function useClick(context, props) {
2676
+ if (props === void 0) props = {};
2677
+ const { open, onOpenChange, dataRef, elements: { domReference } } = context;
2678
+ const { enabled = true, event: eventOption = "click", toggle = true, ignoreMouse = false, keyboardHandlers = true, stickIfOpen = true } = props;
2679
+ const pointerTypeRef = React$1.useRef();
2680
+ const didKeyDownRef = React$1.useRef(false);
2681
+ const reference = React$1.useMemo(() => ({
2682
+ onPointerDown(event) {
2683
+ pointerTypeRef.current = event.pointerType;
2684
+ },
2685
+ onMouseDown(event) {
2686
+ const pointerType = pointerTypeRef.current;
2687
+ if (event.button !== 0) return;
2688
+ if (eventOption === "click") return;
2689
+ if (isMouseLikePointerType(pointerType, true) && ignoreMouse) return;
2690
+ if (open && toggle && (dataRef.current.openEvent && stickIfOpen ? dataRef.current.openEvent.type === "mousedown" : true)) onOpenChange(false, event.nativeEvent, "click");
2691
+ else {
2692
+ event.preventDefault();
2693
+ onOpenChange(true, event.nativeEvent, "click");
2694
+ }
2695
+ },
2696
+ onClick(event) {
2697
+ const pointerType = pointerTypeRef.current;
2698
+ if (eventOption === "mousedown" && pointerTypeRef.current) {
2699
+ pointerTypeRef.current = void 0;
2700
+ return;
2701
+ }
2702
+ if (isMouseLikePointerType(pointerType, true) && ignoreMouse) return;
2703
+ if (open && toggle && (dataRef.current.openEvent && stickIfOpen ? dataRef.current.openEvent.type === "click" : true)) onOpenChange(false, event.nativeEvent, "click");
2704
+ else onOpenChange(true, event.nativeEvent, "click");
2705
+ },
2706
+ onKeyDown(event) {
2707
+ pointerTypeRef.current = void 0;
2708
+ if (event.defaultPrevented || !keyboardHandlers || isButtonTarget(event)) return;
2709
+ if (event.key === " " && !isSpaceIgnored(domReference)) {
2710
+ event.preventDefault();
2711
+ didKeyDownRef.current = true;
2712
+ }
2713
+ if (isAnchorTarget(event)) return;
2714
+ if (event.key === "Enter") if (open && toggle) onOpenChange(false, event.nativeEvent, "click");
2715
+ else onOpenChange(true, event.nativeEvent, "click");
2716
+ },
2717
+ onKeyUp(event) {
2718
+ if (event.defaultPrevented || !keyboardHandlers || isButtonTarget(event) || isSpaceIgnored(domReference)) return;
2719
+ if (event.key === " " && didKeyDownRef.current) {
2720
+ didKeyDownRef.current = false;
2721
+ if (open && toggle) onOpenChange(false, event.nativeEvent, "click");
2722
+ else onOpenChange(true, event.nativeEvent, "click");
2723
+ }
2724
+ }
2725
+ }), [
2726
+ dataRef,
2727
+ domReference,
2728
+ eventOption,
2729
+ ignoreMouse,
2730
+ keyboardHandlers,
2731
+ onOpenChange,
2732
+ open,
2733
+ stickIfOpen,
2734
+ toggle
2735
+ ]);
2736
+ return React$1.useMemo(() => enabled ? { reference } : {}, [enabled, reference]);
2737
+ }
2738
+ var bubbleHandlerKeys = {
2739
+ pointerdown: "onPointerDown",
2740
+ mousedown: "onMouseDown",
2741
+ click: "onClick"
2742
+ };
2743
+ var captureHandlerKeys = {
2744
+ pointerdown: "onPointerDownCapture",
2745
+ mousedown: "onMouseDownCapture",
2746
+ click: "onClickCapture"
2747
+ };
2748
+ var normalizeProp = (normalizable) => {
2749
+ var _normalizable$escapeK, _normalizable$outside;
2750
+ return {
2751
+ escapeKey: typeof normalizable === "boolean" ? normalizable : (_normalizable$escapeK = normalizable == null ? void 0 : normalizable.escapeKey) != null ? _normalizable$escapeK : false,
2752
+ outsidePress: typeof normalizable === "boolean" ? normalizable : (_normalizable$outside = normalizable == null ? void 0 : normalizable.outsidePress) != null ? _normalizable$outside : true
2753
+ };
2754
+ };
2755
+ function useDismiss(context, props) {
2756
+ if (props === void 0) props = {};
2757
+ const { open, onOpenChange, elements, dataRef } = context;
2758
+ const { enabled = true, escapeKey = true, outsidePress: unstable_outsidePress = true, outsidePressEvent = "pointerdown", referencePress = false, referencePressEvent = "pointerdown", ancestorScroll = false, bubbles, capture } = props;
2759
+ const tree = useFloatingTree();
2760
+ const outsidePressFn = useEffectEvent(typeof unstable_outsidePress === "function" ? unstable_outsidePress : () => false);
2761
+ const outsidePress = typeof unstable_outsidePress === "function" ? outsidePressFn : unstable_outsidePress;
2762
+ const endedOrStartedInsideRef = React$1.useRef(false);
2763
+ const { escapeKey: escapeKeyBubbles, outsidePress: outsidePressBubbles } = normalizeProp(bubbles);
2764
+ const { escapeKey: escapeKeyCapture, outsidePress: outsidePressCapture } = normalizeProp(capture);
2765
+ const isComposingRef = React$1.useRef(false);
2766
+ const closeOnEscapeKeyDown = useEffectEvent((event) => {
2767
+ var _dataRef$current$floa;
2768
+ if (!open || !enabled || !escapeKey || event.key !== "Escape") return;
2769
+ if (isComposingRef.current) return;
2770
+ const nodeId = (_dataRef$current$floa = dataRef.current.floatingContext) == null ? void 0 : _dataRef$current$floa.nodeId;
2771
+ const children = tree ? getNodeChildren(tree.nodesRef.current, nodeId) : [];
2772
+ if (!escapeKeyBubbles) {
2773
+ event.stopPropagation();
2774
+ if (children.length > 0) {
2775
+ let shouldDismiss = true;
2776
+ children.forEach((child) => {
2777
+ var _child$context;
2778
+ if ((_child$context = child.context) != null && _child$context.open && !child.context.dataRef.current.__escapeKeyBubbles) {
2779
+ shouldDismiss = false;
2780
+ return;
2781
+ }
2782
+ });
2783
+ if (!shouldDismiss) return;
2784
+ }
2785
+ }
2786
+ onOpenChange(false, isReactEvent(event) ? event.nativeEvent : event, "escape-key");
2787
+ });
2788
+ const closeOnEscapeKeyDownCapture = useEffectEvent((event) => {
2789
+ var _getTarget2;
2790
+ const callback = () => {
2791
+ var _getTarget;
2792
+ closeOnEscapeKeyDown(event);
2793
+ (_getTarget = getTarget(event)) == null || _getTarget.removeEventListener("keydown", callback);
2794
+ };
2795
+ (_getTarget2 = getTarget(event)) == null || _getTarget2.addEventListener("keydown", callback);
2796
+ });
2797
+ const closeOnPressOutside = useEffectEvent((event) => {
2798
+ var _dataRef$current$floa2;
2799
+ const insideReactTree = dataRef.current.insideReactTree;
2800
+ dataRef.current.insideReactTree = false;
2801
+ const endedOrStartedInside = endedOrStartedInsideRef.current;
2802
+ endedOrStartedInsideRef.current = false;
2803
+ if (outsidePressEvent === "click" && endedOrStartedInside) return;
2804
+ if (insideReactTree) return;
2805
+ if (typeof outsidePress === "function" && !outsidePress(event)) return;
2806
+ const target = getTarget(event);
2807
+ const inertSelector = "[" + createAttribute("inert") + "]";
2808
+ const markers = getDocument(elements.floating).querySelectorAll(inertSelector);
2809
+ let targetRootAncestor = isElement(target) ? target : null;
2810
+ while (targetRootAncestor && !isLastTraversableNode(targetRootAncestor)) {
2811
+ const nextParent = getParentNode(targetRootAncestor);
2812
+ if (isLastTraversableNode(nextParent) || !isElement(nextParent)) break;
2813
+ targetRootAncestor = nextParent;
2814
+ }
2815
+ if (markers.length && isElement(target) && !isRootElement(target) && !contains(target, elements.floating) && Array.from(markers).every((marker) => !contains(targetRootAncestor, marker))) return;
2816
+ if (isHTMLElement(target) && floating) {
2817
+ const lastTraversableNode = isLastTraversableNode(target);
2818
+ const style = getComputedStyle$1(target);
2819
+ const scrollRe = /auto|scroll/;
2820
+ const isScrollableX = lastTraversableNode || scrollRe.test(style.overflowX);
2821
+ const isScrollableY = lastTraversableNode || scrollRe.test(style.overflowY);
2822
+ const canScrollX = isScrollableX && target.clientWidth > 0 && target.scrollWidth > target.clientWidth;
2823
+ const canScrollY = isScrollableY && target.clientHeight > 0 && target.scrollHeight > target.clientHeight;
2824
+ const isRTL$1 = style.direction === "rtl";
2825
+ const pressedVerticalScrollbar = canScrollY && (isRTL$1 ? event.offsetX <= target.offsetWidth - target.clientWidth : event.offsetX > target.clientWidth);
2826
+ const pressedHorizontalScrollbar = canScrollX && event.offsetY > target.clientHeight;
2827
+ if (pressedVerticalScrollbar || pressedHorizontalScrollbar) return;
2828
+ }
2829
+ const nodeId = (_dataRef$current$floa2 = dataRef.current.floatingContext) == null ? void 0 : _dataRef$current$floa2.nodeId;
2830
+ const targetIsInsideChildren = tree && getNodeChildren(tree.nodesRef.current, nodeId).some((node) => {
2831
+ var _node$context;
2832
+ return isEventTargetWithin(event, (_node$context = node.context) == null ? void 0 : _node$context.elements.floating);
2833
+ });
2834
+ if (isEventTargetWithin(event, elements.floating) || isEventTargetWithin(event, elements.domReference) || targetIsInsideChildren) return;
2835
+ const children = tree ? getNodeChildren(tree.nodesRef.current, nodeId) : [];
2836
+ if (children.length > 0) {
2837
+ let shouldDismiss = true;
2838
+ children.forEach((child) => {
2839
+ var _child$context2;
2840
+ if ((_child$context2 = child.context) != null && _child$context2.open && !child.context.dataRef.current.__outsidePressBubbles) {
2841
+ shouldDismiss = false;
2842
+ return;
2843
+ }
2844
+ });
2845
+ if (!shouldDismiss) return;
2846
+ }
2847
+ onOpenChange(false, event, "outside-press");
2848
+ });
2849
+ const closeOnPressOutsideCapture = useEffectEvent((event) => {
2850
+ var _getTarget4;
2851
+ const callback = () => {
2852
+ var _getTarget3;
2853
+ closeOnPressOutside(event);
2854
+ (_getTarget3 = getTarget(event)) == null || _getTarget3.removeEventListener(outsidePressEvent, callback);
2855
+ };
2856
+ (_getTarget4 = getTarget(event)) == null || _getTarget4.addEventListener(outsidePressEvent, callback);
2857
+ });
2858
+ React$1.useEffect(() => {
2859
+ if (!open || !enabled) return;
2860
+ dataRef.current.__escapeKeyBubbles = escapeKeyBubbles;
2861
+ dataRef.current.__outsidePressBubbles = outsidePressBubbles;
2862
+ let compositionTimeout = -1;
2863
+ function onScroll(event) {
2864
+ onOpenChange(false, event, "ancestor-scroll");
2865
+ }
2866
+ function handleCompositionStart() {
2867
+ window.clearTimeout(compositionTimeout);
2868
+ isComposingRef.current = true;
2869
+ }
2870
+ function handleCompositionEnd() {
2871
+ compositionTimeout = window.setTimeout(() => {
2872
+ isComposingRef.current = false;
2873
+ }, isWebKit() ? 5 : 0);
2874
+ }
2875
+ const doc = getDocument(elements.floating);
2876
+ if (escapeKey) {
2877
+ doc.addEventListener("keydown", escapeKeyCapture ? closeOnEscapeKeyDownCapture : closeOnEscapeKeyDown, escapeKeyCapture);
2878
+ doc.addEventListener("compositionstart", handleCompositionStart);
2879
+ doc.addEventListener("compositionend", handleCompositionEnd);
2880
+ }
2881
+ outsidePress && doc.addEventListener(outsidePressEvent, outsidePressCapture ? closeOnPressOutsideCapture : closeOnPressOutside, outsidePressCapture);
2882
+ let ancestors = [];
2883
+ if (ancestorScroll) {
2884
+ if (isElement(elements.domReference)) ancestors = getOverflowAncestors(elements.domReference);
2885
+ if (isElement(elements.floating)) ancestors = ancestors.concat(getOverflowAncestors(elements.floating));
2886
+ if (!isElement(elements.reference) && elements.reference && elements.reference.contextElement) ancestors = ancestors.concat(getOverflowAncestors(elements.reference.contextElement));
2887
+ }
2888
+ ancestors = ancestors.filter((ancestor) => {
2889
+ var _doc$defaultView;
2890
+ return ancestor !== ((_doc$defaultView = doc.defaultView) == null ? void 0 : _doc$defaultView.visualViewport);
2891
+ });
2892
+ ancestors.forEach((ancestor) => {
2893
+ ancestor.addEventListener("scroll", onScroll, { passive: true });
2894
+ });
2895
+ return () => {
2896
+ if (escapeKey) {
2897
+ doc.removeEventListener("keydown", escapeKeyCapture ? closeOnEscapeKeyDownCapture : closeOnEscapeKeyDown, escapeKeyCapture);
2898
+ doc.removeEventListener("compositionstart", handleCompositionStart);
2899
+ doc.removeEventListener("compositionend", handleCompositionEnd);
2900
+ }
2901
+ outsidePress && doc.removeEventListener(outsidePressEvent, outsidePressCapture ? closeOnPressOutsideCapture : closeOnPressOutside, outsidePressCapture);
2902
+ ancestors.forEach((ancestor) => {
2903
+ ancestor.removeEventListener("scroll", onScroll);
2904
+ });
2905
+ window.clearTimeout(compositionTimeout);
2906
+ };
2907
+ }, [
2908
+ dataRef,
2909
+ elements,
2910
+ escapeKey,
2911
+ outsidePress,
2912
+ outsidePressEvent,
2913
+ open,
2914
+ onOpenChange,
2915
+ ancestorScroll,
2916
+ enabled,
2917
+ escapeKeyBubbles,
2918
+ outsidePressBubbles,
2919
+ closeOnEscapeKeyDown,
2920
+ escapeKeyCapture,
2921
+ closeOnEscapeKeyDownCapture,
2922
+ closeOnPressOutside,
2923
+ outsidePressCapture,
2924
+ closeOnPressOutsideCapture
2925
+ ]);
2926
+ React$1.useEffect(() => {
2927
+ dataRef.current.insideReactTree = false;
2928
+ }, [
2929
+ dataRef,
2930
+ outsidePress,
2931
+ outsidePressEvent
2932
+ ]);
2933
+ const reference = React$1.useMemo(() => ({
2934
+ onKeyDown: closeOnEscapeKeyDown,
2935
+ ...referencePress && {
2936
+ [bubbleHandlerKeys[referencePressEvent]]: (event) => {
2937
+ onOpenChange(false, event.nativeEvent, "reference-press");
2938
+ },
2939
+ ...referencePressEvent !== "click" && { onClick(event) {
2940
+ onOpenChange(false, event.nativeEvent, "reference-press");
2941
+ } }
2942
+ }
2943
+ }), [
2944
+ closeOnEscapeKeyDown,
2945
+ onOpenChange,
2946
+ referencePress,
2947
+ referencePressEvent
2948
+ ]);
2949
+ const floating = React$1.useMemo(() => ({
2950
+ onKeyDown: closeOnEscapeKeyDown,
2951
+ onMouseDown() {
2952
+ endedOrStartedInsideRef.current = true;
2953
+ },
2954
+ onMouseUp() {
2955
+ endedOrStartedInsideRef.current = true;
2956
+ },
2957
+ [captureHandlerKeys[outsidePressEvent]]: () => {
2958
+ dataRef.current.insideReactTree = true;
2959
+ }
2960
+ }), [
2961
+ closeOnEscapeKeyDown,
2962
+ outsidePressEvent,
2963
+ dataRef
2964
+ ]);
2965
+ return React$1.useMemo(() => enabled ? {
2966
+ reference,
2967
+ floating
2968
+ } : {}, [
2969
+ enabled,
2970
+ reference,
2971
+ floating
2972
+ ]);
2973
+ }
2974
+ function useFloatingRootContext(options) {
2975
+ const { open = false, onOpenChange: onOpenChangeProp, elements: elementsProp } = options;
2976
+ const floatingId = useId$1();
2977
+ const dataRef = React$1.useRef({});
2978
+ const [events] = React$1.useState(() => createEventEmitter());
2979
+ const nested = useFloatingParentNodeId() != null;
2980
+ if (process.env.NODE_ENV !== "production") {
2981
+ const optionDomReference = elementsProp.reference;
2982
+ if (optionDomReference && !isElement(optionDomReference)) error("Cannot pass a virtual element to the `elements.reference` option,", "as it must be a real DOM element. Use `refs.setPositionReference()`", "instead.");
2983
+ }
2984
+ const [positionReference, setPositionReference] = React$1.useState(elementsProp.reference);
2985
+ const onOpenChange = useEffectEvent((open$1, event, reason) => {
2986
+ dataRef.current.openEvent = open$1 ? event : void 0;
2987
+ events.emit("openchange", {
2988
+ open: open$1,
2989
+ event,
2990
+ reason,
2991
+ nested
2992
+ });
2993
+ onOpenChangeProp?.(open$1, event, reason);
2994
+ });
2995
+ const refs = React$1.useMemo(() => ({ setPositionReference }), []);
2996
+ const elements = React$1.useMemo(() => ({
2997
+ reference: positionReference || elementsProp.reference || null,
2998
+ floating: elementsProp.floating || null,
2999
+ domReference: elementsProp.reference
3000
+ }), [
3001
+ positionReference,
3002
+ elementsProp.reference,
3003
+ elementsProp.floating
3004
+ ]);
3005
+ return React$1.useMemo(() => ({
3006
+ dataRef,
3007
+ open,
3008
+ onOpenChange,
3009
+ elements,
3010
+ events,
3011
+ floatingId,
3012
+ refs
3013
+ }), [
3014
+ open,
3015
+ onOpenChange,
3016
+ elements,
3017
+ events,
3018
+ floatingId,
3019
+ refs
3020
+ ]);
3021
+ }
3022
+ function useFloating(options) {
3023
+ if (options === void 0) options = {};
3024
+ const { nodeId } = options;
3025
+ const internalRootContext = useFloatingRootContext({
3026
+ ...options,
3027
+ elements: {
3028
+ reference: null,
3029
+ floating: null,
3030
+ ...options.elements
3031
+ }
3032
+ });
3033
+ const rootContext = options.rootContext || internalRootContext;
3034
+ const computedElements = rootContext.elements;
3035
+ const [_domReference, setDomReference] = React$1.useState(null);
3036
+ const [positionReference, _setPositionReference] = React$1.useState(null);
3037
+ const domReference = (computedElements == null ? void 0 : computedElements.domReference) || _domReference;
3038
+ const domReferenceRef = React$1.useRef(null);
3039
+ const tree = useFloatingTree();
3040
+ index(() => {
3041
+ if (domReference) domReferenceRef.current = domReference;
3042
+ }, [domReference]);
3043
+ const position = useFloating$1({
3044
+ ...options,
3045
+ elements: {
3046
+ ...computedElements,
3047
+ ...positionReference && { reference: positionReference }
3048
+ }
3049
+ });
3050
+ const setPositionReference = React$1.useCallback((node) => {
3051
+ const computedPositionReference = isElement(node) ? {
3052
+ getBoundingClientRect: () => node.getBoundingClientRect(),
3053
+ getClientRects: () => node.getClientRects(),
3054
+ contextElement: node
3055
+ } : node;
3056
+ _setPositionReference(computedPositionReference);
3057
+ position.refs.setReference(computedPositionReference);
3058
+ }, [position.refs]);
3059
+ const setReference = React$1.useCallback((node) => {
3060
+ if (isElement(node) || node === null) {
3061
+ domReferenceRef.current = node;
3062
+ setDomReference(node);
3063
+ }
3064
+ if (isElement(position.refs.reference.current) || position.refs.reference.current === null || node !== null && !isElement(node)) position.refs.setReference(node);
3065
+ }, [position.refs]);
3066
+ const refs = React$1.useMemo(() => ({
3067
+ ...position.refs,
3068
+ setReference,
3069
+ setPositionReference,
3070
+ domReference: domReferenceRef
3071
+ }), [
3072
+ position.refs,
3073
+ setReference,
3074
+ setPositionReference
3075
+ ]);
3076
+ const elements = React$1.useMemo(() => ({
3077
+ ...position.elements,
3078
+ domReference
3079
+ }), [position.elements, domReference]);
3080
+ const context = React$1.useMemo(() => ({
3081
+ ...position,
3082
+ ...rootContext,
3083
+ refs,
3084
+ elements,
3085
+ nodeId
3086
+ }), [
3087
+ position,
3088
+ refs,
3089
+ elements,
3090
+ nodeId,
3091
+ rootContext
3092
+ ]);
3093
+ index(() => {
3094
+ rootContext.dataRef.current.floatingContext = context;
3095
+ const node = tree == null ? void 0 : tree.nodesRef.current.find((node$1) => node$1.id === nodeId);
3096
+ if (node) node.context = context;
3097
+ });
3098
+ return React$1.useMemo(() => ({
3099
+ ...position,
3100
+ context,
3101
+ refs,
3102
+ elements
3103
+ }), [
3104
+ position,
3105
+ refs,
3106
+ elements,
3107
+ context
3108
+ ]);
3109
+ }
3110
+ function mergeProps(userProps, propsList, elementKey) {
3111
+ const map = /* @__PURE__ */ new Map();
3112
+ const isItem = elementKey === "item";
3113
+ let domUserProps = userProps;
3114
+ if (isItem && userProps) {
3115
+ const { [ACTIVE_KEY]: _, [SELECTED_KEY]: __, ...validProps } = userProps;
3116
+ domUserProps = validProps;
3117
+ }
3118
+ return {
3119
+ ...elementKey === "floating" && {
3120
+ tabIndex: -1,
3121
+ [FOCUSABLE_ATTRIBUTE]: ""
3122
+ },
3123
+ ...domUserProps,
3124
+ ...propsList.map((value) => {
3125
+ const propsOrGetProps = value ? value[elementKey] : null;
3126
+ if (typeof propsOrGetProps === "function") return userProps ? propsOrGetProps(userProps) : null;
3127
+ return propsOrGetProps;
3128
+ }).concat(userProps).reduce((acc, props) => {
3129
+ if (!props) return acc;
3130
+ Object.entries(props).forEach((_ref) => {
3131
+ let [key, value] = _ref;
3132
+ if (isItem && [ACTIVE_KEY, SELECTED_KEY].includes(key)) return;
3133
+ if (key.indexOf("on") === 0) {
3134
+ if (!map.has(key)) map.set(key, []);
3135
+ if (typeof value === "function") {
3136
+ var _map$get;
3137
+ (_map$get = map.get(key)) == null || _map$get.push(value);
3138
+ acc[key] = function() {
3139
+ var _map$get2;
3140
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key];
3141
+ return (_map$get2 = map.get(key)) == null ? void 0 : _map$get2.map((fn) => fn(...args)).find((val) => val !== void 0);
3142
+ };
3143
+ }
3144
+ } else acc[key] = value;
3145
+ });
3146
+ return acc;
3147
+ }, {})
3148
+ };
3149
+ }
3150
+ function useInteractions(propsList) {
3151
+ if (propsList === void 0) propsList = [];
3152
+ const referenceDeps = propsList.map((key) => key == null ? void 0 : key.reference);
3153
+ const floatingDeps = propsList.map((key) => key == null ? void 0 : key.floating);
3154
+ const itemDeps = propsList.map((key) => key == null ? void 0 : key.item);
3155
+ const getReferenceProps = React$1.useCallback((userProps) => mergeProps(userProps, propsList, "reference"), referenceDeps);
3156
+ const getFloatingProps = React$1.useCallback((userProps) => mergeProps(userProps, propsList, "floating"), floatingDeps);
3157
+ const getItemProps = React$1.useCallback((userProps) => mergeProps(userProps, propsList, "item"), itemDeps);
3158
+ return React$1.useMemo(() => ({
3159
+ getReferenceProps,
3160
+ getFloatingProps,
3161
+ getItemProps
3162
+ }), [
3163
+ getReferenceProps,
3164
+ getFloatingProps,
3165
+ getItemProps
3166
+ ]);
3167
+ }
3168
+ var DateInputInternal = ({ value, onChange, onBlur, inputId, legendId, setErrorText, resources, withClearButton, ["aria-describedby"]: ariaDescribedBy, ["aria-labelledby"]: ariaLabelledBy }) => {
3169
+ const [errorTextDd, setErrorTextDd] = useState("");
3170
+ const [errorTextMm, setErrorTextMm] = useState("");
3171
+ const [errorTextYyyy, setErrorTextYyyy] = useState("");
3172
+ const [dd, setDd] = useState("");
3173
+ const [mm, setMm] = useState("");
3174
+ const [yyyy, setYyyy] = useState("");
3175
+ const hasValue = dd !== "" || mm !== "" || yyyy !== "";
3176
+ const ddRef = useRef(null);
3177
+ const mmRef = useRef(null);
3178
+ const yyyyRef = useRef(null);
3179
+ const inputRefs = [
3180
+ ddRef,
3181
+ mmRef,
3182
+ yyyyRef
3183
+ ];
3184
+ const clearButtonRef = useRef(null);
3185
+ const [isClearButtonFocused, setIsClearButtonFocused] = useState(false);
3186
+ useEffect(() => {
3187
+ if (!value || value === "") return;
3188
+ const match = value.match(/^(\d{2})\.(\d{2})\.(\d{4})$/);
3189
+ if (match) {
3190
+ const [_, newDd, newMm, newYyyy] = match;
3191
+ if (dd !== newDd) setDd(newDd);
3192
+ if (mm !== newMm) setMm(newMm);
3193
+ if (yyyy !== newYyyy) setYyyy(newYyyy);
3194
+ }
3195
+ }, [value]);
3196
+ const combinedValue = dd && mm && yyyy ? `${dd}.${mm}.${yyyy}` : "";
3197
+ useEffect(() => {
3198
+ if (onChange) onChange(combinedValue);
3199
+ }, [combinedValue]);
3200
+ const validateDd = (newDd) => {
3201
+ if (newDd === "") {
3202
+ setErrorTextDd("");
3203
+ return true;
3204
+ }
3205
+ if (/^\d{0,2}$/.test(newDd)) {
3206
+ const dayNum = parseInt(newDd, 10);
3207
+ if (dayNum < 0 || dayNum > 31) {
3208
+ setErrorTextDd(resources?.validateDefaultMessageDay || "Dag må være et tall mellom 01 og 31");
3209
+ return false;
3210
+ } else {
3211
+ setErrorTextDd("");
3212
+ return true;
3213
+ }
3214
+ } else {
3215
+ setErrorTextDd(resources?.validateDefaultMessageDay || "Dag må være et tall mellom 01 og 31");
3216
+ return false;
3217
+ }
3218
+ };
3219
+ const handleDdChange = (e) => {
3220
+ const newDd = e.target.value;
3221
+ setDd(newDd);
3222
+ if (validateDd(newDd)) {
3223
+ if (newDd.length === 2) mmRef.current?.focus();
3224
+ }
3225
+ };
3226
+ const validateMm = (newMm) => {
3227
+ if (newMm === "") {
3228
+ setErrorTextMm("");
3229
+ return true;
3230
+ }
3231
+ if (/^\d{0,2}$/.test(newMm)) {
3232
+ const dayNum = parseInt(newMm, 10);
3233
+ if (dayNum < 0 || dayNum > 12) {
3234
+ setErrorTextMm(resources?.validateDefaultMessageMonth || "Måned må være et tall mellom 01 og 12");
3235
+ return false;
3236
+ } else {
3237
+ setErrorTextMm("");
3238
+ return true;
3239
+ }
3240
+ } else {
3241
+ setErrorTextMm(resources?.validateDefaultMessageMonth || "Måned må være et tall mellom 01 og 12");
3242
+ return false;
3243
+ }
3244
+ };
3245
+ const handleMmChange = (e) => {
3246
+ const newMm = e.target.value;
3247
+ setMm(newMm);
3248
+ if (validateMm(newMm)) {
3249
+ if (newMm.length === 2) yyyyRef.current?.focus();
3250
+ }
3251
+ };
3252
+ const validateYyyy = (newYyyy, strict) => {
3253
+ if (newYyyy === "") {
3254
+ setErrorTextYyyy("");
3255
+ return true;
3256
+ }
3257
+ if (/^\d{0,4}$/.test(newYyyy)) {
3258
+ const dayNum = parseInt(newYyyy, 10);
3259
+ let minValue = 0;
3260
+ if (strict) minValue = 1e3;
3261
+ if (dayNum < minValue || dayNum > 9999) {
3262
+ setErrorTextYyyy(resources?.validateDefaultMessageYear || "År må være et tall med 4 siffer");
3263
+ return false;
3264
+ } else {
3265
+ setErrorTextYyyy("");
3266
+ return true;
3267
+ }
3268
+ } else {
3269
+ setErrorTextYyyy(resources?.validateDefaultMessageYear || "År må være et tall med 4 siffer");
3270
+ return false;
3271
+ }
3272
+ };
3273
+ const handleYyyyChange = (e) => {
3274
+ const newYyyy = e.target.value;
3275
+ setYyyy(newYyyy);
3276
+ validateYyyy(newYyyy);
3277
+ };
3278
+ const handleBlurOnSegment = () => {
3279
+ validateDd(dd);
3280
+ validateMm(mm);
3281
+ validateYyyy(yyyy, true);
3282
+ };
3283
+ useEffect(() => {
3284
+ const combinedErrors = [
3285
+ errorTextDd,
3286
+ errorTextMm,
3287
+ errorTextYyyy
3288
+ ].filter((err) => err !== "").join(". ");
3289
+ if (setErrorText) setErrorText(combinedErrors);
3290
+ }, [
3291
+ errorTextDd,
3292
+ errorTextMm,
3293
+ errorTextYyyy
3294
+ ]);
3295
+ const segmentClass = styles["date-segment"];
3296
+ const errorClass = styles["date-segment--error"];
3297
+ const daySegmentClassNames = classNames(segmentClass, errorTextDd && errorClass);
3298
+ const monthSegmentClassNames = classNames(segmentClass, errorTextMm && errorClass);
3299
+ const yearSegmentClassNames = classNames(segmentClass, errorTextYyyy && errorClass, styles["date-segment--year"]);
3300
+ const handleGroupBlur = () => {
3301
+ setTimeout(() => {
3302
+ if (!inputRefs.some((ref) => ref.current && ref.current === document.activeElement)) onBlur?.(combinedValue);
3303
+ }, 0);
3304
+ };
3305
+ const handleGroupClick = () => {
3306
+ if (ddRef.current && document.activeElement !== ddRef.current && mmRef.current && document.activeElement !== mmRef.current && yyyyRef.current && document.activeElement !== yyyyRef.current && document.activeElement !== clearButtonRef.current) if (dd === "") ddRef.current.focus();
3307
+ else if (mm === "") mmRef.current.focus();
3308
+ else yyyyRef.current.focus();
3309
+ };
3310
+ const handleClear = () => {
3311
+ setDd("");
3312
+ setMm("");
3313
+ setYyyy("");
3314
+ setErrorTextDd("");
3315
+ setErrorTextMm("");
3316
+ setErrorTextYyyy("");
3317
+ if (onChange) onChange("");
3318
+ ddRef.current?.focus();
3319
+ };
3320
+ const moveFocusLeft = () => {
3321
+ const activeElement$1 = document.activeElement;
3322
+ if (!activeElement$1) return;
3323
+ if (mmRef.current === activeElement$1) {
3324
+ if (activeElement$1.selectionStart === 0 && activeElement$1.selectionEnd === 0) setTimeout(() => {
3325
+ ddRef.current?.focus();
3326
+ }, 0);
3327
+ } else if (yyyyRef.current === activeElement$1) {
3328
+ if (activeElement$1.selectionStart === 0 && activeElement$1.selectionEnd === 0) setTimeout(() => {
3329
+ mmRef.current?.focus();
3330
+ }, 0);
3331
+ }
3332
+ };
3333
+ const moveFocusRight = () => {
3334
+ const activeElement$1 = document.activeElement;
3335
+ if (!activeElement$1) return;
3336
+ if (mmRef.current === activeElement$1) {
3337
+ if (activeElement$1.selectionStart === activeElement$1.value.length && activeElement$1.selectionEnd === activeElement$1.value.length) setTimeout(() => {
3338
+ yyyyRef.current?.focus();
3339
+ }, 0);
3340
+ } else if (ddRef.current === activeElement$1) {
3341
+ if (activeElement$1.selectionStart === activeElement$1.value.length && activeElement$1.selectionEnd === activeElement$1.value.length) setTimeout(() => {
3342
+ mmRef.current?.focus();
3343
+ }, 0);
3344
+ }
3345
+ };
3346
+ const moveFocusOnBackspaceInEmptyField = () => {
3347
+ if (yyyyRef.current === document.activeElement && yyyy === "") setTimeout(() => {
3348
+ mmRef.current?.focus();
3349
+ }, 0);
3350
+ else if (mmRef.current === document.activeElement && mm === "") setTimeout(() => {
3351
+ ddRef.current?.focus();
3352
+ }, 0);
3353
+ };
3354
+ useKeyboardEvent(yyyyRef, moveFocusOnBackspaceInEmptyField, [KeyboardEventKey.Backspace]);
3355
+ useKeyboardEvent(mmRef, moveFocusOnBackspaceInEmptyField, [KeyboardEventKey.Backspace]);
3356
+ useKeyboardEvent(mmRef, moveFocusLeft, [KeyboardEventKey.ArrowLeft]);
3357
+ useKeyboardEvent(yyyyRef, moveFocusLeft, [KeyboardEventKey.ArrowLeft]);
3358
+ useKeyboardEvent(ddRef, moveFocusRight, [KeyboardEventKey.ArrowRight]);
3359
+ useKeyboardEvent(mmRef, moveFocusRight, [KeyboardEventKey.ArrowRight]);
3360
+ return /* @__PURE__ */ jsx(Fragment, { children: /* @__PURE__ */ jsxs("div", {
3361
+ role: "group",
3362
+ className: classNames(styles["date-picker"], {
3363
+ [styles["date-picker--with-clear-button"]]: withClearButton,
3364
+ [styles["date-picker--clear-button-focused"]]: isClearButtonFocused
3365
+ }),
3366
+ id: inputId,
3367
+ "aria-labelledby": ariaLabelledBy ?? legendId,
3368
+ "aria-describedby": ariaDescribedBy,
3369
+ onBlurCapture: handleGroupBlur,
3370
+ onClickCapture: handleGroupClick,
3371
+ children: [/* @__PURE__ */ jsxs("span", {
3372
+ className: styles["date-picker__inputs"],
3373
+ children: [
3374
+ /* @__PURE__ */ jsx("input", {
3375
+ ref: ddRef,
3376
+ type: "text",
3377
+ enterKeyHint: "next",
3378
+ inputMode: "numeric",
3379
+ pattern: "[0-9]*",
3380
+ maxLength: 2,
3381
+ value: dd,
3382
+ onChange: handleDdChange,
3383
+ onBlur: handleBlurOnSegment,
3384
+ placeholder: resources?.dayFormatPlaceholder || "dd",
3385
+ "aria-label": resources?.ariaLabelInputDay || "Dag",
3386
+ className: daySegmentClassNames
3387
+ }),
3388
+ /* @__PURE__ */ jsx("span", {
3389
+ "aria-hidden": true,
3390
+ children: "."
3391
+ }),
3392
+ /* @__PURE__ */ jsx("input", {
3393
+ ref: mmRef,
3394
+ type: "text",
3395
+ enterKeyHint: "next",
3396
+ inputMode: "numeric",
3397
+ pattern: "[0-9]*",
3398
+ maxLength: 2,
3399
+ value: mm,
3400
+ onChange: handleMmChange,
3401
+ onBlur: handleBlurOnSegment,
3402
+ placeholder: resources?.monthFormatPlaceholder || "mm",
3403
+ "aria-label": resources?.ariaLabelInputMonth || "Måned",
3404
+ className: monthSegmentClassNames
3405
+ }),
3406
+ /* @__PURE__ */ jsx("span", {
3407
+ "aria-hidden": true,
3408
+ children: "."
3409
+ }),
3410
+ /* @__PURE__ */ jsx("input", {
3411
+ ref: yyyyRef,
3412
+ type: "text",
3413
+ enterKeyHint: "next",
3414
+ inputMode: "numeric",
3415
+ pattern: "[0-9]*",
3416
+ maxLength: 4,
3417
+ value: yyyy,
3418
+ onChange: handleYyyyChange,
3419
+ onBlur: handleBlurOnSegment,
3420
+ placeholder: resources?.yearFormatPlaceholder || "åååå",
3421
+ "aria-label": resources?.ariaLabelInputYear || "År",
3422
+ className: yearSegmentClassNames
3423
+ })
3424
+ ]
3425
+ }), withClearButton && (hasValue ? /* @__PURE__ */ jsx("button", {
3426
+ type: "button",
3427
+ onClick: handleClear,
3428
+ onFocus: () => setIsClearButtonFocused(true),
3429
+ onBlur: () => setIsClearButtonFocused(false),
3430
+ ref: clearButtonRef,
3431
+ className: styles["clear-button"],
3432
+ "aria-label": resources?.clearButtonAriaLabel || "Nullstill dato",
3433
+ children: /* @__PURE__ */ jsx(Icon, {
3434
+ svgIcon: X,
3435
+ size: IconSize.XXSmall
3436
+ })
3437
+ }) : /* @__PURE__ */ jsx("div", { className: styles["clear-button__placeholder"] }))]
3438
+ }) });
3439
+ };
3440
+ DateInputInternal.displayName = "DateInputInternal";
3441
+ var DateInputInternal_default = DateInputInternal;
3442
+ var Unsafe_DatePicker = ({ value, onChange, onBlur, label, id, errorText, withClearButton = true, ["aria-describedby"]: ariaDescribedBy, ["aria-labelledby"]: ariaLabelledBy, resources, ...baseDayPickerProps }) => {
3443
+ const dateToString = (date) => {
3444
+ if (!isValid(date) || !date) return "";
3445
+ return format(date, "P", { locale: nb });
3446
+ };
3447
+ const [dateString, setDateString] = useState(dateToString(value) || "");
3448
+ const [dateDate, setDateDate] = useState(value || void 0);
3449
+ const [softErrorText, setSoftErrorText] = useState("");
3450
+ const containerRef = useRef(null);
3451
+ const calendarButtonRef = useRef(null);
3452
+ const internalChangeRef = useRef(false);
3453
+ useEffect(() => {
3454
+ if (!internalChangeRef.current) {
3455
+ setDateString(dateToString(value) || "");
3456
+ setDateDate(value || void 0);
3457
+ }
3458
+ internalChangeRef.current = false;
3459
+ }, [value]);
3460
+ const { language } = useLanguage(LanguageLocales.NORWEGIAN);
3461
+ const mergedResources = {
3462
+ ...getResources(language),
3463
+ ...resources
3464
+ };
3465
+ const { value: isPopupOpen, toggleValue: toggleIsPopupOpen } = useToggle(false);
3466
+ const { refs, floatingStyles, context, middlewareData } = useFloating({
3467
+ placement: "bottom-start",
3468
+ middleware: [offset(8), shift({
3469
+ mainAxis: false,
3470
+ padding: 8
3471
+ })],
3472
+ whileElementsMounted: autoUpdate,
3473
+ elements: { reference: containerRef.current }
3474
+ });
3475
+ const dayPickerPopupRef = useRef(null);
3476
+ const { getFloatingProps } = useInteractions([useClick(context), useDismiss(context)]);
3477
+ const isVisible = isPopupOpen && !middlewareData.hide?.referenceHidden;
3478
+ const setFocusToCalendarButton = () => {
3479
+ calendarButtonRef.current?.focus();
3480
+ };
3481
+ const handleDayPickerSelect = (date) => {
3482
+ internalChangeRef.current = true;
3483
+ if (!date) {
3484
+ setDateString("");
3485
+ setDateDate(void 0);
3486
+ if (onChange) onChange(void 0);
3487
+ } else {
3488
+ setDateDate(date);
3489
+ setDateString(format(date, "P", { locale: nb }));
3490
+ if (onChange) onChange(date);
3491
+ if (isPopupOpen) toggleIsPopupOpen();
3492
+ setFocusToCalendarButton();
3493
+ }
3494
+ };
3495
+ const handleEscapeKeyDown = () => {
3496
+ if (isPopupOpen) {
3497
+ toggleIsPopupOpen();
3498
+ setFocusToCalendarButton();
3499
+ }
3500
+ };
3501
+ useKeyboardEvent(dayPickerPopupRef, handleEscapeKeyDown, [KeyboardEventKey.Escape]);
3502
+ useKeyboardEvent(calendarButtonRef, handleEscapeKeyDown, [KeyboardEventKey.Escape]);
3503
+ useOutsideEvent([calendarButtonRef, dayPickerPopupRef], (e) => {
3504
+ if (calendarButtonRef.current && dayPickerPopupRef.current && !e?.composedPath().includes(calendarButtonRef.current) && !e?.composedPath().includes(dayPickerPopupRef.current)) {
3505
+ if (isPopupOpen) toggleIsPopupOpen();
3506
+ }
3507
+ }, [
3508
+ "mousedown",
3509
+ "focusin",
3510
+ "blur"
3511
+ ]);
3512
+ const handleInputChange = (date) => {
3513
+ internalChangeRef.current = true;
3514
+ setDateString(date);
3515
+ const parsedDate = parse(date, "P", /* @__PURE__ */ new Date(), { locale: nb });
3516
+ if (isValid(parsedDate)) {
3517
+ setDateDate(parsedDate);
3518
+ if (onChange) onChange(parsedDate);
3519
+ } else {
3520
+ setDateDate(void 0);
3521
+ if (onChange) onChange(void 0);
3522
+ }
3523
+ };
3524
+ const handleBlur = (date) => {
3525
+ const parsedDate = parse(date, "P", /* @__PURE__ */ new Date(), { locale: nb });
3526
+ if (isValid(parsedDate)) {
3527
+ if (onBlur) onBlur(parsedDate);
3528
+ } else if (onBlur) onBlur(void 0);
3529
+ };
3530
+ const labelGivenAsPropIsValidLabelComponent = isComponent(label, Label);
3531
+ const legend = label && labelGivenAsPropIsValidLabelComponent ? cloneElement(label, {
3532
+ htmlMarkup: "legend",
3533
+ labelId: label.props.labelId || "date-legend"
3534
+ }) : null;
3535
+ const legendId = labelGivenAsPropIsValidLabelComponent && label.props.labelId ? label.props.labelId : "date-legend";
3536
+ const popupId = isPopupOpen ? "calendar-popup" : void 0;
3537
+ return /* @__PURE__ */ jsxs(ErrorWrapper, {
3538
+ errorText,
3539
+ children: [/* @__PURE__ */ jsxs("fieldset", {
3540
+ className: styles["date-field"],
3541
+ "aria-labelledby": legendId,
3542
+ children: [
3543
+ legend,
3544
+ /* @__PURE__ */ jsxs("div", {
3545
+ ref: containerRef,
3546
+ children: [/* @__PURE__ */ jsx(DateInputInternal_default, {
3547
+ inputId: id,
3548
+ "aria-describedby": ariaDescribedBy,
3549
+ "aria-labelledby": ariaLabelledBy,
3550
+ value: dateString,
3551
+ onChange: handleInputChange,
3552
+ onBlur: handleBlur,
3553
+ legendId,
3554
+ setErrorText: setSoftErrorText,
3555
+ withClearButton,
3556
+ resources: mergedResources
3557
+ }), /* @__PURE__ */ jsx("button", {
3558
+ type: "button",
3559
+ ref: calendarButtonRef,
3560
+ onClick: toggleIsPopupOpen,
3561
+ "aria-label": mergedResources.calendarButtonAriaLabel,
3562
+ "aria-controls": popupId,
3563
+ "aria-expanded": isPopupOpen,
3564
+ className: styles["calendar-button"],
3565
+ children: /* @__PURE__ */ jsx(Icon, {
3566
+ svgIcon: Calendar,
3567
+ size: IconSize$1.XSmall
3568
+ })
3569
+ })]
3570
+ }),
3571
+ /* @__PURE__ */ jsx("div", {
3572
+ className: styles["date-field__soft-error-text"],
3573
+ role: "status",
3574
+ children: softErrorText
3575
+ })
3576
+ ]
3577
+ }), isPopupOpen && /* @__PURE__ */ jsx(FloatingFocusManager, {
3578
+ context,
3579
+ modal: false,
3580
+ children: /* @__PURE__ */ jsx("div", {
3581
+ id: popupId,
3582
+ ref: mergeRefs([refs.setFloating, dayPickerPopupRef]),
3583
+ style: {
3584
+ ...floatingStyles,
3585
+ visibility: isVisible ? "visible" : "hidden",
3586
+ zIndex: 1e4
3587
+ },
3588
+ ...getFloatingProps(),
3589
+ children: /* @__PURE__ */ jsx(BaseDayPicker_default, {
3590
+ ...baseDayPickerProps,
3591
+ resources: mergedResources,
3592
+ selectedDate: dateDate,
3593
+ onDateChange: handleDayPickerSelect
3594
+ })
3595
+ })
3596
+ })]
3597
+ });
3598
+ };
3599
+ Unsafe_DatePicker.displayName = "DateInput";
3600
+ var Unsafe_DatePicker_default = Unsafe_DatePicker;
3601
+ var toTimeString = (date) => {
3602
+ if (!date || !isValid(date)) return;
3603
+ return `${date.getHours().toString().padStart(2, "0")}:${date.getMinutes().toString().padStart(2, "0")}`;
3604
+ };
3605
+ var mergeDateAndTime = (date, time) => {
3606
+ if (!date || !isValid(date)) return;
3607
+ const merged = new Date(date);
3608
+ if (!time) {
3609
+ merged.setHours(0, 0, 0, 0);
3610
+ return merged;
3611
+ }
3612
+ const [hoursStr, minutesStr] = time.split(":");
3613
+ const hours = parseInt(hoursStr, 10);
3614
+ const minutes = parseInt(minutesStr, 10);
3615
+ if (isNaN(hours) || isNaN(minutes)) {
3616
+ merged.setHours(0, 0, 0, 0);
3617
+ return merged;
3618
+ }
3619
+ merged.setHours(hours, minutes, 0, 0);
3620
+ return merged;
3621
+ };
3622
+ var Unsafe_DateAndTime = ({ value, onChange, legend, errorText, datepickerProps, timeInputProps }) => {
3623
+ const internalDate = value;
3624
+ const hasMeaningfulTime = (date) => {
3625
+ if (!date) return false;
3626
+ return date.getHours() !== 0 || date.getMinutes() !== 0;
3627
+ };
3628
+ const [internalTime, setInternalTime] = useState(hasMeaningfulTime(value) ? toTimeString(value) : void 0);
3629
+ const isTypingTimeRef = useRef(false);
3630
+ const hasUserTimeRef = useRef(hasMeaningfulTime(value));
3631
+ useEffect(() => {
3632
+ if (!isTypingTimeRef.current && hasUserTimeRef.current) {
3633
+ const newTimeString = toTimeString(value);
3634
+ if (hasMeaningfulTime(value)) setInternalTime(newTimeString);
3635
+ }
3636
+ isTypingTimeRef.current = false;
3637
+ }, [value]);
3638
+ const handleDateChange = (newDate) => {
3639
+ const merged = mergeDateAndTime(newDate, internalTime);
3640
+ onChange?.(merged);
3641
+ };
3642
+ const handleTimeChange = (newTime) => {
3643
+ hasUserTimeRef.current = !!newTime;
3644
+ isTypingTimeRef.current = true;
3645
+ setInternalTime(newTime);
3646
+ const merged = mergeDateAndTime(value, newTime);
3647
+ onChange?.(merged);
3648
+ };
3649
+ return /* @__PURE__ */ jsx(ErrorWrapper, {
3650
+ errorText,
3651
+ children: /* @__PURE__ */ jsxs("fieldset", {
3652
+ className: styles$1["date-and-time--fieldset"],
3653
+ children: [legend, /* @__PURE__ */ jsxs("div", {
3654
+ className: styles$1["date-and-time__fields"],
3655
+ children: [/* @__PURE__ */ jsx(Unsafe_DatePicker_default, {
3656
+ ...datepickerProps,
3657
+ value: internalDate,
3658
+ onChange: handleDateChange
3659
+ }), /* @__PURE__ */ jsx(Unsafe_TimeInput_default, {
3660
+ ...timeInputProps,
3661
+ value: internalTime,
3662
+ onChange: handleTimeChange
3663
+ })]
3664
+ })]
3665
+ })
3666
+ });
3667
+ };
3668
+ var Unsafe_DateAndTime_default = Unsafe_DateAndTime;
3669
+ var Unsafe_ISODatePicker = ({ value, onChange, ...baseDateInputProps }) => {
3670
+ const [internalDate, setInternalDate] = useState(value ? new Date(value) : void 0);
3671
+ const dateToIso = (date) => {
3672
+ if (!isValid(date) || !date) return "";
3673
+ return formatISO(date, { representation: "date" });
3674
+ };
3675
+ const isoToDate = (iso) => {
3676
+ const date = new Date(iso);
3677
+ if (!isValid(date)) return;
3678
+ return date;
3679
+ };
3680
+ useEffect(() => {
3681
+ if (value) setInternalDate(isoToDate(value));
3682
+ else setInternalDate(void 0);
3683
+ }, [value]);
3684
+ useEffect(() => {
3685
+ if (!internalDate) {
3686
+ onChange?.("");
3687
+ return;
3688
+ }
3689
+ const iso = dateToIso(internalDate);
3690
+ onChange?.(iso);
3691
+ }, [internalDate]);
3692
+ return /* @__PURE__ */ jsx(Unsafe_DatePicker_default, {
3693
+ ...baseDateInputProps,
3694
+ value: internalDate,
3695
+ onChange: setInternalDate
3696
+ });
3697
+ };
3698
+ var Unsafe_ISODatePicker_default = Unsafe_ISODatePicker;
3699
+ var Unsafe_DatePicker_default$1 = Unsafe_DatePicker_default;
3700
+ export { Unsafe_DateAndTime_default as Unsafe_DateAndTime, Unsafe_DatePicker_default as Unsafe_DatePicker, BaseDayPicker_default as Unsafe_DatePickerStandalone, Unsafe_ISODatePicker_default as Unsafe_ISODatePicker, Unsafe_TimeInput_default as Unsafe_TimeInput, Unsafe_DatePicker_default$1 as default };
3701
+
3702
+ //# sourceMappingURL=index.js.map