"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __publicField = (obj, key, value) => {
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
return value;
};
var __accessCheck = (obj, member, msg) => {
if (!member.has(obj))
throw TypeError("Cannot " + msg);
};
var __privateGet = (obj, member, getter) => {
__accessCheck(obj, member, "read from private field");
return getter ? getter.call(obj) : member.get(obj);
};
var __privateAdd = (obj, member, value) => {
if (member.has(obj))
throw TypeError("Cannot add the same private member more than once");
member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
};
var __privateSet = (obj, member, value, setter) => {
__accessCheck(obj, member, "write to private field");
setter ? setter.call(obj, value) : member.set(obj, value);
return value;
};
// src/index.ts
var src_exports = {};
__export(src_exports, {
Button: () => Button,
Checkbox: () => Checkbox,
CloseButton: () => CloseButton,
Combobox: () => Combobox,
ComboboxButton: () => ComboboxButton,
ComboboxInput: () => ComboboxInput,
ComboboxLabel: () => ComboboxLabel,
ComboboxOption: () => ComboboxOption,
ComboboxOptions: () => ComboboxOptions,
DataInteractive: () => DataInteractive,
Description: () => Description,
Dialog: () => Dialog,
DialogBackdrop: () => DialogBackdrop,
DialogDescription: () => DialogDescription,
DialogPanel: () => DialogPanel,
DialogTitle: () => DialogTitle,
Disclosure: () => Disclosure,
DisclosureButton: () => DisclosureButton,
DisclosurePanel: () => DisclosurePanel,
Field: () => Field,
Fieldset: () => Fieldset,
FocusTrap: () => FocusTrap,
FocusTrapFeatures: () => FocusTrapFeatures,
Input: () => Input,
Label: () => Label,
Legend: () => Legend,
Listbox: () => Listbox,
ListboxButton: () => ListboxButton,
ListboxLabel: () => ListboxLabel,
ListboxOption: () => ListboxOption,
ListboxOptions: () => ListboxOptions,
ListboxSelectedOption: () => ListboxSelectedOption,
Menu: () => Menu,
MenuButton: () => MenuButton,
MenuHeading: () => MenuHeading,
MenuItem: () => MenuItem,
MenuItems: () => MenuItems,
MenuSection: () => MenuSection,
MenuSeparator: () => MenuSeparator,
Popover: () => Popover,
PopoverBackdrop: () => PopoverBackdrop,
PopoverButton: () => PopoverButton,
PopoverGroup: () => PopoverGroup,
PopoverOverlay: () => PopoverOverlay,
PopoverPanel: () => PopoverPanel,
Portal: () => Portal,
Radio: () => Radio,
RadioGroup: () => RadioGroup,
RadioGroupDescription: () => RadioGroupDescription,
RadioGroupLabel: () => RadioGroupLabel,
RadioGroupOption: () => RadioGroupOption,
Select: () => Select,
Switch: () => Switch,
SwitchDescription: () => SwitchDescription,
SwitchGroup: () => SwitchGroup,
SwitchLabel: () => SwitchLabel,
Tab: () => Tab,
TabGroup: () => TabGroup,
TabList: () => TabList,
TabPanel: () => TabPanel,
TabPanels: () => TabPanels,
Textarea: () => Textarea,
Transition: () => Transition,
TransitionChild: () => TransitionChild,
useClose: () => useClose
});
module.exports = __toCommonJS(src_exports);
// ../../node_modules/@react-aria/utils/dist/useLayoutEffect.mjs
var import_react = __toESM(require("react"), 1);
var $f0a04ccd8dbdd83b$export$e5c5a5f917a5871c = typeof document !== "undefined" ? (0, import_react.default).useLayoutEffect : () => {
};
// ../../node_modules/@react-aria/utils/dist/useEffectEvent.mjs
var import_react2 = require("react");
function $8ae05eaa5c114e9c$export$7f54fc3180508a52(fn) {
const ref = (0, import_react2.useRef)(null);
(0, $f0a04ccd8dbdd83b$export$e5c5a5f917a5871c)(() => {
ref.current = fn;
}, [
fn
]);
return (0, import_react2.useCallback)((...args) => {
const f = ref.current;
return f === null || f === void 0 ? void 0 : f(...args);
}, []);
}
// ../../node_modules/@react-aria/utils/dist/domHelpers.mjs
var $431fbd86ca7dc216$export$b204af158042fbac = (el) => {
var _el_ownerDocument;
return (_el_ownerDocument = el === null || el === void 0 ? void 0 : el.ownerDocument) !== null && _el_ownerDocument !== void 0 ? _el_ownerDocument : document;
};
var $431fbd86ca7dc216$export$f21a1ffae260145a = (el) => {
if (el && "window" in el && el.window === el)
return el;
const doc = $431fbd86ca7dc216$export$b204af158042fbac(el);
return doc.defaultView || window;
};
function $431fbd86ca7dc216$var$isNode(value) {
return value !== null && typeof value === "object" && "nodeType" in value && typeof value.nodeType === "number";
}
function $431fbd86ca7dc216$export$af51f0f06c0f328a(node) {
return $431fbd86ca7dc216$var$isNode(node) && node.nodeType === Node.DOCUMENT_FRAGMENT_NODE && "host" in node;
}
// ../../node_modules/@react-stately/flags/dist/import.mjs
var $f4e2df6bd15f8569$var$_shadowDOM = false;
function $f4e2df6bd15f8569$export$98658e8c59125e6a() {
return $f4e2df6bd15f8569$var$_shadowDOM;
}
// ../../node_modules/@react-aria/utils/dist/DOMFunctions.mjs
function $d4ee10de306f2510$export$4282f70798064fe0(node, otherNode) {
if (!(0, $f4e2df6bd15f8569$export$98658e8c59125e6a)())
return otherNode && node ? node.contains(otherNode) : false;
if (!node || !otherNode)
return false;
let currentNode = otherNode;
while (currentNode !== null) {
if (currentNode === node)
return true;
if (currentNode.tagName === "SLOT" && currentNode.assignedSlot)
currentNode = currentNode.assignedSlot.parentNode;
else if ((0, $431fbd86ca7dc216$export$af51f0f06c0f328a)(currentNode))
currentNode = currentNode.host;
else
currentNode = currentNode.parentNode;
}
return false;
}
var $d4ee10de306f2510$export$cd4e5573fbe2b576 = (doc = document) => {
var _activeElement_shadowRoot;
if (!(0, $f4e2df6bd15f8569$export$98658e8c59125e6a)())
return doc.activeElement;
let activeElement2 = doc.activeElement;
while (activeElement2 && "shadowRoot" in activeElement2 && ((_activeElement_shadowRoot = activeElement2.shadowRoot) === null || _activeElement_shadowRoot === void 0 ? void 0 : _activeElement_shadowRoot.activeElement))
activeElement2 = activeElement2.shadowRoot.activeElement;
return activeElement2;
};
function $d4ee10de306f2510$export$e58f029f0fbfdb29(event) {
if ((0, $f4e2df6bd15f8569$export$98658e8c59125e6a)() && event.target.shadowRoot) {
if (event.composedPath)
return event.composedPath()[0];
}
return event.target;
}
// ../../node_modules/@react-aria/utils/dist/platform.mjs
function $c87311424ea30a05$var$testUserAgent(re) {
var _window_navigator_userAgentData;
if (typeof window === "undefined" || window.navigator == null)
return false;
return ((_window_navigator_userAgentData = window.navigator["userAgentData"]) === null || _window_navigator_userAgentData === void 0 ? void 0 : _window_navigator_userAgentData.brands.some((brand) => re.test(brand.brand))) || re.test(window.navigator.userAgent);
}
function $c87311424ea30a05$var$testPlatform(re) {
var _window_navigator_userAgentData;
return typeof window !== "undefined" && window.navigator != null ? re.test(((_window_navigator_userAgentData = window.navigator["userAgentData"]) === null || _window_navigator_userAgentData === void 0 ? void 0 : _window_navigator_userAgentData.platform) || window.navigator.platform) : false;
}
function $c87311424ea30a05$var$cached(fn) {
if (false)
return fn;
let res = null;
return () => {
if (res == null)
res = fn();
return res;
};
}
var $c87311424ea30a05$export$9ac100e40613ea10 = $c87311424ea30a05$var$cached(function() {
return $c87311424ea30a05$var$testPlatform(/^Mac/i);
});
var $c87311424ea30a05$export$186c6964ca17d99 = $c87311424ea30a05$var$cached(function() {
return $c87311424ea30a05$var$testPlatform(/^iPhone/i);
});
var $c87311424ea30a05$export$7bef049ce92e4224 = $c87311424ea30a05$var$cached(function() {
return $c87311424ea30a05$var$testPlatform(/^iPad/i) || // iPadOS 13 lies and says it's a Mac, but we can distinguish by detecting touch support.
$c87311424ea30a05$export$9ac100e40613ea10() && navigator.maxTouchPoints > 1;
});
var $c87311424ea30a05$export$fedb369cb70207f1 = $c87311424ea30a05$var$cached(function() {
return $c87311424ea30a05$export$186c6964ca17d99() || $c87311424ea30a05$export$7bef049ce92e4224();
});
var $c87311424ea30a05$export$e1865c3bedcd822b = $c87311424ea30a05$var$cached(function() {
return $c87311424ea30a05$export$9ac100e40613ea10() || $c87311424ea30a05$export$fedb369cb70207f1();
});
var $c87311424ea30a05$export$78551043582a6a98 = $c87311424ea30a05$var$cached(function() {
return $c87311424ea30a05$var$testUserAgent(/AppleWebKit/i) && !$c87311424ea30a05$export$6446a186d09e379e();
});
var $c87311424ea30a05$export$6446a186d09e379e = $c87311424ea30a05$var$cached(function() {
return $c87311424ea30a05$var$testUserAgent(/Chrome/i);
});
var $c87311424ea30a05$export$a11b0059900ceec8 = $c87311424ea30a05$var$cached(function() {
return $c87311424ea30a05$var$testUserAgent(/Android/i);
});
var $c87311424ea30a05$export$b7d78993b74f766d = $c87311424ea30a05$var$cached(function() {
return $c87311424ea30a05$var$testUserAgent(/Firefox/i);
});
// ../../node_modules/@react-aria/utils/dist/useGlobalListeners.mjs
var import_react3 = require("react");
function $03deb23ff14920c4$export$4eaf04e54aa8eed6() {
let globalListeners = (0, import_react3.useRef)(/* @__PURE__ */ new Map());
let addGlobalListener = (0, import_react3.useCallback)((eventTarget, type, listener, options) => {
let fn = (options === null || options === void 0 ? void 0 : options.once) ? (...args) => {
globalListeners.current.delete(listener);
listener(...args);
} : listener;
globalListeners.current.set(listener, {
type,
eventTarget,
fn,
options
});
eventTarget.addEventListener(type, fn, options);
}, []);
let removeGlobalListener = (0, import_react3.useCallback)((eventTarget, type, listener, options) => {
var _globalListeners_current_get;
let fn = ((_globalListeners_current_get = globalListeners.current.get(listener)) === null || _globalListeners_current_get === void 0 ? void 0 : _globalListeners_current_get.fn) || listener;
eventTarget.removeEventListener(type, fn, options);
globalListeners.current.delete(listener);
}, []);
let removeAllGlobalListeners = (0, import_react3.useCallback)(() => {
globalListeners.current.forEach((value, key) => {
removeGlobalListener(value.eventTarget, value.type, key, value.options);
});
}, [
removeGlobalListener
]);
(0, import_react3.useEffect)(() => {
return removeAllGlobalListeners;
}, [
removeAllGlobalListeners
]);
return {
addGlobalListener,
removeGlobalListener,
removeAllGlobalListeners
};
}
// ../../node_modules/@react-aria/utils/dist/isVirtualEvent.mjs
function $6a7db85432448f7f$export$60278871457622de(event) {
if (event.mozInputSource === 0 && event.isTrusted)
return true;
if ((0, $c87311424ea30a05$export$a11b0059900ceec8)() && event.pointerType)
return event.type === "click" && event.buttons === 1;
return event.detail === 0 && !event.pointerType;
}
// ../../node_modules/@react-aria/interactions/dist/utils.mjs
var import_react4 = require("react");
function $8a9cb279dc87e130$export$525bc4921d56d4a(nativeEvent) {
let event = nativeEvent;
event.nativeEvent = nativeEvent;
event.isDefaultPrevented = () => event.defaultPrevented;
event.isPropagationStopped = () => event.cancelBubble;
event.persist = () => {
};
return event;
}
function $8a9cb279dc87e130$export$c2b7abe5d61ec696(event, target) {
Object.defineProperty(event, "target", {
value: target
});
Object.defineProperty(event, "currentTarget", {
value: target
});
}
function $8a9cb279dc87e130$export$715c682d09d639cc(onBlur) {
let stateRef = (0, import_react4.useRef)({
isFocused: false,
observer: null
});
(0, $f0a04ccd8dbdd83b$export$e5c5a5f917a5871c)(() => {
const state = stateRef.current;
return () => {
if (state.observer) {
state.observer.disconnect();
state.observer = null;
}
};
}, []);
let dispatchBlur = (0, $8ae05eaa5c114e9c$export$7f54fc3180508a52)((e) => {
onBlur === null || onBlur === void 0 ? void 0 : onBlur(e);
});
return (0, import_react4.useCallback)((e) => {
if (e.target instanceof HTMLButtonElement || e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement || e.target instanceof HTMLSelectElement) {
stateRef.current.isFocused = true;
let target = e.target;
let onBlurHandler = (e2) => {
stateRef.current.isFocused = false;
if (target.disabled) {
let event = $8a9cb279dc87e130$export$525bc4921d56d4a(e2);
dispatchBlur(event);
}
if (stateRef.current.observer) {
stateRef.current.observer.disconnect();
stateRef.current.observer = null;
}
};
target.addEventListener("focusout", onBlurHandler, {
once: true
});
stateRef.current.observer = new MutationObserver(() => {
if (stateRef.current.isFocused && target.disabled) {
var _stateRef_current_observer;
(_stateRef_current_observer = stateRef.current.observer) === null || _stateRef_current_observer === void 0 ? void 0 : _stateRef_current_observer.disconnect();
let relatedTargetEl = target === document.activeElement ? null : document.activeElement;
target.dispatchEvent(new FocusEvent("blur", {
relatedTarget: relatedTargetEl
}));
target.dispatchEvent(new FocusEvent("focusout", {
bubbles: true,
relatedTarget: relatedTargetEl
}));
}
});
stateRef.current.observer.observe(target, {
attributes: true,
attributeFilter: [
"disabled"
]
});
}
}, [
dispatchBlur
]);
}
var $8a9cb279dc87e130$export$fda7da73ab5d4c48 = false;
// ../../node_modules/@react-aria/interactions/dist/useFocusVisible.mjs
var import_react5 = require("react");
var $507fabe10e71c6fb$var$currentModality = null;
var $507fabe10e71c6fb$var$changeHandlers = /* @__PURE__ */ new Set();
var $507fabe10e71c6fb$export$d90243b58daecda7 = /* @__PURE__ */ new Map();
var $507fabe10e71c6fb$var$hasEventBeforeFocus = false;
var $507fabe10e71c6fb$var$hasBlurredWindowRecently = false;
var $507fabe10e71c6fb$var$FOCUS_VISIBLE_INPUT_KEYS = {
Tab: true,
Escape: true
};
function $507fabe10e71c6fb$var$triggerChangeHandlers(modality, e) {
for (let handler of $507fabe10e71c6fb$var$changeHandlers)
handler(modality, e);
}
function $507fabe10e71c6fb$var$isValidKey(e) {
return !(e.metaKey || !(0, $c87311424ea30a05$export$9ac100e40613ea10)() && e.altKey || e.ctrlKey || e.key === "Control" || e.key === "Shift" || e.key === "Meta");
}
function $507fabe10e71c6fb$var$handleKeyboardEvent(e) {
$507fabe10e71c6fb$var$hasEventBeforeFocus = true;
if ($507fabe10e71c6fb$var$isValidKey(e)) {
$507fabe10e71c6fb$var$currentModality = "keyboard";
$507fabe10e71c6fb$var$triggerChangeHandlers("keyboard", e);
}
}
function $507fabe10e71c6fb$var$handlePointerEvent(e) {
$507fabe10e71c6fb$var$currentModality = "pointer";
if (e.type === "mousedown" || e.type === "pointerdown") {
$507fabe10e71c6fb$var$hasEventBeforeFocus = true;
$507fabe10e71c6fb$var$triggerChangeHandlers("pointer", e);
}
}
function $507fabe10e71c6fb$var$handleClickEvent(e) {
if ((0, $6a7db85432448f7f$export$60278871457622de)(e)) {
$507fabe10e71c6fb$var$hasEventBeforeFocus = true;
$507fabe10e71c6fb$var$currentModality = "virtual";
}
}
function $507fabe10e71c6fb$var$handleFocusEvent(e) {
if (e.target === window || e.target === document || (0, $8a9cb279dc87e130$export$fda7da73ab5d4c48) || !e.isTrusted)
return;
if (!$507fabe10e71c6fb$var$hasEventBeforeFocus && !$507fabe10e71c6fb$var$hasBlurredWindowRecently) {
$507fabe10e71c6fb$var$currentModality = "virtual";
$507fabe10e71c6fb$var$triggerChangeHandlers("virtual", e);
}
$507fabe10e71c6fb$var$hasEventBeforeFocus = false;
$507fabe10e71c6fb$var$hasBlurredWindowRecently = false;
}
function $507fabe10e71c6fb$var$handleWindowBlur() {
if (0, $8a9cb279dc87e130$export$fda7da73ab5d4c48)
return;
$507fabe10e71c6fb$var$hasEventBeforeFocus = false;
$507fabe10e71c6fb$var$hasBlurredWindowRecently = true;
}
function $507fabe10e71c6fb$var$setupGlobalFocusEvents(element) {
if (typeof window === "undefined" || $507fabe10e71c6fb$export$d90243b58daecda7.get((0, $431fbd86ca7dc216$export$f21a1ffae260145a)(element)))
return;
const windowObject = (0, $431fbd86ca7dc216$export$f21a1ffae260145a)(element);
const documentObject = (0, $431fbd86ca7dc216$export$b204af158042fbac)(element);
let focus = windowObject.HTMLElement.prototype.focus;
windowObject.HTMLElement.prototype.focus = function() {
$507fabe10e71c6fb$var$hasEventBeforeFocus = true;
focus.apply(this, arguments);
};
documentObject.addEventListener("keydown", $507fabe10e71c6fb$var$handleKeyboardEvent, true);
documentObject.addEventListener("keyup", $507fabe10e71c6fb$var$handleKeyboardEvent, true);
documentObject.addEventListener("click", $507fabe10e71c6fb$var$handleClickEvent, true);
windowObject.addEventListener("focus", $507fabe10e71c6fb$var$handleFocusEvent, true);
windowObject.addEventListener("blur", $507fabe10e71c6fb$var$handleWindowBlur, false);
if (typeof PointerEvent !== "undefined") {
documentObject.addEventListener("pointerdown", $507fabe10e71c6fb$var$handlePointerEvent, true);
documentObject.addEventListener("pointermove", $507fabe10e71c6fb$var$handlePointerEvent, true);
documentObject.addEventListener("pointerup", $507fabe10e71c6fb$var$handlePointerEvent, true);
} else if (false) {
documentObject.addEventListener("mousedown", $507fabe10e71c6fb$var$handlePointerEvent, true);
documentObject.addEventListener("mousemove", $507fabe10e71c6fb$var$handlePointerEvent, true);
documentObject.addEventListener("mouseup", $507fabe10e71c6fb$var$handlePointerEvent, true);
}
windowObject.addEventListener("beforeunload", () => {
$507fabe10e71c6fb$var$tearDownWindowFocusTracking(element);
}, {
once: true
});
$507fabe10e71c6fb$export$d90243b58daecda7.set(windowObject, {
focus
});
}
var $507fabe10e71c6fb$var$tearDownWindowFocusTracking = (element, loadListener) => {
const windowObject = (0, $431fbd86ca7dc216$export$f21a1ffae260145a)(element);
const documentObject = (0, $431fbd86ca7dc216$export$b204af158042fbac)(element);
if (loadListener)
documentObject.removeEventListener("DOMContentLoaded", loadListener);
if (!$507fabe10e71c6fb$export$d90243b58daecda7.has(windowObject))
return;
windowObject.HTMLElement.prototype.focus = $507fabe10e71c6fb$export$d90243b58daecda7.get(windowObject).focus;
documentObject.removeEventListener("keydown", $507fabe10e71c6fb$var$handleKeyboardEvent, true);
documentObject.removeEventListener("keyup", $507fabe10e71c6fb$var$handleKeyboardEvent, true);
documentObject.removeEventListener("click", $507fabe10e71c6fb$var$handleClickEvent, true);
windowObject.removeEventListener("focus", $507fabe10e71c6fb$var$handleFocusEvent, true);
windowObject.removeEventListener("blur", $507fabe10e71c6fb$var$handleWindowBlur, false);
if (typeof PointerEvent !== "undefined") {
documentObject.removeEventListener("pointerdown", $507fabe10e71c6fb$var$handlePointerEvent, true);
documentObject.removeEventListener("pointermove", $507fabe10e71c6fb$var$handlePointerEvent, true);
documentObject.removeEventListener("pointerup", $507fabe10e71c6fb$var$handlePointerEvent, true);
} else if (false) {
documentObject.removeEventListener("mousedown", $507fabe10e71c6fb$var$handlePointerEvent, true);
documentObject.removeEventListener("mousemove", $507fabe10e71c6fb$var$handlePointerEvent, true);
documentObject.removeEventListener("mouseup", $507fabe10e71c6fb$var$handlePointerEvent, true);
}
$507fabe10e71c6fb$export$d90243b58daecda7.delete(windowObject);
};
function $507fabe10e71c6fb$export$2f1888112f558a7d(element) {
const documentObject = (0, $431fbd86ca7dc216$export$b204af158042fbac)(element);
let loadListener;
if (documentObject.readyState !== "loading")
$507fabe10e71c6fb$var$setupGlobalFocusEvents(element);
else {
loadListener = () => {
$507fabe10e71c6fb$var$setupGlobalFocusEvents(element);
};
documentObject.addEventListener("DOMContentLoaded", loadListener);
}
return () => $507fabe10e71c6fb$var$tearDownWindowFocusTracking(element, loadListener);
}
if (typeof document !== "undefined")
$507fabe10e71c6fb$export$2f1888112f558a7d();
function $507fabe10e71c6fb$export$b9b3dfddab17db27() {
return $507fabe10e71c6fb$var$currentModality !== "pointer";
}
var $507fabe10e71c6fb$var$nonTextInputTypes = /* @__PURE__ */ new Set([
"checkbox",
"radio",
"range",
"color",
"file",
"image",
"button",
"submit",
"reset"
]);
function $507fabe10e71c6fb$var$isKeyboardFocusEvent(isTextInput, modality, e) {
let document1 = (0, $431fbd86ca7dc216$export$b204af158042fbac)(e === null || e === void 0 ? void 0 : e.target);
const IHTMLInputElement = typeof window !== "undefined" ? (0, $431fbd86ca7dc216$export$f21a1ffae260145a)(e === null || e === void 0 ? void 0 : e.target).HTMLInputElement : HTMLInputElement;
const IHTMLTextAreaElement = typeof window !== "undefined" ? (0, $431fbd86ca7dc216$export$f21a1ffae260145a)(e === null || e === void 0 ? void 0 : e.target).HTMLTextAreaElement : HTMLTextAreaElement;
const IHTMLElement = typeof window !== "undefined" ? (0, $431fbd86ca7dc216$export$f21a1ffae260145a)(e === null || e === void 0 ? void 0 : e.target).HTMLElement : HTMLElement;
const IKeyboardEvent = typeof window !== "undefined" ? (0, $431fbd86ca7dc216$export$f21a1ffae260145a)(e === null || e === void 0 ? void 0 : e.target).KeyboardEvent : KeyboardEvent;
isTextInput = isTextInput || document1.activeElement instanceof IHTMLInputElement && !$507fabe10e71c6fb$var$nonTextInputTypes.has(document1.activeElement.type) || document1.activeElement instanceof IHTMLTextAreaElement || document1.activeElement instanceof IHTMLElement && document1.activeElement.isContentEditable;
return !(isTextInput && modality === "keyboard" && e instanceof IKeyboardEvent && !$507fabe10e71c6fb$var$FOCUS_VISIBLE_INPUT_KEYS[e.key]);
}
function $507fabe10e71c6fb$export$ec71b4b83ac08ec3(fn, deps, opts) {
$507fabe10e71c6fb$var$setupGlobalFocusEvents();
(0, import_react5.useEffect)(() => {
let handler = (modality, e) => {
if (!$507fabe10e71c6fb$var$isKeyboardFocusEvent(!!(opts === null || opts === void 0 ? void 0 : opts.isTextInput), modality, e))
return;
fn($507fabe10e71c6fb$export$b9b3dfddab17db27());
};
$507fabe10e71c6fb$var$changeHandlers.add(handler);
return () => {
$507fabe10e71c6fb$var$changeHandlers.delete(handler);
};
}, deps);
}
// ../../node_modules/@react-aria/interactions/dist/useFocus.mjs
var import_react6 = require("react");
function $a1ea59d68270f0dd$export$f8168d8dd8fd66e6(props) {
let { isDisabled, onFocus: onFocusProp, onBlur: onBlurProp, onFocusChange } = props;
const onBlur = (0, import_react6.useCallback)((e) => {
if (e.target === e.currentTarget) {
if (onBlurProp)
onBlurProp(e);
if (onFocusChange)
onFocusChange(false);
return true;
}
}, [
onBlurProp,
onFocusChange
]);
const onSyntheticFocus = (0, $8a9cb279dc87e130$export$715c682d09d639cc)(onBlur);
const onFocus = (0, import_react6.useCallback)((e) => {
const ownerDocument = (0, $431fbd86ca7dc216$export$b204af158042fbac)(e.target);
const activeElement2 = ownerDocument ? (0, $d4ee10de306f2510$export$cd4e5573fbe2b576)(ownerDocument) : (0, $d4ee10de306f2510$export$cd4e5573fbe2b576)();
if (e.target === e.currentTarget && activeElement2 === (0, $d4ee10de306f2510$export$e58f029f0fbfdb29)(e.nativeEvent)) {
if (onFocusProp)
onFocusProp(e);
if (onFocusChange)
onFocusChange(true);
onSyntheticFocus(e);
}
}, [
onFocusChange,
onFocusProp,
onSyntheticFocus
]);
return {
focusProps: {
onFocus: !isDisabled && (onFocusProp || onFocusChange || onBlurProp) ? onFocus : void 0,
onBlur: !isDisabled && (onBlurProp || onFocusChange) ? onBlur : void 0
}
};
}
// ../../node_modules/@react-aria/interactions/dist/useFocusWithin.mjs
var import_react7 = require("react");
function $9ab94262bd0047c7$export$420e68273165f4ec(props) {
let { isDisabled, onBlurWithin, onFocusWithin, onFocusWithinChange } = props;
let state = (0, import_react7.useRef)({
isFocusWithin: false
});
let { addGlobalListener, removeAllGlobalListeners } = (0, $03deb23ff14920c4$export$4eaf04e54aa8eed6)();
let onBlur = (0, import_react7.useCallback)((e) => {
if (!e.currentTarget.contains(e.target))
return;
if (state.current.isFocusWithin && !e.currentTarget.contains(e.relatedTarget)) {
state.current.isFocusWithin = false;
removeAllGlobalListeners();
if (onBlurWithin)
onBlurWithin(e);
if (onFocusWithinChange)
onFocusWithinChange(false);
}
}, [
onBlurWithin,
onFocusWithinChange,
state,
removeAllGlobalListeners
]);
let onSyntheticFocus = (0, $8a9cb279dc87e130$export$715c682d09d639cc)(onBlur);
let onFocus = (0, import_react7.useCallback)((e) => {
if (!e.currentTarget.contains(e.target))
return;
const ownerDocument = (0, $431fbd86ca7dc216$export$b204af158042fbac)(e.target);
const activeElement2 = (0, $d4ee10de306f2510$export$cd4e5573fbe2b576)(ownerDocument);
if (!state.current.isFocusWithin && activeElement2 === (0, $d4ee10de306f2510$export$e58f029f0fbfdb29)(e.nativeEvent)) {
if (onFocusWithin)
onFocusWithin(e);
if (onFocusWithinChange)
onFocusWithinChange(true);
state.current.isFocusWithin = true;
onSyntheticFocus(e);
let currentTarget = e.currentTarget;
addGlobalListener(ownerDocument, "focus", (e2) => {
if (state.current.isFocusWithin && !(0, $d4ee10de306f2510$export$4282f70798064fe0)(currentTarget, e2.target)) {
let nativeEvent = new ownerDocument.defaultView.FocusEvent("blur", {
relatedTarget: e2.target
});
(0, $8a9cb279dc87e130$export$c2b7abe5d61ec696)(nativeEvent, currentTarget);
let event = (0, $8a9cb279dc87e130$export$525bc4921d56d4a)(nativeEvent);
onBlur(event);
}
}, {
capture: true
});
}
}, [
onFocusWithin,
onFocusWithinChange,
onSyntheticFocus,
addGlobalListener,
onBlur
]);
if (isDisabled)
return {
focusWithinProps: {
// These cannot be null, that would conflict in mergeProps
onFocus: void 0,
onBlur: void 0
}
};
return {
focusWithinProps: {
onFocus,
onBlur
}
};
}
// ../../node_modules/@react-aria/interactions/dist/useHover.mjs
var import_react8 = require("react");
var $6179b936705e76d3$var$globalIgnoreEmulatedMouseEvents = false;
var $6179b936705e76d3$var$hoverCount = 0;
function $6179b936705e76d3$var$setGlobalIgnoreEmulatedMouseEvents() {
$6179b936705e76d3$var$globalIgnoreEmulatedMouseEvents = true;
setTimeout(() => {
$6179b936705e76d3$var$globalIgnoreEmulatedMouseEvents = false;
}, 50);
}
function $6179b936705e76d3$var$handleGlobalPointerEvent(e) {
if (e.pointerType === "touch")
$6179b936705e76d3$var$setGlobalIgnoreEmulatedMouseEvents();
}
function $6179b936705e76d3$var$setupGlobalTouchEvents() {
if (typeof document === "undefined")
return;
if (typeof PointerEvent !== "undefined")
document.addEventListener("pointerup", $6179b936705e76d3$var$handleGlobalPointerEvent);
else if (false)
document.addEventListener("touchend", $6179b936705e76d3$var$setGlobalIgnoreEmulatedMouseEvents);
$6179b936705e76d3$var$hoverCount++;
return () => {
$6179b936705e76d3$var$hoverCount--;
if ($6179b936705e76d3$var$hoverCount > 0)
return;
if (typeof PointerEvent !== "undefined")
document.removeEventListener("pointerup", $6179b936705e76d3$var$handleGlobalPointerEvent);
else if (false)
document.removeEventListener("touchend", $6179b936705e76d3$var$setGlobalIgnoreEmulatedMouseEvents);
};
}
function $6179b936705e76d3$export$ae780daf29e6d456(props) {
let { onHoverStart, onHoverChange, onHoverEnd, isDisabled } = props;
let [isHovered, setHovered] = (0, import_react8.useState)(false);
let state = (0, import_react8.useRef)({
isHovered: false,
ignoreEmulatedMouseEvents: false,
pointerType: "",
target: null
}).current;
(0, import_react8.useEffect)($6179b936705e76d3$var$setupGlobalTouchEvents, []);
let { addGlobalListener, removeAllGlobalListeners } = (0, $03deb23ff14920c4$export$4eaf04e54aa8eed6)();
let { hoverProps, triggerHoverEnd } = (0, import_react8.useMemo)(() => {
let triggerHoverStart = (event, pointerType) => {
state.pointerType = pointerType;
if (isDisabled || pointerType === "touch" || state.isHovered || !event.currentTarget.contains(event.target))
return;
state.isHovered = true;
let target = event.currentTarget;
state.target = target;
addGlobalListener((0, $431fbd86ca7dc216$export$b204af158042fbac)(event.target), "pointerover", (e) => {
if (state.isHovered && state.target && !(0, $d4ee10de306f2510$export$4282f70798064fe0)(state.target, e.target))
triggerHoverEnd2(e, e.pointerType);
}, {
capture: true
});
if (onHoverStart)
onHoverStart({
type: "hoverstart",
target,
pointerType
});
if (onHoverChange)
onHoverChange(true);
setHovered(true);
};
let triggerHoverEnd2 = (event, pointerType) => {
let target = state.target;
state.pointerType = "";
state.target = null;
if (pointerType === "touch" || !state.isHovered || !target)
return;
state.isHovered = false;
removeAllGlobalListeners();
if (onHoverEnd)
onHoverEnd({
type: "hoverend",
target,
pointerType
});
if (onHoverChange)
onHoverChange(false);
setHovered(false);
};
let hoverProps2 = {};
if (typeof PointerEvent !== "undefined") {
hoverProps2.onPointerEnter = (e) => {
if ($6179b936705e76d3$var$globalIgnoreEmulatedMouseEvents && e.pointerType === "mouse")
return;
triggerHoverStart(e, e.pointerType);
};
hoverProps2.onPointerLeave = (e) => {
if (!isDisabled && e.currentTarget.contains(e.target))
triggerHoverEnd2(e, e.pointerType);
};
} else if (false) {
hoverProps2.onTouchStart = () => {
state.ignoreEmulatedMouseEvents = true;
};
hoverProps2.onMouseEnter = (e) => {
if (!state.ignoreEmulatedMouseEvents && !$6179b936705e76d3$var$globalIgnoreEmulatedMouseEvents)
triggerHoverStart(e, "mouse");
state.ignoreEmulatedMouseEvents = false;
};
hoverProps2.onMouseLeave = (e) => {
if (!isDisabled && e.currentTarget.contains(e.target))
triggerHoverEnd2(e, "mouse");
};
}
return {
hoverProps: hoverProps2,
triggerHoverEnd: triggerHoverEnd2
};
}, [
onHoverStart,
onHoverChange,
onHoverEnd,
isDisabled,
state,
addGlobalListener,
removeAllGlobalListeners
]);
(0, import_react8.useEffect)(() => {
if (isDisabled)
triggerHoverEnd({
currentTarget: state.target
}, state.pointerType);
}, [
isDisabled
]);
return {
hoverProps,
isHovered
};
}
// ../../node_modules/@react-aria/focus/dist/useFocusRing.mjs
var import_react9 = require("react");
function $f7dceffc5ad7768b$export$4e328f61c538687f(props = {}) {
let { autoFocus = false, isTextInput, within } = props;
let state = (0, import_react9.useRef)({
isFocused: false,
isFocusVisible: autoFocus || (0, $507fabe10e71c6fb$export$b9b3dfddab17db27)()
});
let [isFocused, setFocused] = (0, import_react9.useState)(false);
let [isFocusVisibleState, setFocusVisible] = (0, import_react9.useState)(() => state.current.isFocused && state.current.isFocusVisible);
let updateState = (0, import_react9.useCallback)(() => setFocusVisible(state.current.isFocused && state.current.isFocusVisible), []);
let onFocusChange = (0, import_react9.useCallback)((isFocused2) => {
state.current.isFocused = isFocused2;
setFocused(isFocused2);
updateState();
}, [
updateState
]);
(0, $507fabe10e71c6fb$export$ec71b4b83ac08ec3)((isFocusVisible) => {
state.current.isFocusVisible = isFocusVisible;
updateState();
}, [], {
isTextInput
});
let { focusProps } = (0, $a1ea59d68270f0dd$export$f8168d8dd8fd66e6)({
isDisabled: within,
onFocusChange
});
let { focusWithinProps } = (0, $9ab94262bd0047c7$export$420e68273165f4ec)({
isDisabled: !within,
onFocusWithinChange: onFocusChange
});
return {
isFocused,
isFocusVisible: isFocusVisibleState,
focusProps: within ? focusWithinProps : focusProps
};
}
// src/hooks/use-active-press.tsx
var import_react14 = require("react");
// src/utils/env.ts
var Env = class {
constructor() {
__publicField(this, "current", this.detect());
__publicField(this, "handoffState", "pending");
__publicField(this, "currentId", 0);
}
set(env2) {
if (this.current === env2)
return;
this.handoffState = "pending";
this.currentId = 0;
this.current = env2;
}
reset() {
this.set(this.detect());
}
nextId() {
return ++this.currentId;
}
get isServer() {
return this.current === "server";
}
get isClient() {
return this.current === "client";
}
detect() {
if (typeof window === "undefined" || typeof document === "undefined") {
return "server";
}
return "client";
}
handoff() {
if (this.handoffState === "pending") {
this.handoffState = "complete";
}
}
get isHandoffComplete() {
return this.handoffState === "complete";
}
};
var env = new Env();
// src/utils/owner.ts
function getOwnerDocument(element) {
var _a3;
if (env.isServer)
return null;
if (element == null)
return document;
return (_a3 = element == null ? void 0 : element.ownerDocument) != null ? _a3 : document;
}
function getRootNode(element) {
var _a3, _b2;
if (env.isServer)
return null;
if (element == null)
return document;
return (_b2 = (_a3 = element == null ? void 0 : element.getRootNode) == null ? void 0 : _a3.call(element)) != null ? _b2 : document;
}
function getActiveElement(element) {
var _a3, _b2;
return (_b2 = (_a3 = getRootNode(element)) == null ? void 0 : _a3.activeElement) != null ? _b2 : null;
}
function isActiveElement(element) {
return getActiveElement(element) === element;
}
// src/hooks/use-disposables.ts
var import_react10 = require("react");
// src/utils/micro-task.ts
function microTask(cb) {
if (typeof queueMicrotask === "function") {
queueMicrotask(cb);
} else {
Promise.resolve().then(cb).catch(
(e) => setTimeout(() => {
throw e;
})
);
}
}
// src/utils/disposables.ts
function disposables() {
let _disposables = [];
let api = {
addEventListener(element, name, listener, options) {
element.addEventListener(name, listener, options);
return api.add(() => element.removeEventListener(name, listener, options));
},
requestAnimationFrame(...args) {
let raf = requestAnimationFrame(...args);
return api.add(() => cancelAnimationFrame(raf));
},
nextFrame(...args) {
return api.requestAnimationFrame(() => {
return api.requestAnimationFrame(...args);
});
},
setTimeout(...args) {
let timer = setTimeout(...args);
return api.add(() => clearTimeout(timer));
},
microTask(...args) {
let task = { current: true };
microTask(() => {
if (task.current) {
args[0]();
}
});
return api.add(() => {
task.current = false;
});
},
style(node, property, value) {
let previous = node.style.getPropertyValue(property);
Object.assign(node.style, { [property]: value });
return this.add(() => {
Object.assign(node.style, { [property]: previous });
});
},
group(cb) {
let d = disposables();
cb(d);
return this.add(() => d.dispose());
},
add(cb) {
if (!_disposables.includes(cb)) {
_disposables.push(cb);
}
return () => {
let idx = _disposables.indexOf(cb);
if (idx >= 0) {
for (let dispose of _disposables.splice(idx, 1)) {
dispose();
}
}
};
},
dispose() {
for (let dispose of _disposables.splice(0)) {
dispose();
}
}
};
return api;
}
// src/hooks/use-disposables.ts
function useDisposables() {
let [d] = (0, import_react10.useState)(disposables);
(0, import_react10.useEffect)(() => () => d.dispose(), [d]);
return d;
}
// src/hooks/use-event.ts
var import_react13 = __toESM(require("react"), 1);
// src/hooks/use-latest-value.ts
var import_react12 = require("react");
// src/hooks/use-iso-morphic-effect.ts
var import_react11 = require("react");
var useIsoMorphicEffect = (effect, deps) => {
if (env.isServer) {
(0, import_react11.useEffect)(effect, deps);
} else {
(0, import_react11.useLayoutEffect)(effect, deps);
}
};
// src/hooks/use-latest-value.ts
function useLatestValue(value) {
let cache = (0, import_react12.useRef)(value);
useIsoMorphicEffect(() => {
cache.current = value;
}, [value]);
return cache;
}
// src/hooks/use-event.ts
var useEvent = (
// TODO: Add React.useEvent ?? once the useEvent hook is available
function useEvent2(cb) {
let cache = useLatestValue(cb);
return import_react13.default.useCallback((...args) => cache.current(...args), [cache]);
}
);
// src/hooks/use-active-press.tsx
function pointerRectFromPointerEvent(event) {
let offsetX = event.width / 2;
let offsetY = event.height / 2;
return {
top: event.clientY - offsetY,
right: event.clientX + offsetX,
bottom: event.clientY + offsetY,
left: event.clientX - offsetX
};
}
function areRectsOverlapping(a, b) {
if (!a || !b) {
return false;
}
if (a.right < b.left || a.left > b.right) {
return false;
}
if (a.bottom < b.top || a.top > b.bottom) {
return false;
}
return true;
}
function useActivePress({ disabled = false } = {}) {
let target = (0, import_react14.useRef)(null);
let [pressed, setPressed] = (0, import_react14.useState)(false);
let d = useDisposables();
let reset = useEvent(() => {
target.current = null;
setPressed(false);
d.dispose();
});
let handlePointerDown = useEvent((event) => {
d.dispose();
if (target.current !== null)
return;
target.current = event.currentTarget;
setPressed(true);
{
let owner = getOwnerDocument(event.currentTarget);
d.addEventListener(owner, "pointerup", reset, false);
d.addEventListener(
owner,
"pointermove",
(event2) => {
if (target.current) {
let pointerRect = pointerRectFromPointerEvent(event2);
setPressed(areRectsOverlapping(pointerRect, target.current.getBoundingClientRect()));
}
},
false
);
d.addEventListener(owner, "pointercancel", reset, false);
}
});
return {
pressed,
pressProps: disabled ? {} : {
onPointerDown: handlePointerDown,
onPointerUp: reset,
onClick: reset
}
};
}
// src/hooks/use-slot.ts
var import_react15 = require("react");
function useSlot(object) {
return (0, import_react15.useMemo)(() => object, Object.values(object));
}
// src/internal/disabled.tsx
var import_react16 = __toESM(require("react"), 1);
var DisabledContext = (0, import_react16.createContext)(void 0);
function useDisabled() {
return (0, import_react16.useContext)(DisabledContext);
}
function DisabledProvider({
value,
children
}) {
return /* @__PURE__ */ import_react16.default.createElement(DisabledContext.Provider, { value }, children);
}
// src/utils/render.ts
var import_react17 = __toESM(require("react"), 1);
// src/utils/class-names.ts
function classNames(...classes) {
return Array.from(
new Set(
classes.flatMap((value) => {
if (typeof value === "string") {
return value.split(" ");
}
return [];
})
)
).filter(Boolean).join(" ");
}
// src/utils/match.ts
function match(value, lookup, ...args) {
if (value in lookup) {
let returnValue = lookup[value];
return typeof returnValue === "function" ? returnValue(...args) : returnValue;
}
let error2 = new Error(
`Tried to handle "${value}" but there is no handler defined. Only defined handlers are: ${Object.keys(
lookup
).map((key) => `"${key}"`).join(", ")}.`
);
if (Error.captureStackTrace)
Error.captureStackTrace(error2, match);
throw error2;
}
// src/utils/render.ts
function useRender() {
let mergeRefs = useMergeRefsFn();
return (0, import_react17.useCallback)(
(args) => render({ mergeRefs, ...args }),
[mergeRefs]
);
}
function render({
ourProps,
theirProps,
slot,
defaultTag,
features,
visible = true,
name,
mergeRefs
}) {
mergeRefs = mergeRefs != null ? mergeRefs : defaultMergeRefs;
let props = mergePropsAdvanced(theirProps, ourProps);
if (visible)
return _render(props, slot, defaultTag, name, mergeRefs);
let featureFlags = features != null ? features : 0 /* None */;
if (featureFlags & 2 /* Static */) {
let { static: isStatic = false, ...rest } = props;
if (isStatic)
return _render(rest, slot, defaultTag, name, mergeRefs);
}
if (featureFlags & 1 /* RenderStrategy */) {
let { unmount = true, ...rest } = props;
let strategy = unmount ? 0 /* Unmount */ : 1 /* Hidden */;
return match(strategy, {
[0 /* Unmount */]() {
return null;
},
[1 /* Hidden */]() {
return _render(
{ ...rest, ...{ hidden: true, style: { display: "none" } } },
slot,
defaultTag,
name,
mergeRefs
);
}
});
}
return _render(props, slot, defaultTag, name, mergeRefs);
}
function _render(props, slot = {}, tag, name, mergeRefs) {
let {
as: Component = tag,
children,
refName = "ref",
...rest
} = omit(props, ["unmount", "static"]);
let refRelatedProps = props.ref !== void 0 ? { [refName]: props.ref } : {};
let resolvedChildren = typeof children === "function" ? children(slot) : children;
if ("className" in rest && rest.className && typeof rest.className === "function") {
rest.className = rest.className(slot);
}
if (rest["aria-labelledby"] && rest["aria-labelledby"] === rest.id) {
rest["aria-labelledby"] = void 0;
}
let dataAttributes = {};
if (slot) {
let exposeState = false;
let states = [];
for (let [k, v] of Object.entries(slot)) {
if (typeof v === "boolean") {
exposeState = true;
}
if (v === true) {
states.push(k.replace(/([A-Z])/g, (m) => `-${m.toLowerCase()}`));
}
}
if (exposeState) {
dataAttributes["data-headlessui-state"] = states.join(" ");
for (let state of states) {
dataAttributes[`data-${state}`] = "";
}
}
}
if (isFragment(Component)) {
if (Object.keys(compact(rest)).length > 0 || Object.keys(compact(dataAttributes)).length > 0) {
if (!(0, import_react17.isValidElement)(resolvedChildren) || Array.isArray(resolvedChildren) && resolvedChildren.length > 1 || isFragmentInstance(resolvedChildren)) {
if (Object.keys(compact(rest)).length > 0) {
throw new Error(
[
'Passing props on "Fragment"!',
"",
`The current component <${name} /> is rendering a "Fragment".`,
`However we need to passthrough the following props:`,
Object.keys(compact(rest)).concat(Object.keys(compact(dataAttributes))).map((line) => ` - ${line}`).join("\n"),
"",
"You can apply a few solutions:",
[
'Add an `as="..."` prop, to ensure that we render an actual element instead of a "Fragment".',
"Render a single element as the child so that we can forward the props onto that element."
].map((line) => ` - ${line}`).join("\n")
].join("\n")
);
}
} else {
let childProps = resolvedChildren.props;
let childPropsClassName = childProps == null ? void 0 : childProps.className;
let newClassName = typeof childPropsClassName === "function" ? (...args) => classNames(
childPropsClassName(...args),
rest.className
) : classNames(childPropsClassName, rest.className);
let classNameProps = newClassName ? { className: newClassName } : {};
let mergedProps = mergePropsAdvanced(
resolvedChildren.props,
// Filter out undefined values so that they don't override the existing values
compact(omit(rest, ["ref"]))
);
for (let key in dataAttributes) {
if (key in mergedProps) {
delete dataAttributes[key];
}
}
return (0, import_react17.cloneElement)(
resolvedChildren,
Object.assign(
{},
mergedProps,
dataAttributes,
refRelatedProps,
{ ref: mergeRefs(getElementRef(resolvedChildren), refRelatedProps.ref) },
classNameProps
)
);
}
}
}
return (0, import_react17.createElement)(
Component,
Object.assign(
{},
omit(rest, ["ref"]),
!isFragment(Component) && refRelatedProps,
!isFragment(Component) && dataAttributes
),
resolvedChildren
);
}
function useMergeRefsFn() {
let currentRefs = (0, import_react17.useRef)([]);
let mergedRef = (0, import_react17.useCallback)((value) => {
for (let ref of currentRefs.current) {
if (ref == null)
continue;
if (typeof ref === "function")
ref(value);
else
ref.current = value;
}
}, []);
return (...refs) => {
if (refs.every((ref) => ref == null)) {
return void 0;
}
currentRefs.current = refs;
return mergedRef;
};
}
function defaultMergeRefs(...refs) {
return refs.every((ref) => ref == null) ? void 0 : (value) => {
for (let ref of refs) {
if (ref == null)
continue;
if (typeof ref === "function")
ref(value);
else
ref.current = value;
}
};
}
function mergePropsAdvanced(...listOfProps) {
var _a3;
if (listOfProps.length === 0)
return {};
if (listOfProps.length === 1)
return listOfProps[0];
let target = {};
let eventHandlers = {};
for (let props of listOfProps) {
for (let prop in props) {
if (prop.startsWith("on") && typeof props[prop] === "function") {
(_a3 = eventHandlers[prop]) != null ? _a3 : eventHandlers[prop] = [];
eventHandlers[prop].push(props[prop]);
} else {
target[prop] = props[prop];
}
}
}
if (target.disabled || target["aria-disabled"]) {
for (let eventName in eventHandlers) {
if (/^(on(?:Click|Pointer|Mouse|Key)(?:Down|Up|Press)?)$/.test(eventName)) {
eventHandlers[eventName] = [(e) => {
var _a4;
return (_a4 = e == null ? void 0 : e.preventDefault) == null ? void 0 : _a4.call(e);
}];
}
}
}
for (let eventName in eventHandlers) {
Object.assign(target, {
[eventName](event, ...args) {
let handlers = eventHandlers[eventName];
for (let handler of handlers) {
if ((event instanceof Event || (event == null ? void 0 : event.nativeEvent) instanceof Event) && event.defaultPrevented) {
return;
}
handler(event, ...args);
}
}
});
}
return target;
}
function mergeProps(...listOfProps) {
var _a3;
if (listOfProps.length === 0)
return {};
if (listOfProps.length === 1)
return listOfProps[0];
let target = {};
let eventHandlers = {};
for (let props of listOfProps) {
for (let prop in props) {
if (prop.startsWith("on") && typeof props[prop] === "function") {
(_a3 = eventHandlers[prop]) != null ? _a3 : eventHandlers[prop] = [];
eventHandlers[prop].push(props[prop]);
} else {
target[prop] = props[prop];
}
}
}
for (let eventName in eventHandlers) {
Object.assign(target, {
[eventName](...args) {
let handlers = eventHandlers[eventName];
for (let handler of handlers) {
handler == null ? void 0 : handler(...args);
}
}
});
}
return target;
}
function forwardRefWithAs(component) {
var _a3;
return Object.assign((0, import_react17.forwardRef)(component), {
displayName: (_a3 = component.displayName) != null ? _a3 : component.name
});
}
function compact(object) {
let clone = Object.assign({}, object);
for (let key in clone) {
if (clone[key] === void 0)
delete clone[key];
}
return clone;
}
function omit(object, keysToOmit = []) {
let clone = Object.assign({}, object);
for (let key of keysToOmit) {
if (key in clone)
delete clone[key];
}
return clone;
}
function getElementRef(element) {
return import_react17.default.version.split(".")[0] >= "19" ? element.props.ref : element.ref;
}
function isFragment(element) {
return element === import_react17.Fragment || element === Symbol.for("react.fragment");
}
function isFragmentInstance(element) {
return isFragment(element.type);
}
// src/components/button/button.tsx
var DEFAULT_BUTTON_TAG = "button";
function ButtonFn(props, ref) {
var _a3;
let providedDisabled = useDisabled();
let { disabled = providedDisabled || false, autoFocus = false, ...theirProps } = props;
let { isFocusVisible: focus, focusProps } = $f7dceffc5ad7768b$export$4e328f61c538687f({ autoFocus });
let { isHovered: hover, hoverProps } = $6179b936705e76d3$export$ae780daf29e6d456({ isDisabled: disabled });
let { pressed: active, pressProps } = useActivePress({ disabled });
let ourProps = mergeProps(
{
ref,
type: (_a3 = theirProps.type) != null ? _a3 : "button",
disabled: disabled || void 0,
autoFocus
},
focusProps,
hoverProps,
pressProps
);
let slot = useSlot({ disabled, hover, focus, active, autofocus: autoFocus });
let render2 = useRender();
return render2({
ourProps,
theirProps,
slot,
defaultTag: DEFAULT_BUTTON_TAG,
name: "Button"
});
}
var Button = forwardRefWithAs(ButtonFn);
// src/components/checkbox/checkbox.tsx
var import_react27 = __toESM(require("react"), 1);
// src/hooks/use-controllable.ts
var import_react18 = require("react");
var import_react_dom = require("react-dom");
function useControllable(controlledValue, onChange, defaultValue) {
let [internalValue, setInternalValue] = (0, import_react18.useState)(defaultValue);
let isControlled = controlledValue !== void 0;
let wasControlled = (0, import_react18.useRef)(isControlled);
let didWarnOnUncontrolledToControlled = (0, import_react18.useRef)(false);
let didWarnOnControlledToUncontrolled = (0, import_react18.useRef)(false);
if (isControlled && !wasControlled.current && !didWarnOnUncontrolledToControlled.current) {
didWarnOnUncontrolledToControlled.current = true;
wasControlled.current = isControlled;
console.error(
"A component is changing from uncontrolled to controlled. This may be caused by the value changing from undefined to a defined value, which should not happen."
);
} else if (!isControlled && wasControlled.current && !didWarnOnControlledToUncontrolled.current) {
didWarnOnControlledToUncontrolled.current = true;
wasControlled.current = isControlled;
console.error(
"A component is changing from controlled to uncontrolled. This may be caused by the value changing from a defined value to undefined, which should not happen."
);
}
return [
isControlled ? controlledValue : internalValue,
useEvent((value) => {
if (isControlled) {
return onChange == null ? void 0 : onChange(value);
} else {
(0, import_react_dom.flushSync)(() => setInternalValue(value));
return onChange == null ? void 0 : onChange(value);
}
})
];
}
// src/hooks/use-default-value.ts
var import_react19 = require("react");
function useDefaultValue(value) {
let [defaultValue] = (0, import_react19.useState)(value);
return defaultValue;
}
// src/hooks/use-id.ts
var import_react20 = require("react");
// src/internal/form-fields.tsx
var import_react22 = __toESM(require("react"), 1);
var import_react_dom2 = require("react-dom");
// src/utils/form.ts
var import_react21 = require("react");
function objectToFormEntries(source = {}, parentKey = null, entries = []) {
for (let [key, value] of Object.entries(source)) {
append(entries, composeKey(parentKey, key), value);
}
return entries;
}
function composeKey(parent, key) {
return parent ? parent + "[" + key + "]" : key;
}
function append(entries, key, value) {
if (Array.isArray(value)) {
for (let [subkey, subvalue] of value.entries()) {
append(entries, composeKey(key, subkey.toString()), subvalue);
}
} else if (value instanceof Date) {
entries.push([key, value.toISOString()]);
} else if (typeof value === "boolean") {
entries.push([key, value ? "1" : "0"]);
} else if (typeof value === "string") {
entries.push([key, value]);
} else if (typeof value === "number") {
entries.push([key, `${value}`]);
} else if (value === null || value === void 0) {
entries.push([key, ""]);
} else if (isPlainObject(value) && !(0, import_react21.isValidElement)(value)) {
objectToFormEntries(value, key, entries);
}
}
function attemptSubmit(elementInForm) {
var _a3, _b2;
let form = (_a3 = elementInForm == null ? void 0 : elementInForm.form) != null ? _a3 : elementInForm.closest("form");
if (!form)
return;
for (let element of form.elements) {
if (element === elementInForm)
continue;
if (element.tagName === "INPUT" && element.type === "submit" || element.tagName === "BUTTON" && element.type === "submit" || element.nodeName === "INPUT" && element.type === "image") {
element.click();
return;
}
}
(_b2 = form.requestSubmit) == null ? void 0 : _b2.call(form);
}
function isPlainObject(value) {
if (Object.prototype.toString.call(value) !== "[object Object]") {
return false;
}
let prototype = Object.getPrototypeOf(value);
return prototype === null || Object.getPrototypeOf(prototype) === null;
}
// src/internal/hidden.tsx
var DEFAULT_VISUALLY_HIDDEN_TAG = "span";
function VisuallyHidden(props, ref) {
var _a3;
let { features = 1 /* None */, ...theirProps } = props;
let ourProps = {
ref,
"aria-hidden": (features & 2 /* Focusable */) === 2 /* Focusable */ ? true : (_a3 = theirProps["aria-hidden"]) != null ? _a3 : void 0,
hidden: (features & 4 /* Hidden */) === 4 /* Hidden */ ? true : void 0,
style: {
position: "fixed",
top: 1,
left: 1,
width: 1,
height: 0,
padding: 0,
margin: -1,
overflow: "hidden",
clip: "rect(0, 0, 0, 0)",
whiteSpace: "nowrap",
borderWidth: "0",
...(features & 4 /* Hidden */) === 4 /* Hidden */ && !((features & 2 /* Focusable */) === 2 /* Focusable */) && {
display: "none"
}
}
};
let render2 = useRender();
return render2({
ourProps,
theirProps,
slot: {},
defaultTag: DEFAULT_VISUALLY_HIDDEN_TAG,
name: "Hidden"
});
}
var Hidden = forwardRefWithAs(VisuallyHidden);
// src/internal/form-fields.tsx
var FormFieldsContext = (0, import_react22.createContext)(null);
function FormFieldsProvider(props) {
let [target, setTarget] = (0, import_react22.useState)(null);
return /* @__PURE__ */ import_react22.default.createElement(FormFieldsContext.Provider, { value: { target } }, props.children, /* @__PURE__ */ import_react22.default.createElement(Hidden, { features: 4 /* Hidden */, ref: setTarget }));
}
function HoistFormFields({ children }) {
let formFieldsContext = (0, import_react22.useContext)(FormFieldsContext);
if (!formFieldsContext)
return /* @__PURE__ */ import_react22.default.createElement(import_react22.default.Fragment, null, children);
let { target } = formFieldsContext;
return target ? (0, import_react_dom2.createPortal)(/* @__PURE__ */ import_react22.default.createElement(import_react22.default.Fragment, null, children), target) : null;
}
function FormFields({
data,
form: formId,
disabled,
onReset,
overrides
}) {
let [form, setForm] = (0, import_react22.useState)(null);
let d = useDisposables();
(0, import_react22.useEffect)(() => {
if (!onReset)
return;
if (!form)
return;
return d.addEventListener(form, "reset", onReset);
}, [form, formId, onReset]);
return /* @__PURE__ */ import_react22.default.createElement(HoistFormFields, null, /* @__PURE__ */ import_react22.default.createElement(FormResolver, { setForm, formId }), objectToFormEntries(data).map(([name, value]) => {
return /* @__PURE__ */ import_react22.default.createElement(
Hidden,
{
features: 4 /* Hidden */,
...compact({
key: name,
as: "input",
type: "hidden",
hidden: true,
readOnly: true,
form: formId,
disabled,
name,
value,
...overrides
})
}
);
}));
}
function FormResolver({
setForm,
formId
}) {
(0, import_react22.useEffect)(() => {
if (formId) {
let resolvedForm = document.getElementById(formId);
if (resolvedForm)
setForm(resolvedForm);
}
}, [setForm, formId]);
return formId ? null : /* @__PURE__ */ import_react22.default.createElement(
Hidden,
{
features: 4 /* Hidden */,
as: "input",
type: "hidden",
hidden: true,
readOnly: true,
ref: (el) => {
if (!el)
return;
let resolvedForm = el.closest("form");
if (resolvedForm)
setForm(resolvedForm);
}
}
);
}
// src/internal/id.tsx
var import_react23 = __toESM(require("react"), 1);
var IdContext = (0, import_react23.createContext)(void 0);
function useProvidedId() {
return (0, import_react23.useContext)(IdContext);
}
function IdProvider({ id, children }) {
return /* @__PURE__ */ import_react23.default.createElement(IdContext.Provider, { value: id }, children);
}
// src/utils/dom.ts
function isNode(element) {
if (typeof element !== "object")
return false;
if (element === null)
return false;
return "nodeType" in element;
}
function isElement(element) {
return isNode(element) && "tagName" in element;
}
function isHTMLElement(element) {
return isElement(element) && "accessKey" in element;
}
function isHTMLorSVGElement(element) {
return isElement(element) && "tabIndex" in element;
}
function hasInlineStyle(element) {
return isElement(element) && "style" in element;
}
function isHTMLIframeElement(element) {
return isHTMLElement(element) && element.nodeName === "IFRAME";
}
function isHTMLInputElement(element) {
return isHTMLElement(element) && element.nodeName === "INPUT";
}
function isHTMLLabelElement(element) {
return isHTMLElement(element) && element.nodeName === "LABEL";
}
function isHTMLFieldSetElement(element) {
return isHTMLElement(element) && element.nodeName === "FIELDSET";
}
function isHTMLLegendElement(element) {
return isHTMLElement(element) && element.nodeName === "LEGEND";
}
function isInteractiveElement(element) {
if (!isElement(element))
return false;
return element.matches(
'a[href],audio[controls],button,details,embed,iframe,img[usemap],input:not([type="hidden"]),label,select,textarea,video[controls]'
);
}
// src/utils/bugs.ts
function isDisabledReactIssue7711(element) {
let parent = element.parentElement;
let legend = null;
while (parent && !isHTMLFieldSetElement(parent)) {
if (isHTMLLegendElement(parent))
legend = parent;
parent = parent.parentElement;
}
let isParentDisabled = (parent == null ? void 0 : parent.getAttribute("disabled")) === "";
if (isParentDisabled && isFirstLegend(legend))
return false;
return isParentDisabled;
}
function isFirstLegend(element) {
if (!element)
return false;
let previous = element.previousElementSibling;
while (previous !== null) {
if (isHTMLLegendElement(previous))
return false;
previous = previous.previousElementSibling;
}
return true;
}
// src/components/description/description.tsx
var import_react25 = __toESM(require("react"), 1);
// src/hooks/use-sync-refs.ts
var import_react24 = require("react");
var Optional = Symbol();
function optionalRef(cb, isOptional = true) {
return Object.assign(cb, { [Optional]: isOptional });
}
function useSyncRefs(...refs) {
let cache = (0, import_react24.useRef)(refs);
(0, import_react24.useEffect)(() => {
cache.current = refs;
}, [refs]);
let syncRefs = useEvent((value) => {
for (let ref of cache.current) {
if (ref == null)
continue;
if (typeof ref === "function")
ref(value);
else
ref.current = value;
}
});
return refs.every(
(ref) => ref == null || // @ts-expect-error
(ref == null ? void 0 : ref[Optional])
) ? void 0 : syncRefs;
}
// src/components/description/description.tsx
var DescriptionContext = (0, import_react25.createContext)(null);
DescriptionContext.displayName = "DescriptionContext";
function useDescriptionContext() {
let context = (0, import_react25.useContext)(DescriptionContext);
if (context === null) {
let err = new Error(
"You used a component, but it is not inside a relevant parent."
);
if (Error.captureStackTrace)
Error.captureStackTrace(err, useDescriptionContext);
throw err;
}
return context;
}
function useDescribedBy() {
var _a3, _b2;
return (_b2 = (_a3 = (0, import_react25.useContext)(DescriptionContext)) == null ? void 0 : _a3.value) != null ? _b2 : void 0;
}
function useDescriptions() {
let [descriptionIds, setDescriptionIds] = (0, import_react25.useState)([]);
return [
// The actual id's as string or undefined
descriptionIds.length > 0 ? descriptionIds.join(" ") : void 0,
// The provider component
(0, import_react25.useMemo)(() => {
return function DescriptionProvider(props) {
let register = useEvent((value) => {
setDescriptionIds((existing) => [...existing, value]);
return () => {
return setDescriptionIds((existing) => {
let clone = existing.slice();
let idx = clone.indexOf(value);
if (idx !== -1)
clone.splice(idx, 1);
return clone;
});
};
});
let contextBag = (0, import_react25.useMemo)(
() => ({
register,
slot: props.slot,
name: props.name,
props: props.props,
value: props.value
}),
[register, props.slot, props.name, props.props, props.value]
);
return /* @__PURE__ */ import_react25.default.createElement(DescriptionContext.Provider, { value: contextBag }, props.children);
};
}, [setDescriptionIds])
];
}
var DEFAULT_DESCRIPTION_TAG = "p";
function DescriptionFn(props, ref) {
let internalId = (0, import_react20.useId)();
let providedDisabled = useDisabled();
let { id = `headlessui-description-${internalId}`, ...theirProps } = props;
let context = useDescriptionContext();
let descriptionRef = useSyncRefs(ref);
useIsoMorphicEffect(() => context.register(id), [id, context.register]);
let slot = useSlot({ ...context.slot, disabled: providedDisabled || false });
let ourProps = { ref: descriptionRef, ...context.props, id };
let render2 = useRender();
return render2({
ourProps,
theirProps,
slot,
defaultTag: DEFAULT_DESCRIPTION_TAG,
name: context.name || "Description"
});
}
var DescriptionRoot = forwardRefWithAs(DescriptionFn);
var Description = Object.assign(DescriptionRoot, {
//
});
// src/components/label/label.tsx
var import_react26 = __toESM(require("react"), 1);
var LabelContext = (0, import_react26.createContext)(null);
LabelContext.displayName = "LabelContext";
function useLabelContext() {
let context = (0, import_react26.useContext)(LabelContext);
if (context === null) {
let err = new Error("You used a component, but it is not inside a relevant parent.");
if (Error.captureStackTrace)
Error.captureStackTrace(err, useLabelContext);
throw err;
}
return context;
}
function useLabelledBy(alwaysAvailableIds) {
var _a3, _b2, _c;
let labelIds = (_b2 = (_a3 = (0, import_react26.useContext)(LabelContext)) == null ? void 0 : _a3.value) != null ? _b2 : void 0;
if (((_c = alwaysAvailableIds == null ? void 0 : alwaysAvailableIds.length) != null ? _c : 0) > 0) {
return [labelIds, ...alwaysAvailableIds].filter(Boolean).join(" ");
}
return labelIds;
}
function useLabels({ inherit = false } = {}) {
let parentLabelledBy = useLabelledBy();
let [labelIds, setLabelIds] = (0, import_react26.useState)([]);
let allLabelIds = inherit ? [parentLabelledBy, ...labelIds].filter(Boolean) : labelIds;
return [
// The actual id's as string or undefined.
allLabelIds.length > 0 ? allLabelIds.join(" ") : void 0,
// The provider component
(0, import_react26.useMemo)(() => {
return function LabelProvider(props) {
let register = useEvent((value) => {
setLabelIds((existing) => [...existing, value]);
return () => {
return setLabelIds((existing) => {
let clone = existing.slice();
let idx = clone.indexOf(value);
if (idx !== -1)
clone.splice(idx, 1);
return clone;
});
};
});
let contextBag = (0, import_react26.useMemo)(
() => ({
register,
slot: props.slot,
name: props.name,
props: props.props,
value: props.value
}),
[register, props.slot, props.name, props.props, props.value]
);
return /* @__PURE__ */ import_react26.default.createElement(LabelContext.Provider, { value: contextBag }, props.children);
};
}, [setLabelIds])
];
}
var DEFAULT_LABEL_TAG = "label";
function LabelFn(props, ref) {
var _a3;
let internalId = (0, import_react20.useId)();
let context = useLabelContext();
let providedHtmlFor = useProvidedId();
let providedDisabled = useDisabled();
let {
id = `headlessui-label-${internalId}`,
htmlFor = providedHtmlFor != null ? providedHtmlFor : (_a3 = context.props) == null ? void 0 : _a3.htmlFor,
passive = false,
...theirProps
} = props;
let labelRef = useSyncRefs(ref);
useIsoMorphicEffect(() => context.register(id), [id, context.register]);
let handleClick = useEvent((e) => {
let current = e.currentTarget;
if (e.target !== e.currentTarget && isInteractiveElement(e.target)) {
return;
}
if (isHTMLLabelElement(current)) {
e.preventDefault();
}
if (context.props && "onClick" in context.props && typeof context.props.onClick === "function") {
context.props.onClick(e);
}
if (isHTMLLabelElement(current)) {
let target = document.getElementById(current.htmlFor);
if (target) {
let actuallyDisabled = target.getAttribute("disabled");
if (actuallyDisabled === "true" || actuallyDisabled === "") {
return;
}
let ariaDisabled = target.getAttribute("aria-disabled");
if (ariaDisabled === "true" || ariaDisabled === "") {
return;
}
if (isHTMLInputElement(target) && (target.type === "file" || target.type === "radio" || target.type === "checkbox") || target.role === "radio" || target.role === "checkbox" || target.role === "switch") {
target.click();
}
target.focus({ preventScroll: true });
}
}
});
let slot = useSlot({ ...context.slot, disabled: providedDisabled || false });
let ourProps = {
ref: labelRef,
...context.props,
id,
htmlFor,
onClick: handleClick
};
if (passive) {
if ("onClick" in ourProps) {
delete ourProps["htmlFor"];
delete ourProps["onClick"];
}
if ("onClick" in theirProps) {
delete theirProps["onClick"];
}
}
let render2 = useRender();
return render2({
ourProps,
theirProps,
slot,
defaultTag: htmlFor ? DEFAULT_LABEL_TAG : "div",
name: context.name || "Label"
});
}
var LabelRoot = forwardRefWithAs(LabelFn);
var Label = Object.assign(LabelRoot, {
//
});
// src/components/checkbox/checkbox.tsx
var DEFAULT_CHECKBOX_TAG = "span";
function CheckboxFn(props, ref) {
let internalId = (0, import_react20.useId)();
let providedId = useProvidedId();
let providedDisabled = useDisabled();
let {
id = providedId || `headlessui-checkbox-${internalId}`,
disabled = providedDisabled || false,
autoFocus = false,
checked: controlledChecked,
defaultChecked: _defaultChecked,
onChange: controlledOnChange,
name,
value,
form,
indeterminate = false,
tabIndex = 0,
...theirProps
} = props;
let defaultChecked = useDefaultValue(_defaultChecked);
let [checked, onChange] = useControllable(
controlledChecked,
controlledOnChange,
defaultChecked != null ? defaultChecked : false
);
let labelledBy = useLabelledBy();
let describedBy = useDescribedBy();
let d = useDisposables();
let [changing, setChanging] = (0, import_react27.useState)(false);
let toggle = useEvent(() => {
setChanging(true);
onChange == null ? void 0 : onChange(!checked);
d.nextFrame(() => {
setChanging(false);
});
});
let handleClick = useEvent((event) => {
if (isDisabledReactIssue7711(event.currentTarget))
return event.preventDefault();
event.preventDefault();
toggle();
});
let handleKeyUp = useEvent((event) => {
if (event.key === " " /* Space */) {
event.preventDefault();
toggle();
} else if (event.key === "Enter" /* Enter */) {
attemptSubmit(event.currentTarget);
}
});
let handleKeyPress = useEvent((event) => event.preventDefault());
let { isFocusVisible: focus, focusProps } = $f7dceffc5ad7768b$export$4e328f61c538687f({ autoFocus });
let { isHovered: hover, hoverProps } = $6179b936705e76d3$export$ae780daf29e6d456({ isDisabled: disabled });
let { pressed: active, pressProps } = useActivePress({ disabled });
let ourProps = mergeProps(
{
ref,
id,
role: "checkbox",
"aria-checked": indeterminate ? "mixed" : checked ? "true" : "false",
"aria-labelledby": labelledBy,
"aria-describedby": describedBy,
"aria-disabled": disabled ? true : void 0,
indeterminate: indeterminate ? "true" : void 0,
tabIndex: disabled ? void 0 : tabIndex,
onKeyUp: disabled ? void 0 : handleKeyUp,
onKeyPress: disabled ? void 0 : handleKeyPress,
onClick: disabled ? void 0 : handleClick
},
focusProps,
hoverProps,
pressProps
);
let slot = useSlot({
checked,
disabled,
hover,
focus,
active,
indeterminate,
changing,
autofocus: autoFocus
});
let reset = (0, import_react27.useCallback)(() => {
if (defaultChecked === void 0)
return;
return onChange == null ? void 0 : onChange(defaultChecked);
}, [onChange, defaultChecked]);
let render2 = useRender();
return /* @__PURE__ */ import_react27.default.createElement(import_react27.default.Fragment, null, name != null && /* @__PURE__ */ import_react27.default.createElement(
FormFields,
{
disabled,
data: { [name]: value || "on" },
overrides: { type: "checkbox", checked },
form,
onReset: reset
}
), render2({
ourProps,
theirProps,
slot,
defaultTag: DEFAULT_CHECKBOX_TAG,
name: "Checkbox"
}));
}
var Checkbox = forwardRefWithAs(CheckboxFn);
// src/components/close-button/close-button.tsx
var import_react29 = __toESM(require("react"), 1);
// src/internal/close-provider.tsx
var import_react28 = __toESM(require("react"), 1);
var CloseContext = (0, import_react28.createContext)(() => {
});
function useClose() {
return (0, import_react28.useContext)(CloseContext);
}
function CloseProvider({ value, children }) {
return /* @__PURE__ */ import_react28.default.createElement(CloseContext.Provider, { value }, children);
}
// src/components/close-button/close-button.tsx
function CloseButtonFn(props, ref) {
let close = useClose();
return /* @__PURE__ */ import_react29.default.createElement(Button, { ref, ...mergeProps({ onClick: close }, props) });
}
var CloseButton = forwardRefWithAs(CloseButtonFn);
// ../../node_modules/@tanstack/react-virtual/dist/esm/index.js
var React11 = __toESM(require("react"), 1);
var import_react_dom3 = require("react-dom");
// ../../node_modules/@tanstack/react-virtual/node_modules/@tanstack/virtual-core/dist/esm/utils.js
function memo(getDeps, fn, opts) {
var _a3;
let deps = (_a3 = opts.initialDeps) != null ? _a3 : [];
let result;
function memoizedFunction() {
var _a4, _b2, _c, _d;
let depTime;
if (opts.key && ((_a4 = opts.debug) == null ? void 0 : _a4.call(opts)))
depTime = Date.now();
const newDeps = getDeps();
const depsChanged = newDeps.length !== deps.length || newDeps.some((dep, index3) => deps[index3] !== dep);
if (!depsChanged) {
return result;
}
deps = newDeps;
let resultTime;
if (opts.key && ((_b2 = opts.debug) == null ? void 0 : _b2.call(opts)))
resultTime = Date.now();
result = fn(...newDeps);
if (opts.key && ((_c = opts.debug) == null ? void 0 : _c.call(opts))) {
const depEndTime = Math.round((Date.now() - depTime) * 100) / 100;
const resultEndTime = Math.round((Date.now() - resultTime) * 100) / 100;
const resultFpsPercentage = resultEndTime / 16;
const pad = (str, num) => {
str = String(str);
while (str.length < num) {
str = " " + str;
}
return str;
};
console.info(
`%c\u23F1 ${pad(resultEndTime, 5)} /${pad(depEndTime, 5)} ms`,
`
font-size: .6rem;
font-weight: bold;
color: hsl(${Math.max(
0,
Math.min(120 - 120 * resultFpsPercentage, 120)
)}deg 100% 31%);`,
opts == null ? void 0 : opts.key
);
}
(_d = opts == null ? void 0 : opts.onChange) == null ? void 0 : _d.call(opts, result);
return result;
}
memoizedFunction.updateDeps = (newDeps) => {
deps = newDeps;
};
return memoizedFunction;
}
function notUndefined(value, msg) {
if (value === void 0) {
throw new Error(`Unexpected undefined${msg ? `: ${msg}` : ""}`);
} else {
return value;
}
}
var approxEqual = (a, b) => Math.abs(a - b) <= 1;
var debounce = (targetWindow, fn, ms) => {
let timeoutId;
return function(...args) {
targetWindow.clearTimeout(timeoutId);
timeoutId = targetWindow.setTimeout(() => fn.apply(this, args), ms);
};
};
// ../../node_modules/@tanstack/react-virtual/node_modules/@tanstack/virtual-core/dist/esm/index.js
var getRect = (element) => {
const { offsetWidth, offsetHeight } = element;
return { width: offsetWidth, height: offsetHeight };
};
var defaultKeyExtractor = (index3) => index3;
var defaultRangeExtractor = (range) => {
const start = Math.max(range.startIndex - range.overscan, 0);
const end = Math.min(range.endIndex + range.overscan, range.count - 1);
const arr = [];
for (let i = start; i <= end; i++) {
arr.push(i);
}
return arr;
};
var observeElementRect = (instance, cb) => {
const element = instance.scrollElement;
if (!element) {
return;
}
const targetWindow = instance.targetWindow;
if (!targetWindow) {
return;
}
const handler = (rect) => {
const { width, height } = rect;
cb({ width: Math.round(width), height: Math.round(height) });
};
handler(getRect(element));
if (!targetWindow.ResizeObserver) {
return () => {
};
}
const observer = new targetWindow.ResizeObserver((entries) => {
const run = () => {
const entry = entries[0];
if (entry == null ? void 0 : entry.borderBoxSize) {
const box = entry.borderBoxSize[0];
if (box) {
handler({ width: box.inlineSize, height: box.blockSize });
return;
}
}
handler(getRect(element));
};
instance.options.useAnimationFrameWithResizeObserver ? requestAnimationFrame(run) : run();
});
observer.observe(element, { box: "border-box" });
return () => {
observer.unobserve(element);
};
};
var addEventListenerOptions = {
passive: true
};
var supportsScrollend = typeof window == "undefined" ? true : "onscrollend" in window;
var observeElementOffset = (instance, cb) => {
const element = instance.scrollElement;
if (!element) {
return;
}
const targetWindow = instance.targetWindow;
if (!targetWindow) {
return;
}
let offset3 = 0;
const fallback = instance.options.useScrollendEvent && supportsScrollend ? () => void 0 : debounce(
targetWindow,
() => {
cb(offset3, false);
},
instance.options.isScrollingResetDelay
);
const createHandler = (isScrolling) => () => {
const { horizontal, isRtl } = instance.options;
offset3 = horizontal ? element["scrollLeft"] * (isRtl && -1 || 1) : element["scrollTop"];
fallback();
cb(offset3, isScrolling);
};
const handler = createHandler(true);
const endHandler = createHandler(false);
endHandler();
element.addEventListener("scroll", handler, addEventListenerOptions);
const registerScrollendEvent = instance.options.useScrollendEvent && supportsScrollend;
if (registerScrollendEvent) {
element.addEventListener("scrollend", endHandler, addEventListenerOptions);
}
return () => {
element.removeEventListener("scroll", handler);
if (registerScrollendEvent) {
element.removeEventListener("scrollend", endHandler);
}
};
};
var measureElement = (element, entry, instance) => {
if (entry == null ? void 0 : entry.borderBoxSize) {
const box = entry.borderBoxSize[0];
if (box) {
const size3 = Math.round(
box[instance.options.horizontal ? "inlineSize" : "blockSize"]
);
return size3;
}
}
return element[instance.options.horizontal ? "offsetWidth" : "offsetHeight"];
};
var elementScroll = (offset3, {
adjustments = 0,
behavior
}, instance) => {
var _a3, _b2;
const toOffset = offset3 + adjustments;
(_b2 = (_a3 = instance.scrollElement) == null ? void 0 : _a3.scrollTo) == null ? void 0 : _b2.call(_a3, {
[instance.options.horizontal ? "left" : "top"]: toOffset,
behavior
});
};
var Virtualizer = class {
constructor(opts) {
this.unsubs = [];
this.scrollElement = null;
this.targetWindow = null;
this.isScrolling = false;
this.scrollToIndexTimeoutId = null;
this.measurementsCache = [];
this.itemSizeCache = /* @__PURE__ */ new Map();
this.pendingMeasuredCacheIndexes = [];
this.scrollRect = null;
this.scrollOffset = null;
this.scrollDirection = null;
this.scrollAdjustments = 0;
this.elementsCache = /* @__PURE__ */ new Map();
this.observer = /* @__PURE__ */ (() => {
let _ro = null;
const get = () => {
if (_ro) {
return _ro;
}
if (!this.targetWindow || !this.targetWindow.ResizeObserver) {
return null;
}
return _ro = new this.targetWindow.ResizeObserver((entries) => {
entries.forEach((entry) => {
const run = () => {
this._measureElement(entry.target, entry);
};
this.options.useAnimationFrameWithResizeObserver ? requestAnimationFrame(run) : run();
});
});
};
return {
disconnect: () => {
var _a3;
(_a3 = get()) == null ? void 0 : _a3.disconnect();
_ro = null;
},
observe: (target) => {
var _a3;
return (_a3 = get()) == null ? void 0 : _a3.observe(target, { box: "border-box" });
},
unobserve: (target) => {
var _a3;
return (_a3 = get()) == null ? void 0 : _a3.unobserve(target);
}
};
})();
this.range = null;
this.setOptions = (opts2) => {
Object.entries(opts2).forEach(([key, value]) => {
if (typeof value === "undefined")
delete opts2[key];
});
this.options = {
debug: false,
initialOffset: 0,
overscan: 1,
paddingStart: 0,
paddingEnd: 0,
scrollPaddingStart: 0,
scrollPaddingEnd: 0,
horizontal: false,
getItemKey: defaultKeyExtractor,
rangeExtractor: defaultRangeExtractor,
onChange: () => {
},
measureElement,
initialRect: { width: 0, height: 0 },
scrollMargin: 0,
gap: 0,
indexAttribute: "data-index",
initialMeasurementsCache: [],
lanes: 1,
isScrollingResetDelay: 150,
enabled: true,
isRtl: false,
useScrollendEvent: false,
useAnimationFrameWithResizeObserver: false,
...opts2
};
};
this.notify = (sync) => {
var _a3, _b2;
(_b2 = (_a3 = this.options).onChange) == null ? void 0 : _b2.call(_a3, this, sync);
};
this.maybeNotify = memo(
() => {
this.calculateRange();
return [
this.isScrolling,
this.range ? this.range.startIndex : null,
this.range ? this.range.endIndex : null
];
},
(isScrolling) => {
this.notify(isScrolling);
},
{
key: "maybeNotify",
debug: () => this.options.debug,
initialDeps: [
this.isScrolling,
this.range ? this.range.startIndex : null,
this.range ? this.range.endIndex : null
]
}
);
this.cleanup = () => {
this.unsubs.filter(Boolean).forEach((d) => d());
this.unsubs = [];
this.observer.disconnect();
this.scrollElement = null;
this.targetWindow = null;
};
this._didMount = () => {
return () => {
this.cleanup();
};
};
this._willUpdate = () => {
var _a4;
var _a3;
const scrollElement = this.options.enabled ? this.options.getScrollElement() : null;
if (this.scrollElement !== scrollElement) {
this.cleanup();
if (!scrollElement) {
this.maybeNotify();
return;
}
this.scrollElement = scrollElement;
if (this.scrollElement && "ownerDocument" in this.scrollElement) {
this.targetWindow = this.scrollElement.ownerDocument.defaultView;
} else {
this.targetWindow = (_a4 = (_a3 = this.scrollElement) == null ? void 0 : _a3.window) != null ? _a4 : null;
}
this.elementsCache.forEach((cached) => {
this.observer.observe(cached);
});
this._scrollToOffset(this.getScrollOffset(), {
adjustments: void 0,
behavior: void 0
});
this.unsubs.push(
this.options.observeElementRect(this, (rect) => {
this.scrollRect = rect;
this.maybeNotify();
})
);
this.unsubs.push(
this.options.observeElementOffset(this, (offset3, isScrolling) => {
this.scrollAdjustments = 0;
this.scrollDirection = isScrolling ? this.getScrollOffset() < offset3 ? "forward" : "backward" : null;
this.scrollOffset = offset3;
this.isScrolling = isScrolling;
this.maybeNotify();
})
);
}
};
this.getSize = () => {
var _a3;
if (!this.options.enabled) {
this.scrollRect = null;
return 0;
}
this.scrollRect = (_a3 = this.scrollRect) != null ? _a3 : this.options.initialRect;
return this.scrollRect[this.options.horizontal ? "width" : "height"];
};
this.getScrollOffset = () => {
var _a3;
if (!this.options.enabled) {
this.scrollOffset = null;
return 0;
}
this.scrollOffset = (_a3 = this.scrollOffset) != null ? _a3 : typeof this.options.initialOffset === "function" ? this.options.initialOffset() : this.options.initialOffset;
return this.scrollOffset;
};
this.getFurthestMeasurement = (measurements, index3) => {
const furthestMeasurementsFound = /* @__PURE__ */ new Map();
const furthestMeasurements = /* @__PURE__ */ new Map();
for (let m = index3 - 1; m >= 0; m--) {
const measurement = measurements[m];
if (furthestMeasurementsFound.has(measurement.lane)) {
continue;
}
const previousFurthestMeasurement = furthestMeasurements.get(
measurement.lane
);
if (previousFurthestMeasurement == null || measurement.end > previousFurthestMeasurement.end) {
furthestMeasurements.set(measurement.lane, measurement);
} else if (measurement.end < previousFurthestMeasurement.end) {
furthestMeasurementsFound.set(measurement.lane, true);
}
if (furthestMeasurementsFound.size === this.options.lanes) {
break;
}
}
return furthestMeasurements.size === this.options.lanes ? Array.from(furthestMeasurements.values()).sort((a, b) => {
if (a.end === b.end) {
return a.index - b.index;
}
return a.end - b.end;
})[0] : void 0;
};
this.getMeasurementOptions = memo(
() => [
this.options.count,
this.options.paddingStart,
this.options.scrollMargin,
this.options.getItemKey,
this.options.enabled
],
(count2, paddingStart, scrollMargin, getItemKey, enabled) => {
this.pendingMeasuredCacheIndexes = [];
return {
count: count2,
paddingStart,
scrollMargin,
getItemKey,
enabled
};
},
{
key: false
}
);
this.getMeasurements = memo(
() => [this.getMeasurementOptions(), this.itemSizeCache],
({ count: count2, paddingStart, scrollMargin, getItemKey, enabled }, itemSizeCache) => {
if (!enabled) {
this.measurementsCache = [];
this.itemSizeCache.clear();
return [];
}
if (this.measurementsCache.length === 0) {
this.measurementsCache = this.options.initialMeasurementsCache;
this.measurementsCache.forEach((item) => {
this.itemSizeCache.set(item.key, item.size);
});
}
const min2 = this.pendingMeasuredCacheIndexes.length > 0 ? Math.min(...this.pendingMeasuredCacheIndexes) : 0;
this.pendingMeasuredCacheIndexes = [];
const measurements = this.measurementsCache.slice(0, min2);
for (let i = min2; i < count2; i++) {
const key = getItemKey(i);
const furthestMeasurement = this.options.lanes === 1 ? measurements[i - 1] : this.getFurthestMeasurement(measurements, i);
const start = furthestMeasurement ? furthestMeasurement.end + this.options.gap : paddingStart + scrollMargin;
const measuredSize = itemSizeCache.get(key);
const size3 = typeof measuredSize === "number" ? measuredSize : this.options.estimateSize(i);
const end = start + size3;
const lane = furthestMeasurement ? furthestMeasurement.lane : i % this.options.lanes;
measurements[i] = {
index: i,
start,
size: size3,
end,
key,
lane
};
}
this.measurementsCache = measurements;
return measurements;
},
{
key: "getMeasurements",
debug: () => this.options.debug
}
);
this.calculateRange = memo(
() => [
this.getMeasurements(),
this.getSize(),
this.getScrollOffset(),
this.options.lanes
],
(measurements, outerSize, scrollOffset, lanes) => {
return this.range = measurements.length > 0 && outerSize > 0 ? calculateRange({
measurements,
outerSize,
scrollOffset,
lanes
}) : null;
},
{
key: "calculateRange",
debug: () => this.options.debug
}
);
this.getVirtualIndexes = memo(
() => {
let startIndex = null;
let endIndex = null;
const range = this.calculateRange();
if (range) {
startIndex = range.startIndex;
endIndex = range.endIndex;
}
this.maybeNotify.updateDeps([this.isScrolling, startIndex, endIndex]);
return [
this.options.rangeExtractor,
this.options.overscan,
this.options.count,
startIndex,
endIndex
];
},
(rangeExtractor, overscan, count2, startIndex, endIndex) => {
return startIndex === null || endIndex === null ? [] : rangeExtractor({
startIndex,
endIndex,
overscan,
count: count2
});
},
{
key: "getVirtualIndexes",
debug: () => this.options.debug
}
);
this.indexFromElement = (node) => {
const attributeName = this.options.indexAttribute;
const indexStr = node.getAttribute(attributeName);
if (!indexStr) {
console.warn(
`Missing attribute name '${attributeName}={index}' on measured element.`
);
return -1;
}
return parseInt(indexStr, 10);
};
this._measureElement = (node, entry) => {
const index3 = this.indexFromElement(node);
const item = this.measurementsCache[index3];
if (!item) {
return;
}
const key = item.key;
const prevNode = this.elementsCache.get(key);
if (prevNode !== node) {
if (prevNode) {
this.observer.unobserve(prevNode);
}
this.observer.observe(node);
this.elementsCache.set(key, node);
}
if (node.isConnected) {
this.resizeItem(index3, this.options.measureElement(node, entry, this));
}
};
this.resizeItem = (index3, size3) => {
var _a3;
const item = this.measurementsCache[index3];
if (!item) {
return;
}
const itemSize = (_a3 = this.itemSizeCache.get(item.key)) != null ? _a3 : item.size;
const delta = size3 - itemSize;
if (delta !== 0) {
if (this.shouldAdjustScrollPositionOnItemSizeChange !== void 0 ? this.shouldAdjustScrollPositionOnItemSizeChange(item, delta, this) : item.start < this.getScrollOffset() + this.scrollAdjustments) {
if (this.options.debug) {
console.info("correction", delta);
}
this._scrollToOffset(this.getScrollOffset(), {
adjustments: this.scrollAdjustments += delta,
behavior: void 0
});
}
this.pendingMeasuredCacheIndexes.push(item.index);
this.itemSizeCache = new Map(this.itemSizeCache.set(item.key, size3));
this.notify(false);
}
};
this.measureElement = (node) => {
if (!node) {
this.elementsCache.forEach((cached, key) => {
if (!cached.isConnected) {
this.observer.unobserve(cached);
this.elementsCache.delete(key);
}
});
return;
}
this._measureElement(node, void 0);
};
this.getVirtualItems = memo(
() => [this.getVirtualIndexes(), this.getMeasurements()],
(indexes, measurements) => {
const virtualItems = [];
for (let k = 0, len = indexes.length; k < len; k++) {
const i = indexes[k];
const measurement = measurements[i];
virtualItems.push(measurement);
}
return virtualItems;
},
{
key: "getVirtualItems",
debug: () => this.options.debug
}
);
this.getVirtualItemForOffset = (offset3) => {
const measurements = this.getMeasurements();
if (measurements.length === 0) {
return void 0;
}
return notUndefined(
measurements[findNearestBinarySearch(
0,
measurements.length - 1,
(index3) => notUndefined(measurements[index3]).start,
offset3
)]
);
};
this.getOffsetForAlignment = (toOffset, align, itemSize = 0) => {
const size3 = this.getSize();
const scrollOffset = this.getScrollOffset();
if (align === "auto") {
align = toOffset >= scrollOffset + size3 ? "end" : "start";
}
if (align === "center") {
toOffset += (itemSize - size3) / 2;
} else if (align === "end") {
toOffset -= size3;
}
const maxOffset = this.getTotalSize() - size3;
return Math.max(Math.min(maxOffset, toOffset), 0);
};
this.getOffsetForIndex = (index3, align = "auto") => {
index3 = Math.max(0, Math.min(index3, this.options.count - 1));
const item = this.measurementsCache[index3];
if (!item) {
return void 0;
}
const size3 = this.getSize();
const scrollOffset = this.getScrollOffset();
if (align === "auto") {
if (item.end >= scrollOffset + size3 - this.options.scrollPaddingEnd) {
align = "end";
} else if (item.start <= scrollOffset + this.options.scrollPaddingStart) {
align = "start";
} else {
return [scrollOffset, align];
}
}
const toOffset = align === "end" ? item.end + this.options.scrollPaddingEnd : item.start - this.options.scrollPaddingStart;
return [
this.getOffsetForAlignment(toOffset, align, item.size),
align
];
};
this.isDynamicMode = () => this.elementsCache.size > 0;
this.cancelScrollToIndex = () => {
if (this.scrollToIndexTimeoutId !== null && this.targetWindow) {
this.targetWindow.clearTimeout(this.scrollToIndexTimeoutId);
this.scrollToIndexTimeoutId = null;
}
};
this.scrollToOffset = (toOffset, { align = "start", behavior } = {}) => {
this.cancelScrollToIndex();
if (behavior === "smooth" && this.isDynamicMode()) {
console.warn(
"The `smooth` scroll behavior is not fully supported with dynamic size."
);
}
this._scrollToOffset(this.getOffsetForAlignment(toOffset, align), {
adjustments: void 0,
behavior
});
};
this.scrollToIndex = (index3, { align: initialAlign = "auto", behavior } = {}) => {
index3 = Math.max(0, Math.min(index3, this.options.count - 1));
this.cancelScrollToIndex();
if (behavior === "smooth" && this.isDynamicMode()) {
console.warn(
"The `smooth` scroll behavior is not fully supported with dynamic size."
);
}
const offsetAndAlign = this.getOffsetForIndex(index3, initialAlign);
if (!offsetAndAlign)
return;
const [offset3, align] = offsetAndAlign;
this._scrollToOffset(offset3, { adjustments: void 0, behavior });
if (behavior !== "smooth" && this.isDynamicMode() && this.targetWindow) {
this.scrollToIndexTimeoutId = this.targetWindow.setTimeout(() => {
this.scrollToIndexTimeoutId = null;
const elementInDOM = this.elementsCache.has(
this.options.getItemKey(index3)
);
if (elementInDOM) {
const result = this.getOffsetForIndex(index3, align);
if (!result)
return;
const [latestOffset] = result;
const currentScrollOffset = this.getScrollOffset();
if (!approxEqual(latestOffset, currentScrollOffset)) {
this.scrollToIndex(index3, { align, behavior });
}
} else {
this.scrollToIndex(index3, { align, behavior });
}
});
}
};
this.scrollBy = (delta, { behavior } = {}) => {
this.cancelScrollToIndex();
if (behavior === "smooth" && this.isDynamicMode()) {
console.warn(
"The `smooth` scroll behavior is not fully supported with dynamic size."
);
}
this._scrollToOffset(this.getScrollOffset() + delta, {
adjustments: void 0,
behavior
});
};
this.getTotalSize = () => {
var _a4;
var _a3;
const measurements = this.getMeasurements();
let end;
if (measurements.length === 0) {
end = this.options.paddingStart;
} else if (this.options.lanes === 1) {
end = (_a4 = (_a3 = measurements[measurements.length - 1]) == null ? void 0 : _a3.end) != null ? _a4 : 0;
} else {
const endByLane = Array(this.options.lanes).fill(null);
let endIndex = measurements.length - 1;
while (endIndex >= 0 && endByLane.some((val) => val === null)) {
const item = measurements[endIndex];
if (endByLane[item.lane] === null) {
endByLane[item.lane] = item.end;
}
endIndex--;
}
end = Math.max(...endByLane.filter((val) => val !== null));
}
return Math.max(
end - this.options.scrollMargin + this.options.paddingEnd,
0
);
};
this._scrollToOffset = (offset3, {
adjustments,
behavior
}) => {
this.options.scrollToFn(offset3, { behavior, adjustments }, this);
};
this.measure = () => {
this.itemSizeCache = /* @__PURE__ */ new Map();
this.notify(false);
};
this.setOptions(opts);
}
};
var findNearestBinarySearch = (low, high, getCurrentValue, value) => {
while (low <= high) {
const middle = (low + high) / 2 | 0;
const currentValue = getCurrentValue(middle);
if (currentValue < value) {
low = middle + 1;
} else if (currentValue > value) {
high = middle - 1;
} else {
return middle;
}
}
if (low > 0) {
return low - 1;
} else {
return 0;
}
};
function calculateRange({
measurements,
outerSize,
scrollOffset,
lanes
}) {
const lastIndex = measurements.length - 1;
const getOffset = (index3) => measurements[index3].start;
if (measurements.length <= lanes) {
return {
startIndex: 0,
endIndex: lastIndex
};
}
let startIndex = findNearestBinarySearch(
0,
lastIndex,
getOffset,
scrollOffset
);
let endIndex = startIndex;
if (lanes === 1) {
while (endIndex < lastIndex && measurements[endIndex].end < scrollOffset + outerSize) {
endIndex++;
}
} else if (lanes > 1) {
const endPerLane = Array(lanes).fill(0);
while (endIndex < lastIndex && endPerLane.some((pos) => pos < scrollOffset + outerSize)) {
const item = measurements[endIndex];
endPerLane[item.lane] = item.end;
endIndex++;
}
const startPerLane = Array(lanes).fill(scrollOffset + outerSize);
while (startIndex >= 0 && startPerLane.some((pos) => pos >= scrollOffset)) {
const item = measurements[startIndex];
startPerLane[item.lane] = item.start;
startIndex--;
}
startIndex = Math.max(0, startIndex - startIndex % lanes);
endIndex = Math.min(lastIndex, endIndex + (lanes - 1 - endIndex % lanes));
}
return { startIndex, endIndex };
}
// ../../node_modules/@tanstack/react-virtual/dist/esm/index.js
var useIsomorphicLayoutEffect = typeof document !== "undefined" ? React11.useLayoutEffect : React11.useEffect;
function useVirtualizerBase(options) {
const rerender = React11.useReducer(() => ({}), {})[1];
const resolvedOptions = {
...options,
onChange: (instance2, sync) => {
var _a3;
if (sync) {
(0, import_react_dom3.flushSync)(rerender);
} else {
rerender();
}
(_a3 = options.onChange) == null ? void 0 : _a3.call(options, instance2, sync);
}
};
const [instance] = React11.useState(
() => new Virtualizer(resolvedOptions)
);
instance.setOptions(resolvedOptions);
useIsomorphicLayoutEffect(() => {
return instance._didMount();
}, []);
useIsomorphicLayoutEffect(() => {
return instance._willUpdate();
});
return instance;
}
function useVirtualizer(options) {
return useVirtualizerBase({
observeElementRect,
observeElementOffset,
scrollToFn: elementScroll,
...options
});
}
// src/components/combobox/combobox.tsx
var import_react59 = __toESM(require("react"), 1);
var import_react_dom8 = require("react-dom");
// src/hooks/use-by-comparator.ts
var import_react30 = require("react");
function defaultBy(a, z) {
if (a !== null && z !== null && typeof a === "object" && typeof z === "object" && "id" in a && "id" in z) {
return a.id === z.id;
}
return a === z;
}
function useByComparator(by = defaultBy) {
return (0, import_react30.useCallback)(
(a, z) => {
if (typeof by === "string") {
let property = by;
return (a == null ? void 0 : a[property]) === (z == null ? void 0 : z[property]);
}
return by(a, z);
},
[by]
);
}
// src/hooks/use-element-size.ts
var import_react31 = require("react");
function computeSize(element) {
if (element === null)
return { width: 0, height: 0 };
let { width, height } = element.getBoundingClientRect();
return { width, height };
}
function useElementSize(enabled, element, unit = false) {
let [size3, setSize] = (0, import_react31.useState)(() => computeSize(element));
useIsoMorphicEffect(() => {
if (!element)
return;
if (!enabled)
return;
let d = disposables();
d.requestAnimationFrame(function run() {
d.requestAnimationFrame(run);
setSize((current) => {
let newSize = computeSize(element);
if (newSize.width === current.width && newSize.height === current.height) {
return current;
}
return newSize;
});
});
return () => {
d.dispose();
};
}, [element, enabled]);
if (unit) {
return {
width: `${size3.width}px`,
height: `${size3.height}px`
};
}
return size3;
}
// src/hooks/use-handle-toggle.tsx
var import_react32 = require("react");
function useHandleToggle(cb) {
let pointerTypeRef = (0, import_react32.useRef)(null);
let handlePointerDown = useEvent((event) => {
pointerTypeRef.current = event.pointerType;
if (isDisabledReactIssue7711(event.currentTarget))
return;
if (event.pointerType !== "mouse")
return;
if (event.button !== 0 /* Left */)
return;
event.preventDefault();
cb(event);
});
let handleClick = useEvent((event) => {
if (pointerTypeRef.current === "mouse")
return;
if (isDisabledReactIssue7711(event.currentTarget))
return;
cb(event);
});
return {
onPointerDown: handlePointerDown,
onClick: handleClick
};
}
// src/hooks/use-is-top-layer.ts
var import_react33 = require("react");
// src/utils/default-map.ts
var DefaultMap = class extends Map {
constructor(factory) {
super();
this.factory = factory;
}
get(key) {
let value = super.get(key);
if (value === void 0) {
value = this.factory(key);
this.set(key, value);
}
return value;
}
};
// src/machine.ts
var _state, _eventSubscribers, _subscribers;
var Machine = class {
constructor(initialState) {
__privateAdd(this, _state, {});
__privateAdd(this, _eventSubscribers, new DefaultMap(() => /* @__PURE__ */ new Set()));
__privateAdd(this, _subscribers, /* @__PURE__ */ new Set());
__publicField(this, "disposables", disposables());
__privateSet(this, _state, initialState);
if (env.isServer) {
this.disposables.microTask(() => {
this.dispose();
});
}
}
dispose() {
this.disposables.dispose();
}
get state() {
return __privateGet(this, _state);
}
subscribe(selector, callback) {
if (env.isServer)
return () => {
};
let subscriber = {
selector,
callback,
current: selector(__privateGet(this, _state))
};
__privateGet(this, _subscribers).add(subscriber);
return this.disposables.add(() => {
__privateGet(this, _subscribers).delete(subscriber);
});
}
on(type, callback) {
if (env.isServer)
return () => {
};
__privateGet(this, _eventSubscribers).get(type).add(callback);
return this.disposables.add(() => {
__privateGet(this, _eventSubscribers).get(type).delete(callback);
});
}
send(event) {
let newState = this.reduce(__privateGet(this, _state), event);
if (newState === __privateGet(this, _state))
return;
__privateSet(this, _state, newState);
for (let subscriber of __privateGet(this, _subscribers)) {
let slice = subscriber.selector(__privateGet(this, _state));
if (shallowEqual(subscriber.current, slice))
continue;
subscriber.current = slice;
subscriber.callback(slice);
}
for (let callback of __privateGet(this, _eventSubscribers).get(event.type)) {
callback(__privateGet(this, _state), event);
}
}
};
_state = new WeakMap();
_eventSubscribers = new WeakMap();
_subscribers = new WeakMap();
function shallowEqual(a, b) {
if (Object.is(a, b))
return true;
if (typeof a !== "object" || a === null || typeof b !== "object" || b === null)
return false;
if (Array.isArray(a) && Array.isArray(b)) {
if (a.length !== b.length)
return false;
return compareEntries(a[Symbol.iterator](), b[Symbol.iterator]());
}
if (a instanceof Map && b instanceof Map || a instanceof Set && b instanceof Set) {
if (a.size !== b.size)
return false;
return compareEntries(a.entries(), b.entries());
}
if (isPlainObject2(a) && isPlainObject2(b)) {
return compareEntries(
Object.entries(a)[Symbol.iterator](),
Object.entries(b)[Symbol.iterator]()
);
}
return false;
}
function compareEntries(a, b) {
do {
let aResult = a.next();
let bResult = b.next();
if (aResult.done && bResult.done)
return true;
if (aResult.done || bResult.done)
return false;
if (!Object.is(aResult.value, bResult.value))
return false;
} while (true);
}
function isPlainObject2(value) {
if (Object.prototype.toString.call(value) !== "[object Object]") {
return false;
}
let prototype = Object.getPrototypeOf(value);
return prototype === null || Object.getPrototypeOf(prototype) === null;
}
function batch(setup) {
let [callback, handle] = setup();
let d = disposables();
return (...args) => {
callback(...args);
d.dispose();
d.microTask(handle);
};
}
// src/machines/stack-machine.ts
var reducers = {
[0 /* Push */](state, action) {
let id = action.id;
let stack = state.stack;
let idx = state.stack.indexOf(id);
if (idx !== -1) {
let copy = state.stack.slice();
copy.splice(idx, 1);
copy.push(id);
stack = copy;
return { ...state, stack };
}
return { ...state, stack: [...state.stack, id] };
},
[1 /* Pop */](state, action) {
let id = action.id;
let idx = state.stack.indexOf(id);
if (idx === -1)
return state;
let copy = state.stack.slice();
copy.splice(idx, 1);
return { ...state, stack: copy };
}
};
var StackMachine = class extends Machine {
constructor() {
super(...arguments);
__publicField(this, "actions", {
push: (id) => this.send({ type: 0 /* Push */, id }),
pop: (id) => this.send({ type: 1 /* Pop */, id })
});
__publicField(this, "selectors", {
isTop: (state, id) => state.stack[state.stack.length - 1] === id,
inStack: (state, id) => state.stack.includes(id)
});
}
static new() {
return new StackMachine({ stack: [] });
}
reduce(state, action) {
return match(action.type, reducers, state, action);
}
};
var stackMachines = new DefaultMap(() => StackMachine.new());
// src/react-glue.tsx
var import_with_selector = require("use-sync-external-store/with-selector");
function useSlice(machine, selector, compare = shallowEqual) {
return (0, import_with_selector.useSyncExternalStoreWithSelector)(
useEvent((onStoreChange) => machine.subscribe(identity, onStoreChange)),
useEvent(() => machine.state),
useEvent(() => machine.state),
useEvent(selector),
compare
);
}
function identity(value) {
return value;
}
// src/hooks/use-is-top-layer.ts
function useIsTopLayer(enabled, scope) {
let id = (0, import_react33.useId)();
let stackMachine = stackMachines.get(scope);
let [isTop, onStack] = useSlice(
stackMachine,
(0, import_react33.useCallback)(
(state) => [
stackMachine.selectors.isTop(state, id),
stackMachine.selectors.inStack(state, id)
],
[stackMachine, id]
)
);
useIsoMorphicEffect(() => {
if (!enabled)
return;
stackMachine.actions.push(id);
return () => stackMachine.actions.pop(id);
}, [stackMachine, enabled, id]);
if (!enabled)
return false;
if (onStack)
return isTop;
return true;
}
// src/hooks/use-inert-others.tsx
var originals = /* @__PURE__ */ new Map();
var counts = /* @__PURE__ */ new Map();
function markInert(element) {
var _a3;
let count2 = (_a3 = counts.get(element)) != null ? _a3 : 0;
counts.set(element, count2 + 1);
if (count2 !== 0)
return () => markNotInert(element);
originals.set(element, {
"aria-hidden": element.getAttribute("aria-hidden"),
inert: element.inert
});
element.setAttribute("aria-hidden", "true");
element.inert = true;
return () => markNotInert(element);
}
function markNotInert(element) {
var _a3;
let count2 = (_a3 = counts.get(element)) != null ? _a3 : 1;
if (count2 === 1)
counts.delete(element);
else
counts.set(element, count2 - 1);
if (count2 !== 1)
return;
let original = originals.get(element);
if (!original)
return;
if (original["aria-hidden"] === null)
element.removeAttribute("aria-hidden");
else
element.setAttribute("aria-hidden", original["aria-hidden"]);
element.inert = original.inert;
originals.delete(element);
}
function useInertOthers(enabled, {
allowed,
disallowed
} = {}) {
let isTopLayer = useIsTopLayer(enabled, "inert-others");
useIsoMorphicEffect(() => {
var _a3, _b2;
if (!isTopLayer)
return;
let d = disposables();
for (let element of (_a3 = disallowed == null ? void 0 : disallowed()) != null ? _a3 : []) {
if (!element)
continue;
d.add(markInert(element));
}
let allowedElements = (_b2 = allowed == null ? void 0 : allowed()) != null ? _b2 : [];
for (let element of allowedElements) {
if (!element)
continue;
let ownerDocument = getOwnerDocument(element);
if (!ownerDocument)
continue;
let parent = element.parentElement;
while (parent && parent !== ownerDocument.body) {
for (let node of parent.children) {
if (allowedElements.some((el) => node.contains(el)))
continue;
d.add(markInert(node));
}
parent = parent.parentElement;
}
}
return d.dispose;
}, [isTopLayer, allowed, disallowed]);
}
// src/hooks/use-on-disappear.ts
var import_react34 = require("react");
function useOnDisappear(enabled, ref, cb) {
let listenerRef = useLatestValue((element) => {
let rect = element.getBoundingClientRect();
if (rect.x === 0 && rect.y === 0 && rect.width === 0 && rect.height === 0) {
cb();
}
});
(0, import_react34.useEffect)(() => {
if (!enabled)
return;
let element = ref === null ? null : isHTMLElement(ref) ? ref : ref.current;
if (!element)
return;
let d = disposables();
if (typeof ResizeObserver !== "undefined") {
let observer = new ResizeObserver(() => listenerRef.current(element));
observer.observe(element);
d.add(() => observer.disconnect());
}
if (typeof IntersectionObserver !== "undefined") {
let observer = new IntersectionObserver(() => listenerRef.current(element));
observer.observe(element);
d.add(() => observer.disconnect());
}
return () => d.dispose();
}, [ref, listenerRef, enabled]);
}
// src/hooks/use-outside-click.ts
var import_react37 = require("react");
// src/utils/focus-management.ts
var focusableSelector = [
"[contentEditable=true]",
"[tabindex]",
"a[href]",
"area[href]",
"button:not([disabled])",
"iframe",
"input:not([disabled])",
"select:not([disabled])",
// TODO: Re-enable once we bump JSDOM
// 'details:not(:has(> summary))',
"details>summary",
"textarea:not([disabled])"
].map(
false ? (
// TODO: Remove this once JSDOM fixes the issue where an element that is
// "hidden" can be the document.activeElement, because this is not possible
// in real browsers.
(selector) => `${selector}:not([tabindex='-1']):not([style*='display: none'])`
) : (selector) => `${selector}:not([tabindex='-1'])`
).join(",");
var autoFocusableSelector = [
// In a perfect world this was just `autofocus`, but React doesn't pass `autofocus` to the DOM...
"[data-autofocus]"
].map(
false ? (
// TODO: Remove this once JSDOM fixes the issue where an element that is
// "hidden" can be the document.activeElement, because this is not possible
// in real browsers.
(selector) => `${selector}:not([tabindex='-1']):not([style*='display: none'])`
) : (selector) => `${selector}:not([tabindex='-1'])`
).join(",");
function getFocusableElements(container = document.body) {
if (container == null)
return [];
return Array.from(container.querySelectorAll(focusableSelector)).sort(
// We want to move `tabIndex={0}` to the end of the list, this is what the browser does as well.
(a, z) => Math.sign((a.tabIndex || Number.MAX_SAFE_INTEGER) - (z.tabIndex || Number.MAX_SAFE_INTEGER))
);
}
function getAutoFocusableElements(container = document.body) {
if (container == null)
return [];
return Array.from(container.querySelectorAll(autoFocusableSelector)).sort(
// We want to move `tabIndex={0}` to the end of the list, this is what the browser does as well.
(a, z) => Math.sign((a.tabIndex || Number.MAX_SAFE_INTEGER) - (z.tabIndex || Number.MAX_SAFE_INTEGER))
);
}
function isFocusableElement(element, mode = 0 /* Strict */) {
var _a3;
if (element === ((_a3 = getOwnerDocument(element)) == null ? void 0 : _a3.body))
return false;
return match(mode, {
[0 /* Strict */]() {
return element.matches(focusableSelector);
},
[1 /* Loose */]() {
let next = element;
while (next !== null) {
if (next.matches(focusableSelector))
return true;
next = next.parentElement;
}
return false;
}
});
}
function restoreFocusIfNecessary(element) {
disposables().nextFrame(() => {
let activeElement2 = getActiveElement(element);
if (activeElement2 && isHTMLorSVGElement(activeElement2) && !isFocusableElement(activeElement2, 0 /* Strict */)) {
focusElement(element);
}
});
}
if (typeof window !== "undefined" && typeof document !== "undefined") {
document.addEventListener(
"keydown",
(event) => {
if (event.metaKey || event.altKey || event.ctrlKey) {
return;
}
document.documentElement.dataset.headlessuiFocusVisible = "";
},
true
);
document.addEventListener(
"click",
(event) => {
if (event.detail === 1 /* Mouse */) {
delete document.documentElement.dataset.headlessuiFocusVisible;
} else if (event.detail === 0 /* Keyboard */) {
document.documentElement.dataset.headlessuiFocusVisible = "";
}
},
true
);
}
function focusElement(element) {
element == null ? void 0 : element.focus({ preventScroll: true });
}
var selectableSelector = ["textarea", "input"].join(",");
function isSelectableElement(element) {
var _a3, _b2;
return (_b2 = (_a3 = element == null ? void 0 : element.matches) == null ? void 0 : _a3.call(element, selectableSelector)) != null ? _b2 : false;
}
function sortByDomNode(nodes, resolveKey = (i) => i) {
return nodes.slice().sort((aItem, zItem) => {
let a = resolveKey(aItem);
let z = resolveKey(zItem);
if (a === null || z === null)
return 0;
let position = a.compareDocumentPosition(z);
if (position & Node.DOCUMENT_POSITION_FOLLOWING)
return -1;
if (position & Node.DOCUMENT_POSITION_PRECEDING)
return 1;
return 0;
});
}
function focusFrom(current, focus, container = current === null ? document.body : getRootNode(current)) {
return focusIn(getFocusableElements(container), focus, { relativeTo: current });
}
function focusIn(container, focus, {
sorted = true,
relativeTo = null,
skipElements = []
} = {}) {
let root = Array.isArray(container) ? container.length > 0 ? getRootNode(container[0]) : document : getRootNode(container);
let elements = Array.isArray(container) ? sorted ? sortByDomNode(container) : container : focus & 64 /* AutoFocus */ ? getAutoFocusableElements(container) : getFocusableElements(container);
if (skipElements.length > 0 && elements.length > 1) {
elements = elements.filter(
(element) => !skipElements.some(
(skipElement) => skipElement != null && "current" in skipElement ? (skipElement == null ? void 0 : skipElement.current) === element : skipElement === element
// Handle HTMLElement directly
)
);
}
relativeTo = relativeTo != null ? relativeTo : root == null ? void 0 : root.activeElement;
let direction = (() => {
if (focus & (1 /* First */ | 4 /* Next */))
return 1 /* Next */;
if (focus & (2 /* Previous */ | 8 /* Last */))
return -1 /* Previous */;
throw new Error("Missing Focus.First, Focus.Previous, Focus.Next or Focus.Last");
})();
let startIndex = (() => {
if (focus & 1 /* First */)
return 0;
if (focus & 2 /* Previous */)
return Math.max(0, elements.indexOf(relativeTo)) - 1;
if (focus & 4 /* Next */)
return Math.max(0, elements.indexOf(relativeTo)) + 1;
if (focus & 8 /* Last */)
return elements.length - 1;
throw new Error("Missing Focus.First, Focus.Previous, Focus.Next or Focus.Last");
})();
let focusOptions = focus & 32 /* NoScroll */ ? { preventScroll: true } : {};
let offset3 = 0;
let total = elements.length;
let next = void 0;
do {
if (offset3 >= total || offset3 + total <= 0)
return 0 /* Error */;
let nextIdx = startIndex + offset3;
if (focus & 16 /* WrapAround */) {
nextIdx = (nextIdx + total) % total;
} else {
if (nextIdx < 0)
return 3 /* Underflow */;
if (nextIdx >= total)
return 1 /* Overflow */;
}
next = elements[nextIdx];
next == null ? void 0 : next.focus(focusOptions);
offset3 += direction;
} while (next !== getActiveElement(next));
if (focus & (4 /* Next */ | 2 /* Previous */) && isSelectableElement(next)) {
next.select();
}
return 2 /* Success */;
}
// src/utils/platform.ts
function isIOS() {
return (
// Check if it is an iPhone
/iPhone/gi.test(window.navigator.platform) || // Check if it is an iPad. iPad reports itself as "MacIntel", but we can check if it is a touch
// screen. Let's hope that Apple doesn't release a touch screen Mac (or maybe this would then
// work as expected 🤔).
/Mac/gi.test(window.navigator.platform) && window.navigator.maxTouchPoints > 0
);
}
function isAndroid() {
return /Android/gi.test(window.navigator.userAgent);
}
function isMobile() {
return isIOS() || isAndroid();
}
// src/hooks/use-document-event.ts
var import_react35 = require("react");
function useDocumentEvent(enabled, type, listener, options) {
let listenerRef = useLatestValue(listener);
(0, import_react35.useEffect)(() => {
if (!enabled)
return;
function handler(event) {
listenerRef.current(event);
}
document.addEventListener(type, handler, options);
return () => document.removeEventListener(type, handler, options);
}, [enabled, type, options]);
}
// src/hooks/use-window-event.ts
var import_react36 = require("react");
function useWindowEvent(enabled, type, listener, options) {
let listenerRef = useLatestValue(listener);
(0, import_react36.useEffect)(() => {
if (!enabled)
return;
function handler(event) {
listenerRef.current(event);
}
window.addEventListener(type, handler, options);
return () => window.removeEventListener(type, handler, options);
}, [enabled, type, options]);
}
// src/hooks/use-outside-click.ts
var MOVE_THRESHOLD_PX = 30;
function useOutsideClick(enabled, containers, cb) {
let cbRef = useLatestValue(cb);
let handleOutsideClick = (0, import_react37.useCallback)(
function handleOutsideClick2(event, resolveTarget) {
if (event.defaultPrevented)
return;
let target = resolveTarget(event);
if (target === null)
return;
if (!target.getRootNode().contains(target))
return;
if (!target.isConnected)
return;
let _containers = function resolve(containers2) {
if (typeof containers2 === "function") {
return resolve(containers2());
}
if (Array.isArray(containers2)) {
return containers2;
}
if (containers2 instanceof Set) {
return containers2;
}
return [containers2];
}(containers);
for (let container of _containers) {
if (container === null)
continue;
if (container.contains(target)) {
return;
}
if (event.composed && event.composedPath().includes(container)) {
return;
}
}
if (
// This check allows us to know whether or not we clicked on a
// "focusable" element like a button or an input. This is a backwards
// compatibility check so that you can open a
and click on
// another which should close Menu A and open Menu B. We might
// revisit that so that you will require 2 clicks instead.
!isFocusableElement(target, 1 /* Loose */) && // This could be improved, but the `Combobox.Button` adds tabIndex={-1}
// to make it unfocusable via the keyboard so that tabbing to the next
// item from the input doesn't first go to the button.
target.tabIndex !== -1
) {
event.preventDefault();
}
return cbRef.current(event, target);
},
[cbRef, containers]
);
let initialClickTarget = (0, import_react37.useRef)(null);
useDocumentEvent(
enabled,
"pointerdown",
(event) => {
var _a3, _b2;
if (isMobile())
return;
initialClickTarget.current = ((_b2 = (_a3 = event.composedPath) == null ? void 0 : _a3.call(event)) == null ? void 0 : _b2[0]) || event.target;
},
true
);
useDocumentEvent(
enabled,
"pointerup",
(event) => {
if (isMobile())
return;
if (!initialClickTarget.current)
return;
let target = initialClickTarget.current;
initialClickTarget.current = null;
return handleOutsideClick(event, () => target);
},
// We will use the `capture` phase so that layers in between with `event.stopPropagation()`
// don't "cancel" this outside click check. E.g.: A `Menu` inside a `DialogPanel` if the `Menu`
// is open, and you click outside of it in the `DialogPanel` the `Menu` should close. However,
// the `DialogPanel` has a `onClick(e) { e.stopPropagation() }` which would cancel this.
true
);
let startPosition = (0, import_react37.useRef)({ x: 0, y: 0 });
useDocumentEvent(
enabled,
"touchstart",
(event) => {
startPosition.current.x = event.touches[0].clientX;
startPosition.current.y = event.touches[0].clientY;
},
true
);
useDocumentEvent(
enabled,
"touchend",
(event) => {
let endPosition = { x: event.changedTouches[0].clientX, y: event.changedTouches[0].clientY };
if (Math.abs(endPosition.x - startPosition.current.x) >= MOVE_THRESHOLD_PX || Math.abs(endPosition.y - startPosition.current.y) >= MOVE_THRESHOLD_PX) {
return;
}
return handleOutsideClick(event, () => {
if (isHTMLorSVGElement(event.target)) {
return event.target;
}
return null;
});
},
// We will use the `capture` phase so that layers in between with `event.stopPropagation()`
// don't "cancel" this outside click check. E.g.: A `Menu` inside a `DialogPanel` if the `Menu`
// is open, and you click outside of it in the `DialogPanel` the `Menu` should close. However,
// the `DialogPanel` has a `onClick(e) { e.stopPropagation() }` which would cancel this.
true
);
useWindowEvent(
enabled,
"blur",
(event) => {
return handleOutsideClick(event, () => {
return isHTMLIframeElement(window.document.activeElement) ? window.document.activeElement : null;
});
},
true
);
}
// src/hooks/use-owner.ts
var import_react38 = require("react");
function useOwnerDocument(...args) {
return (0, import_react38.useMemo)(() => getOwnerDocument(...args), [...args]);
}
function useRootDocument(...args) {
return (0, import_react38.useMemo)(() => getRootNode(...args), [...args]);
}
// src/hooks/use-quick-release.ts
var import_react39 = require("react");
var Action = {
/** Do nothing */
Ignore: { kind: 0 /* Ignore */ },
/** Select the current item */
Select: (target) => ({ kind: 1 /* Select */, target }),
/** Close the dropdown */
Close: { kind: 2 /* Close */ }
};
var POINTER_HOLD_THRESHOLD = 200;
var POINTER_MOVEMENT_THRESHOLD = 5;
function useQuickRelease(enabled, {
trigger,
action,
close,
select
}) {
let triggeredAtRef = (0, import_react39.useRef)(null);
let startXRef = (0, import_react39.useRef)(null);
let startYRef = (0, import_react39.useRef)(null);
useDocumentEvent(enabled && trigger !== null, "pointerdown", (e) => {
if (!isNode(e == null ? void 0 : e.target))
return;
if (!(trigger == null ? void 0 : trigger.contains(e.target)))
return;
startXRef.current = e.x;
startYRef.current = e.y;
triggeredAtRef.current = e.timeStamp;
});
useDocumentEvent(
enabled && trigger !== null,
"pointerup",
(e) => {
var _a3, _b2;
let triggeredAt = triggeredAtRef.current;
if (triggeredAt === null)
return;
triggeredAtRef.current = null;
if (!isHTMLorSVGElement(e.target))
return;
if (Math.abs(e.x - ((_a3 = startXRef.current) != null ? _a3 : e.x)) < POINTER_MOVEMENT_THRESHOLD && Math.abs(e.y - ((_b2 = startYRef.current) != null ? _b2 : e.y)) < POINTER_MOVEMENT_THRESHOLD) {
return;
}
let result = action(e);
switch (result.kind) {
case 0 /* Ignore */:
return;
case 1 /* Select */: {
if (e.timeStamp - triggeredAt > POINTER_HOLD_THRESHOLD) {
select(result.target);
close();
}
break;
}
case 2 /* Close */: {
close();
break;
}
}
},
{ capture: true }
);
}
// src/hooks/use-refocusable-input.ts
var import_react41 = require("react");
// src/hooks/use-event-listener.ts
var import_react40 = require("react");
function useEventListener(element, type, listener, options) {
let listenerRef = useLatestValue(listener);
(0, import_react40.useEffect)(() => {
element = element != null ? element : window;
function handler(event) {
listenerRef.current(event);
}
element.addEventListener(type, handler, options);
return () => element.removeEventListener(type, handler, options);
}, [element, type, options]);
}
// src/hooks/use-refocusable-input.ts
function useRefocusableInput(input) {
let info = (0, import_react41.useRef)({
value: "",
selectionStart: null,
selectionEnd: null
});
useEventListener(input, "blur", (event) => {
let target = event.target;
if (!isHTMLInputElement(target))
return;
info.current = {
value: target.value,
selectionStart: target.selectionStart,
selectionEnd: target.selectionEnd
};
});
return useEvent(() => {
if (isActiveElement(input))
return;
if (!isHTMLInputElement(input))
return;
if (!input.isConnected)
return;
input.focus({ preventScroll: true });
if (input.value !== info.current.value) {
input.setSelectionRange(input.value.length, input.value.length);
} else {
let { selectionStart, selectionEnd } = info.current;
if (selectionStart !== null && selectionEnd !== null) {
input.setSelectionRange(selectionStart, selectionEnd);
}
}
info.current = { value: "", selectionStart: null, selectionEnd: null };
});
}
// src/hooks/use-resolve-button-type.ts
var import_react42 = require("react");
function useResolveButtonType(props, element) {
return (0, import_react42.useMemo)(() => {
var _a3;
if (props.type)
return props.type;
let tag = (_a3 = props.as) != null ? _a3 : "button";
if (typeof tag === "string" && tag.toLowerCase() === "button")
return "button";
if ((element == null ? void 0 : element.tagName) === "BUTTON" && !element.hasAttribute("type"))
return "button";
return void 0;
}, [props.type, props.as, element]);
}
// src/hooks/use-store.ts
var import_react43 = require("react");
function useStore(store) {
return (0, import_react43.useSyncExternalStore)(store.subscribe, store.getSnapshot, store.getSnapshot);
}
// src/utils/store.ts
function createStore(initial, actions) {
let state = initial();
let listeners = /* @__PURE__ */ new Set();
return {
getSnapshot() {
return state;
},
subscribe(onChange) {
listeners.add(onChange);
return () => listeners.delete(onChange);
},
dispatch(key, ...args) {
let newState = actions[key].call(state, ...args);
if (newState) {
state = newState;
listeners.forEach((listener) => listener());
}
}
};
}
// src/hooks/document-overflow/adjust-scrollbar-padding.ts
function adjustScrollbarPadding() {
let scrollbarWidthBefore;
return {
before({ doc }) {
var _a3;
let documentElement = doc.documentElement;
let ownerWindow = (_a3 = doc.defaultView) != null ? _a3 : window;
scrollbarWidthBefore = Math.max(0, ownerWindow.innerWidth - documentElement.clientWidth);
},
after({ doc, d }) {
let documentElement = doc.documentElement;
let scrollbarWidthAfter = Math.max(
0,
documentElement.clientWidth - documentElement.offsetWidth
);
let scrollbarWidth = Math.max(0, scrollbarWidthBefore - scrollbarWidthAfter);
d.style(documentElement, "paddingRight", `${scrollbarWidth}px`);
}
};
}
// src/hooks/document-overflow/handle-ios-locking.ts
function handleIOSLocking() {
if (!isIOS()) {
return {};
}
return {
before({ doc, d, meta }) {
function inAllowedContainer(el) {
for (let resolve of meta().containers) {
for (let element of resolve()) {
if (element.contains(el)) {
return true;
}
}
}
return false;
}
d.microTask(() => {
var _a3;
if (window.getComputedStyle(doc.documentElement).scrollBehavior !== "auto") {
let _d = disposables();
_d.style(doc.documentElement, "scrollBehavior", "auto");
d.add(() => d.microTask(() => _d.dispose()));
}
let scrollPosition = (_a3 = window.scrollY) != null ? _a3 : window.pageYOffset;
let scrollToElement = null;
d.addEventListener(
doc,
"click",
(e) => {
if (!isHTMLorSVGElement(e.target)) {
return;
}
try {
let anchor = e.target.closest("a");
if (!anchor)
return;
let { hash } = new URL(anchor.href);
let el = doc.querySelector(hash);
if (isHTMLorSVGElement(el) && !inAllowedContainer(el)) {
scrollToElement = el;
}
} catch (err) {
}
},
true
);
d.group((_d) => {
d.addEventListener(doc, "touchstart", (e) => {
_d.dispose();
if (isHTMLorSVGElement(e.target) && hasInlineStyle(e.target)) {
if (inAllowedContainer(e.target)) {
let rootContainer = e.target;
while (rootContainer.parentElement && inAllowedContainer(rootContainer.parentElement)) {
rootContainer = rootContainer.parentElement;
}
_d.style(rootContainer, "overscrollBehavior", "contain");
} else {
_d.style(e.target, "touchAction", "none");
}
}
});
});
d.addEventListener(
doc,
"touchmove",
(e) => {
if (isHTMLorSVGElement(e.target)) {
if (isHTMLInputElement(e.target)) {
return;
}
if (inAllowedContainer(e.target)) {
let scrollableParent = e.target;
while (scrollableParent.parentElement && // Assumption: We are always used in a Headless UI Portal. Once we reach the
// portal itself, we can stop crawling up the tree.
scrollableParent.dataset.headlessuiPortal !== "") {
if (scrollableParent.scrollHeight > scrollableParent.clientHeight || scrollableParent.scrollWidth > scrollableParent.clientWidth) {
break;
}
scrollableParent = scrollableParent.parentElement;
}
if (scrollableParent.dataset.headlessuiPortal === "") {
e.preventDefault();
}
} else {
e.preventDefault();
}
}
},
{ passive: false }
);
d.add(() => {
var _a4;
let newScrollPosition = (_a4 = window.scrollY) != null ? _a4 : window.pageYOffset;
if (scrollPosition !== newScrollPosition) {
window.scrollTo(0, scrollPosition);
}
if (scrollToElement && scrollToElement.isConnected) {
scrollToElement.scrollIntoView({ block: "nearest" });
scrollToElement = null;
}
});
});
}
};
}
// src/hooks/document-overflow/prevent-scroll.ts
function preventScroll() {
return {
before({ doc, d }) {
d.style(doc.documentElement, "overflow", "hidden");
}
};
}
// src/hooks/document-overflow/overflow-store.ts
function buildMeta(fns) {
let tmp = {};
for (let fn of fns) {
Object.assign(tmp, fn(tmp));
}
return tmp;
}
var overflows = createStore(() => /* @__PURE__ */ new Map(), {
PUSH(doc, meta) {
var _a3;
let entry = (_a3 = this.get(doc)) != null ? _a3 : {
doc,
count: 0,
d: disposables(),
meta: /* @__PURE__ */ new Set(),
computedMeta: {}
};
entry.count++;
entry.meta.add(meta);
entry.computedMeta = buildMeta(entry.meta);
this.set(doc, entry);
return this;
},
POP(doc, meta) {
let entry = this.get(doc);
if (entry) {
entry.count--;
entry.meta.delete(meta);
entry.computedMeta = buildMeta(entry.meta);
}
return this;
},
SCROLL_PREVENT(entry) {
let ctx = {
doc: entry.doc,
d: entry.d,
// The moment we `PUSH`, we also `SCROLL_PREVENT`. But a later `PUSH` will
// not re-trigger a `SCROLL_PREVENT` because we are already in a locked
// state.
//
// This `meta()` function is called lazily such that a `PUSH` or `POP`
// that happens later can update the meta information. Otherwise we would
// use stale meta information.
meta() {
return entry.computedMeta;
}
};
let steps = [
handleIOSLocking(),
adjustScrollbarPadding(),
preventScroll()
];
steps.forEach(({ before }) => before == null ? void 0 : before(ctx));
steps.forEach(({ after }) => after == null ? void 0 : after(ctx));
},
SCROLL_ALLOW({ d }) {
d.dispose();
},
TEARDOWN({ doc }) {
this.delete(doc);
}
});
overflows.subscribe(() => {
let docs = overflows.getSnapshot();
let styles = /* @__PURE__ */ new Map();
for (let [doc] of docs) {
styles.set(doc, doc.documentElement.style.overflow);
}
for (let entry of docs.values()) {
let isHidden = styles.get(entry.doc) === "hidden";
let isLocked = entry.count !== 0;
let willChange = isLocked && !isHidden || !isLocked && isHidden;
if (willChange) {
overflows.dispatch(entry.count > 0 ? "SCROLL_PREVENT" : "SCROLL_ALLOW", entry);
}
if (entry.count === 0) {
overflows.dispatch("TEARDOWN", entry);
}
}
});
// src/hooks/document-overflow/use-document-overflow.ts
function useDocumentOverflowLockedEffect(shouldBeLocked, doc, meta = () => ({ containers: [] })) {
let store = useStore(overflows);
let entry = doc ? store.get(doc) : void 0;
let locked = entry ? entry.count > 0 : false;
useIsoMorphicEffect(() => {
if (!doc || !shouldBeLocked) {
return;
}
overflows.dispatch("PUSH", doc, meta);
return () => overflows.dispatch("POP", doc, meta);
}, [shouldBeLocked, doc]);
return locked;
}
// src/hooks/use-scroll-lock.ts
function useScrollLock(enabled, ownerDocument, resolveAllowedContainers = () => [document.body]) {
let isTopLayer = useIsTopLayer(enabled, "scroll-lock");
useDocumentOverflowLockedEffect(isTopLayer, ownerDocument, (meta) => {
var _a3;
return {
containers: [...(_a3 = meta.containers) != null ? _a3 : [], resolveAllowedContainers]
};
});
}
// src/hooks/use-tracked-pointer.ts
var import_react44 = require("react");
function eventToPosition(evt) {
return [evt.screenX, evt.screenY];
}
function useTrackedPointer() {
let lastPos = (0, import_react44.useRef)([-1, -1]);
return {
wasMoved(evt) {
if (false) {
return true;
}
let newPos = eventToPosition(evt);
if (lastPos.current[0] === newPos[0] && lastPos.current[1] === newPos[1]) {
return false;
}
lastPos.current = newPos;
return true;
},
update(evt) {
lastPos.current = eventToPosition(evt);
}
};
}
// src/hooks/use-transition.ts
var import_react46 = require("react");
// src/hooks/use-flags.ts
var import_react45 = require("react");
function useFlags(initialFlags = 0) {
let [flags, setFlags] = (0, import_react45.useState)(initialFlags);
let setFlag = (0, import_react45.useCallback)((flag) => setFlags(flag), []);
let addFlag = (0, import_react45.useCallback)((flag) => setFlags((flags2) => flags2 | flag), []);
let hasFlag = (0, import_react45.useCallback)((flag) => (flags & flag) === flag, [flags]);
let removeFlag = (0, import_react45.useCallback)((flag) => setFlags((flags2) => flags2 & ~flag), []);
let toggleFlag = (0, import_react45.useCallback)((flag) => setFlags((flags2) => flags2 ^ flag), []);
return { flags, setFlag, addFlag, hasFlag, removeFlag, toggleFlag };
}
// src/hooks/use-transition.ts
var _a, _b;
if (typeof process !== "undefined" && typeof globalThis !== "undefined" && typeof Element !== "undefined" && // Strange string concatenation is on purpose to prevent `esbuild` from
// replacing `process.env.NODE_ENV` with `production` in the build output,
// eliminating this whole branch.
((_a = process == null ? void 0 : process.env) == null ? void 0 : _a["NODE_ENV"]) === "test") {
if (typeof ((_b = Element == null ? void 0 : Element.prototype) == null ? void 0 : _b.getAnimations) === "undefined") {
Element.prototype.getAnimations = function getAnimationsPolyfill() {
console.warn(
[
"Headless UI has polyfilled `Element.prototype.getAnimations` for your tests.",
"Please install a proper polyfill e.g. `jsdom-testing-mocks`, to silence these warnings.",
"",
"Example usage:",
"```js",
"import { mockAnimationsApi } from 'jsdom-testing-mocks'",
"mockAnimationsApi()",
"```"
].join("\n")
);
return [];
};
}
}
function transitionDataAttributes(data) {
let attributes = {};
for (let key in data) {
if (data[key] === true) {
attributes[`data-${key}`] = "";
}
}
return attributes;
}
function useTransition(enabled, element, show, events) {
let [visible, setVisible] = (0, import_react46.useState)(show);
let { hasFlag, addFlag, removeFlag } = useFlags(
enabled && visible ? 2 /* Enter */ | 1 /* Closed */ : 0 /* None */
);
let inFlight = (0, import_react46.useRef)(false);
let cancelledRef = (0, import_react46.useRef)(false);
let d = useDisposables();
useIsoMorphicEffect(() => {
var _a3;
if (!enabled)
return;
if (show) {
setVisible(true);
}
if (!element) {
if (show) {
addFlag(2 /* Enter */ | 1 /* Closed */);
}
return;
}
(_a3 = events == null ? void 0 : events.start) == null ? void 0 : _a3.call(events, show);
return transition(element, {
inFlight,
prepare() {
if (cancelledRef.current) {
cancelledRef.current = false;
} else {
cancelledRef.current = inFlight.current;
}
inFlight.current = true;
if (cancelledRef.current)
return;
if (show) {
addFlag(2 /* Enter */ | 1 /* Closed */);
removeFlag(4 /* Leave */);
} else {
addFlag(4 /* Leave */);
removeFlag(2 /* Enter */);
}
},
run() {
if (cancelledRef.current) {
if (show) {
removeFlag(2 /* Enter */ | 1 /* Closed */);
addFlag(4 /* Leave */);
} else {
removeFlag(4 /* Leave */);
addFlag(2 /* Enter */ | 1 /* Closed */);
}
} else {
if (show) {
removeFlag(1 /* Closed */);
} else {
addFlag(1 /* Closed */);
}
}
},
done() {
var _a4;
if (cancelledRef.current) {
if (hasPendingTransitions(element)) {
return;
}
}
inFlight.current = false;
removeFlag(2 /* Enter */ | 4 /* Leave */ | 1 /* Closed */);
if (!show) {
setVisible(false);
}
(_a4 = events == null ? void 0 : events.end) == null ? void 0 : _a4.call(events, show);
}
});
}, [enabled, show, element, d]);
if (!enabled) {
return [
show,
{
closed: void 0,
enter: void 0,
leave: void 0,
transition: void 0
}
];
}
return [
visible,
{
closed: hasFlag(1 /* Closed */),
enter: hasFlag(2 /* Enter */),
leave: hasFlag(4 /* Leave */),
transition: hasFlag(2 /* Enter */) || hasFlag(4 /* Leave */)
}
];
}
function transition(node, {
prepare,
run,
done,
inFlight
}) {
let d = disposables();
prepareTransition(node, {
prepare,
inFlight
});
d.nextFrame(() => {
run();
d.requestAnimationFrame(() => {
d.add(waitForTransition(node, done));
});
});
return d.dispose;
}
function waitForTransition(node, done) {
var _a3, _b2;
let d = disposables();
if (!node)
return d.dispose;
let cancelled = false;
d.add(() => {
cancelled = true;
});
let transitions = (_b2 = (_a3 = node.getAnimations) == null ? void 0 : _a3.call(node).filter((animation) => animation instanceof CSSTransition)) != null ? _b2 : [];
if (transitions.length === 0) {
done();
return d.dispose;
}
Promise.allSettled(transitions.map((transition2) => transition2.finished)).then(() => {
if (!cancelled) {
done();
}
});
return d.dispose;
}
function prepareTransition(node, { inFlight, prepare }) {
if (inFlight == null ? void 0 : inFlight.current) {
prepare();
return;
}
let previous = node.style.transition;
node.style.transition = "none";
prepare();
node.offsetHeight;
node.style.transition = previous;
}
function hasPendingTransitions(node) {
var _a3, _b2;
let animations = (_b2 = (_a3 = node.getAnimations) == null ? void 0 : _a3.call(node)) != null ? _b2 : [];
return animations.some((animation) => {
return animation instanceof CSSTransition && animation.playState !== "finished";
});
}
// src/hooks/use-tree-walker.ts
var import_react47 = require("react");
function useTreeWalker(enabled, {
container,
accept,
walk
}) {
let acceptRef = (0, import_react47.useRef)(accept);
let walkRef = (0, import_react47.useRef)(walk);
(0, import_react47.useEffect)(() => {
acceptRef.current = accept;
walkRef.current = walk;
}, [accept, walk]);
useIsoMorphicEffect(() => {
if (!container)
return;
if (!enabled)
return;
let ownerDocument = getOwnerDocument(container);
if (!ownerDocument)
return;
let accept2 = acceptRef.current;
let walk2 = walkRef.current;
let acceptNode = Object.assign((node) => accept2(node), { acceptNode: accept2 });
let walker = ownerDocument.createTreeWalker(
container,
NodeFilter.SHOW_ELEMENT,
acceptNode,
// @ts-expect-error This `false` is a simple small fix for older browsers
false
);
while (walker.nextNode())
walk2(walker.currentNode);
}, [container, enabled, acceptRef, walkRef]);
}
// src/hooks/use-watch.ts
var import_react48 = require("react");
function useWatch(cb, dependencies) {
let track = (0, import_react48.useRef)([]);
let action = useEvent(cb);
(0, import_react48.useEffect)(() => {
let oldValues = [...track.current];
for (let [idx, value] of dependencies.entries()) {
if (track.current[idx] !== value) {
let returnValue = action(dependencies, oldValues);
track.current = dependencies;
return returnValue;
}
}
}, [action, ...dependencies]);
}
// node_modules/@floating-ui/react/dist/floating-ui.react.mjs
var React13 = __toESM(require("react"), 1);
var import_react50 = require("react");
// node_modules/@floating-ui/utils/dist/floating-ui.utils.dom.mjs
function getWindow(node) {
var _node$ownerDocument;
return (node == null || (_node$ownerDocument = node.ownerDocument) == null ? void 0 : _node$ownerDocument.defaultView) || window;
}
function isElement2(value) {
return value instanceof Element || value instanceof getWindow(value).Element;
}
// node_modules/@floating-ui/react/dist/floating-ui.react.utils.mjs
function getUserAgent() {
const uaData = navigator.userAgentData;
if (uaData && Array.isArray(uaData.brands)) {
return uaData.brands.map((_ref) => {
let {
brand,
version
} = _ref;
return brand + "/" + version;
}).join(" ");
}
return navigator.userAgent;
}
// ../../node_modules/@floating-ui/utils/dist/floating-ui.utils.mjs
var min = Math.min;
var max = Math.max;
var round = Math.round;
var floor = Math.floor;
var createCoords = (v) => ({
x: v,
y: v
});
var oppositeSideMap = {
left: "right",
right: "left",
bottom: "top",
top: "bottom"
};
var oppositeAlignmentMap = {
start: "end",
end: "start"
};
function clamp(start, value, end) {
return max(start, min(value, end));
}
function evaluate(value, param) {
return typeof value === "function" ? value(param) : value;
}
function getSide(placement) {
return placement.split("-")[0];
}
function getAlignment(placement) {
return placement.split("-")[1];
}
function getOppositeAxis(axis) {
return axis === "x" ? "y" : "x";
}
function getAxisLength(axis) {
return axis === "y" ? "height" : "width";
}
function getSideAxis(placement) {
return ["top", "bottom"].includes(getSide(placement)) ? "y" : "x";
}
function getAlignmentAxis(placement) {
return getOppositeAxis(getSideAxis(placement));
}
function getAlignmentSides(placement, rects, rtl) {
if (rtl === void 0) {
rtl = false;
}
const alignment = getAlignment(placement);
const alignmentAxis = getAlignmentAxis(placement);
const length = getAxisLength(alignmentAxis);
let mainAlignmentSide = alignmentAxis === "x" ? alignment === (rtl ? "end" : "start") ? "right" : "left" : alignment === "start" ? "bottom" : "top";
if (rects.reference[length] > rects.floating[length]) {
mainAlignmentSide = getOppositePlacement(mainAlignmentSide);
}
return [mainAlignmentSide, getOppositePlacement(mainAlignmentSide)];
}
function getExpandedPlacements(placement) {
const oppositePlacement = getOppositePlacement(placement);
return [getOppositeAlignmentPlacement(placement), oppositePlacement, getOppositeAlignmentPlacement(oppositePlacement)];
}
function getOppositeAlignmentPlacement(placement) {
return placement.replace(/start|end/g, (alignment) => oppositeAlignmentMap[alignment]);
}
function getSideList(side, isStart, rtl) {
const lr = ["left", "right"];
const rl = ["right", "left"];
const tb = ["top", "bottom"];
const bt = ["bottom", "top"];
switch (side) {
case "top":
case "bottom":
if (rtl)
return isStart ? rl : lr;
return isStart ? lr : rl;
case "left":
case "right":
return isStart ? tb : bt;
default:
return [];
}
}
function getOppositeAxisPlacements(placement, flipAlignment, direction, rtl) {
const alignment = getAlignment(placement);
let list = getSideList(getSide(placement), direction === "start", rtl);
if (alignment) {
list = list.map((side) => side + "-" + alignment);
if (flipAlignment) {
list = list.concat(list.map(getOppositeAlignmentPlacement));
}
}
return list;
}
function getOppositePlacement(placement) {
return placement.replace(/left|right|bottom|top/g, (side) => oppositeSideMap[side]);
}
function expandPaddingObject(padding) {
return {
top: 0,
right: 0,
bottom: 0,
left: 0,
...padding
};
}
function getPaddingObject(padding) {
return typeof padding !== "number" ? expandPaddingObject(padding) : {
top: padding,
right: padding,
bottom: padding,
left: padding
};
}
function rectToClientRect(rect) {
return {
...rect,
top: rect.y,
left: rect.x,
right: rect.x + rect.width,
bottom: rect.y + rect.height
};
}
// ../../node_modules/@floating-ui/core/dist/floating-ui.core.mjs
function computeCoordsFromPlacement(_ref, placement, rtl) {
let {
reference,
floating
} = _ref;
const sideAxis = getSideAxis(placement);
const alignmentAxis = getAlignmentAxis(placement);
const alignLength = getAxisLength(alignmentAxis);
const side = getSide(placement);
const isVertical = sideAxis === "y";
const commonX = reference.x + reference.width / 2 - floating.width / 2;
const commonY = reference.y + reference.height / 2 - floating.height / 2;
const commonAlign = reference[alignLength] / 2 - floating[alignLength] / 2;
let coords;
switch (side) {
case "top":
coords = {
x: commonX,
y: reference.y - floating.height
};
break;
case "bottom":
coords = {
x: commonX,
y: reference.y + reference.height
};
break;
case "right":
coords = {
x: reference.x + reference.width,
y: commonY
};
break;
case "left":
coords = {
x: reference.x - floating.width,
y: commonY
};
break;
default:
coords = {
x: reference.x,
y: reference.y
};
}
switch (getAlignment(placement)) {
case "start":
coords[alignmentAxis] -= commonAlign * (rtl && isVertical ? -1 : 1);
break;
case "end":
coords[alignmentAxis] += commonAlign * (rtl && isVertical ? -1 : 1);
break;
}
return coords;
}
var computePosition = async (reference, floating, config) => {
const {
placement = "bottom",
strategy = "absolute",
middleware = [],
platform: platform2
} = config;
const validMiddleware = middleware.filter(Boolean);
const rtl = await (platform2.isRTL == null ? void 0 : platform2.isRTL(floating));
let rects = await platform2.getElementRects({
reference,
floating,
strategy
});
let {
x,
y
} = computeCoordsFromPlacement(rects, placement, rtl);
let statefulPlacement = placement;
let middlewareData = {};
let resetCount = 0;
for (let i = 0; i < validMiddleware.length; i++) {
const {
name,
fn
} = validMiddleware[i];
const {
x: nextX,
y: nextY,
data,
reset
} = await fn({
x,
y,
initialPlacement: placement,
placement: statefulPlacement,
strategy,
middlewareData,
rects,
platform: platform2,
elements: {
reference,
floating
}
});
x = nextX != null ? nextX : x;
y = nextY != null ? nextY : y;
middlewareData = {
...middlewareData,
[name]: {
...middlewareData[name],
...data
}
};
if (reset && resetCount <= 50) {
resetCount++;
if (typeof reset === "object") {
if (reset.placement) {
statefulPlacement = reset.placement;
}
if (reset.rects) {
rects = reset.rects === true ? await platform2.getElementRects({
reference,
floating,
strategy
}) : reset.rects;
}
({
x,
y
} = computeCoordsFromPlacement(rects, statefulPlacement, rtl));
}
i = -1;
continue;
}
}
return {
x,
y,
placement: statefulPlacement,
strategy,
middlewareData
};
};
async function detectOverflow(state, options) {
var _await$platform$isEle;
if (options === void 0) {
options = {};
}
const {
x,
y,
platform: platform2,
rects,
elements,
strategy
} = state;
const {
boundary = "clippingAncestors",
rootBoundary = "viewport",
elementContext = "floating",
altBoundary = false,
padding = 0
} = evaluate(options, state);
const paddingObject = getPaddingObject(padding);
const altContext = elementContext === "floating" ? "reference" : "floating";
const element = elements[altBoundary ? altContext : elementContext];
const clippingClientRect = rectToClientRect(await platform2.getClippingRect({
element: ((_await$platform$isEle = await (platform2.isElement == null ? void 0 : platform2.isElement(element))) != null ? _await$platform$isEle : true) ? element : element.contextElement || await (platform2.getDocumentElement == null ? void 0 : platform2.getDocumentElement(elements.floating)),
boundary,
rootBoundary,
strategy
}));
const rect = elementContext === "floating" ? {
...rects.floating,
x,
y
} : rects.reference;
const offsetParent = await (platform2.getOffsetParent == null ? void 0 : platform2.getOffsetParent(elements.floating));
const offsetScale = await (platform2.isElement == null ? void 0 : platform2.isElement(offsetParent)) ? await (platform2.getScale == null ? void 0 : platform2.getScale(offsetParent)) || {
x: 1,
y: 1
} : {
x: 1,
y: 1
};
const elementClientRect = rectToClientRect(platform2.convertOffsetParentRelativeRectToViewportRelativeRect ? await platform2.convertOffsetParentRelativeRectToViewportRelativeRect({
rect,
offsetParent,
strategy
}) : rect);
return {
top: (clippingClientRect.top - elementClientRect.top + paddingObject.top) / offsetScale.y,
bottom: (elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom) / offsetScale.y,
left: (clippingClientRect.left - elementClientRect.left + paddingObject.left) / offsetScale.x,
right: (elementClientRect.right - clippingClientRect.right + paddingObject.right) / offsetScale.x
};
}
var flip = function(options) {
if (options === void 0) {
options = {};
}
return {
name: "flip",
options,
async fn(state) {
var _middlewareData$arrow, _middlewareData$flip;
const {
placement,
middlewareData,
rects,
initialPlacement,
platform: platform2,
elements
} = state;
const {
mainAxis: checkMainAxis = true,
crossAxis: checkCrossAxis = true,
fallbackPlacements: specifiedFallbackPlacements,
fallbackStrategy = "bestFit",
fallbackAxisSideDirection = "none",
flipAlignment = true,
...detectOverflowOptions
} = evaluate(options, state);
if ((_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) {
return {};
}
const side = getSide(placement);
const isBasePlacement = getSide(initialPlacement) === initialPlacement;
const rtl = await (platform2.isRTL == null ? void 0 : platform2.isRTL(elements.floating));
const fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipAlignment ? [getOppositePlacement(initialPlacement)] : getExpandedPlacements(initialPlacement));
if (!specifiedFallbackPlacements && fallbackAxisSideDirection !== "none") {
fallbackPlacements.push(...getOppositeAxisPlacements(initialPlacement, flipAlignment, fallbackAxisSideDirection, rtl));
}
const placements2 = [initialPlacement, ...fallbackPlacements];
const overflow = await detectOverflow(state, detectOverflowOptions);
const overflows2 = [];
let overflowsData = ((_middlewareData$flip = middlewareData.flip) == null ? void 0 : _middlewareData$flip.overflows) || [];
if (checkMainAxis) {
overflows2.push(overflow[side]);
}
if (checkCrossAxis) {
const sides2 = getAlignmentSides(placement, rects, rtl);
overflows2.push(overflow[sides2[0]], overflow[sides2[1]]);
}
overflowsData = [...overflowsData, {
placement,
overflows: overflows2
}];
if (!overflows2.every((side2) => side2 <= 0)) {
var _middlewareData$flip2, _overflowsData$filter;
const nextIndex = (((_middlewareData$flip2 = middlewareData.flip) == null ? void 0 : _middlewareData$flip2.index) || 0) + 1;
const nextPlacement = placements2[nextIndex];
if (nextPlacement) {
return {
data: {
index: nextIndex,
overflows: overflowsData
},
reset: {
placement: nextPlacement
}
};
}
let resetPlacement = (_overflowsData$filter = overflowsData.filter((d) => d.overflows[0] <= 0).sort((a, b) => a.overflows[1] - b.overflows[1])[0]) == null ? void 0 : _overflowsData$filter.placement;
if (!resetPlacement) {
switch (fallbackStrategy) {
case "bestFit": {
var _overflowsData$map$so;
const placement2 = (_overflowsData$map$so = overflowsData.map((d) => [d.placement, d.overflows.filter((overflow2) => overflow2 > 0).reduce((acc, overflow2) => acc + overflow2, 0)]).sort((a, b) => a[1] - b[1])[0]) == null ? void 0 : _overflowsData$map$so[0];
if (placement2) {
resetPlacement = placement2;
}
break;
}
case "initialPlacement":
resetPlacement = initialPlacement;
break;
}
}
if (placement !== resetPlacement) {
return {
reset: {
placement: resetPlacement
}
};
}
}
return {};
}
};
};
async function convertValueToCoords(state, options) {
const {
placement,
platform: platform2,
elements
} = state;
const rtl = await (platform2.isRTL == null ? void 0 : platform2.isRTL(elements.floating));
const side = getSide(placement);
const alignment = getAlignment(placement);
const isVertical = getSideAxis(placement) === "y";
const mainAxisMulti = ["left", "top"].includes(side) ? -1 : 1;
const crossAxisMulti = rtl && isVertical ? -1 : 1;
const rawValue = evaluate(options, state);
let {
mainAxis,
crossAxis,
alignmentAxis
} = typeof rawValue === "number" ? {
mainAxis: rawValue,
crossAxis: 0,
alignmentAxis: null
} : {
mainAxis: 0,
crossAxis: 0,
alignmentAxis: null,
...rawValue
};
if (alignment && typeof alignmentAxis === "number") {
crossAxis = alignment === "end" ? alignmentAxis * -1 : alignmentAxis;
}
return isVertical ? {
x: crossAxis * crossAxisMulti,
y: mainAxis * mainAxisMulti
} : {
x: mainAxis * mainAxisMulti,
y: crossAxis * crossAxisMulti
};
}
var offset = function(options) {
if (options === void 0) {
options = 0;
}
return {
name: "offset",
options,
async fn(state) {
var _middlewareData$offse, _middlewareData$arrow;
const {
x,
y,
placement,
middlewareData
} = state;
const diffCoords = await convertValueToCoords(state, options);
if (placement === ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse.placement) && (_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) {
return {};
}
return {
x: x + diffCoords.x,
y: y + diffCoords.y,
data: {
...diffCoords,
placement
}
};
}
};
};
var shift = function(options) {
if (options === void 0) {
options = {};
}
return {
name: "shift",
options,
async fn(state) {
const {
x,
y,
placement
} = state;
const {
mainAxis: checkMainAxis = true,
crossAxis: checkCrossAxis = false,
limiter = {
fn: (_ref) => {
let {
x: x2,
y: y2
} = _ref;
return {
x: x2,
y: y2
};
}
},
...detectOverflowOptions
} = evaluate(options, state);
const coords = {
x,
y
};
const overflow = await detectOverflow(state, detectOverflowOptions);
const crossAxis = getSideAxis(getSide(placement));
const mainAxis = getOppositeAxis(crossAxis);
let mainAxisCoord = coords[mainAxis];
let crossAxisCoord = coords[crossAxis];
if (checkMainAxis) {
const minSide = mainAxis === "y" ? "top" : "left";
const maxSide = mainAxis === "y" ? "bottom" : "right";
const min2 = mainAxisCoord + overflow[minSide];
const max2 = mainAxisCoord - overflow[maxSide];
mainAxisCoord = clamp(min2, mainAxisCoord, max2);
}
if (checkCrossAxis) {
const minSide = crossAxis === "y" ? "top" : "left";
const maxSide = crossAxis === "y" ? "bottom" : "right";
const min2 = crossAxisCoord + overflow[minSide];
const max2 = crossAxisCoord - overflow[maxSide];
crossAxisCoord = clamp(min2, crossAxisCoord, max2);
}
const limitedCoords = limiter.fn({
...state,
[mainAxis]: mainAxisCoord,
[crossAxis]: crossAxisCoord
});
return {
...limitedCoords,
data: {
x: limitedCoords.x - x,
y: limitedCoords.y - y
}
};
}
};
};
var size = function(options) {
if (options === void 0) {
options = {};
}
return {
name: "size",
options,
async fn(state) {
const {
placement,
rects,
platform: platform2,
elements
} = state;
const {
apply = () => {
},
...detectOverflowOptions
} = evaluate(options, state);
const overflow = await detectOverflow(state, detectOverflowOptions);
const side = getSide(placement);
const alignment = getAlignment(placement);
const isYAxis = getSideAxis(placement) === "y";
const {
width,
height
} = rects.floating;
let heightSide;
let widthSide;
if (side === "top" || side === "bottom") {
heightSide = side;
widthSide = alignment === (await (platform2.isRTL == null ? void 0 : platform2.isRTL(elements.floating)) ? "start" : "end") ? "left" : "right";
} else {
widthSide = side;
heightSide = alignment === "end" ? "top" : "bottom";
}
const overflowAvailableHeight = height - overflow[heightSide];
const overflowAvailableWidth = width - overflow[widthSide];
const noShift = !state.middlewareData.shift;
let availableHeight = overflowAvailableHeight;
let availableWidth = overflowAvailableWidth;
if (isYAxis) {
const maximumClippingWidth = width - overflow.left - overflow.right;
availableWidth = alignment || noShift ? min(overflowAvailableWidth, maximumClippingWidth) : maximumClippingWidth;
} else {
const maximumClippingHeight = height - overflow.top - overflow.bottom;
availableHeight = alignment || noShift ? min(overflowAvailableHeight, maximumClippingHeight) : maximumClippingHeight;
}
if (noShift && !alignment) {
const xMin = max(overflow.left, 0);
const xMax = max(overflow.right, 0);
const yMin = max(overflow.top, 0);
const yMax = max(overflow.bottom, 0);
if (isYAxis) {
availableWidth = width - 2 * (xMin !== 0 || xMax !== 0 ? xMin + xMax : max(overflow.left, overflow.right));
} else {
availableHeight = height - 2 * (yMin !== 0 || yMax !== 0 ? yMin + yMax : max(overflow.top, overflow.bottom));
}
}
await apply({
...state,
availableWidth,
availableHeight
});
const nextDimensions = await platform2.getDimensions(elements.floating);
if (width !== nextDimensions.width || height !== nextDimensions.height) {
return {
reset: {
rects: true
}
};
}
return {};
}
};
};
// ../../node_modules/@floating-ui/utils/dom/dist/floating-ui.utils.dom.mjs
function getNodeName(node) {
if (isNode2(node)) {
return (node.nodeName || "").toLowerCase();
}
return "#document";
}
function getWindow2(node) {
var _node$ownerDocument;
return (node == null ? void 0 : (_node$ownerDocument = node.ownerDocument) == null ? void 0 : _node$ownerDocument.defaultView) || window;
}
function getDocumentElement(node) {
var _ref;
return (_ref = (isNode2(node) ? node.ownerDocument : node.document) || window.document) == null ? void 0 : _ref.documentElement;
}
function isNode2(value) {
return value instanceof Node || value instanceof getWindow2(value).Node;
}
function isElement3(value) {
return value instanceof Element || value instanceof getWindow2(value).Element;
}
function isHTMLElement2(value) {
return value instanceof HTMLElement || value instanceof getWindow2(value).HTMLElement;
}
function isShadowRoot(value) {
if (typeof ShadowRoot === "undefined") {
return false;
}
return value instanceof ShadowRoot || value instanceof getWindow2(value).ShadowRoot;
}
function isOverflowElement(element) {
const {
overflow,
overflowX,
overflowY,
display
} = getComputedStyle2(element);
return /auto|scroll|overlay|hidden|clip/.test(overflow + overflowY + overflowX) && !["inline", "contents"].includes(display);
}
function isTableElement(element) {
return ["table", "td", "th"].includes(getNodeName(element));
}
function isContainingBlock(element) {
const webkit = isWebKit();
const css = getComputedStyle2(element);
return css.transform !== "none" || css.perspective !== "none" || (css.containerType ? css.containerType !== "normal" : false) || !webkit && (css.backdropFilter ? css.backdropFilter !== "none" : false) || !webkit && (css.filter ? css.filter !== "none" : false) || ["transform", "perspective", "filter"].some((value) => (css.willChange || "").includes(value)) || ["paint", "layout", "strict", "content"].some((value) => (css.contain || "").includes(value));
}
function getContainingBlock(element) {
let currentNode = getParentNode(element);
while (isHTMLElement2(currentNode) && !isLastTraversableNode(currentNode)) {
if (isContainingBlock(currentNode)) {
return currentNode;
} else {
currentNode = getParentNode(currentNode);
}
}
return null;
}
function isWebKit() {
if (typeof CSS === "undefined" || !CSS.supports)
return false;
return CSS.supports("-webkit-backdrop-filter", "none");
}
function isLastTraversableNode(node) {
return ["html", "body", "#document"].includes(getNodeName(node));
}
function getComputedStyle2(element) {
return getWindow2(element).getComputedStyle(element);
}
function getNodeScroll(element) {
if (isElement3(element)) {
return {
scrollLeft: element.scrollLeft,
scrollTop: element.scrollTop
};
}
return {
scrollLeft: element.pageXOffset,
scrollTop: element.pageYOffset
};
}
function getParentNode(node) {
if (getNodeName(node) === "html") {
return node;
}
const result = (
// Step into the shadow DOM of the parent of a slotted node.
node.assignedSlot || // DOM Element detected.
node.parentNode || // ShadowRoot detected.
isShadowRoot(node) && node.host || // Fallback.
getDocumentElement(node)
);
return isShadowRoot(result) ? result.host : result;
}
function getNearestOverflowAncestor(node) {
const parentNode = getParentNode(node);
if (isLastTraversableNode(parentNode)) {
return node.ownerDocument ? node.ownerDocument.body : node.body;
}
if (isHTMLElement2(parentNode) && isOverflowElement(parentNode)) {
return parentNode;
}
return getNearestOverflowAncestor(parentNode);
}
function getOverflowAncestors(node, list, traverseIframes) {
var _node$ownerDocument2;
if (list === void 0) {
list = [];
}
if (traverseIframes === void 0) {
traverseIframes = true;
}
const scrollableAncestor = getNearestOverflowAncestor(node);
const isBody = scrollableAncestor === ((_node$ownerDocument2 = node.ownerDocument) == null ? void 0 : _node$ownerDocument2.body);
const win = getWindow2(scrollableAncestor);
if (isBody) {
return list.concat(win, win.visualViewport || [], isOverflowElement(scrollableAncestor) ? scrollableAncestor : [], win.frameElement && traverseIframes ? getOverflowAncestors(win.frameElement) : []);
}
return list.concat(scrollableAncestor, getOverflowAncestors(scrollableAncestor, [], traverseIframes));
}
// ../../node_modules/@floating-ui/dom/dist/floating-ui.dom.mjs
function getCssDimensions(element) {
const css = getComputedStyle2(element);
let width = parseFloat(css.width) || 0;
let height = parseFloat(css.height) || 0;
const hasOffset = isHTMLElement2(element);
const offsetWidth = hasOffset ? element.offsetWidth : width;
const offsetHeight = hasOffset ? element.offsetHeight : height;
const shouldFallback = round(width) !== offsetWidth || round(height) !== offsetHeight;
if (shouldFallback) {
width = offsetWidth;
height = offsetHeight;
}
return {
width,
height,
$: shouldFallback
};
}
function unwrapElement(element) {
return !isElement3(element) ? element.contextElement : element;
}
function getScale(element) {
const domElement = unwrapElement(element);
if (!isHTMLElement2(domElement)) {
return createCoords(1);
}
const rect = domElement.getBoundingClientRect();
const {
width,
height,
$
} = getCssDimensions(domElement);
let x = ($ ? round(rect.width) : rect.width) / width;
let y = ($ ? round(rect.height) : rect.height) / height;
if (!x || !Number.isFinite(x)) {
x = 1;
}
if (!y || !Number.isFinite(y)) {
y = 1;
}
return {
x,
y
};
}
var noOffsets = /* @__PURE__ */ createCoords(0);
function getVisualOffsets(element) {
const win = getWindow2(element);
if (!isWebKit() || !win.visualViewport) {
return noOffsets;
}
return {
x: win.visualViewport.offsetLeft,
y: win.visualViewport.offsetTop
};
}
function shouldAddVisualOffsets(element, isFixed, floatingOffsetParent) {
if (isFixed === void 0) {
isFixed = false;
}
if (!floatingOffsetParent || isFixed && floatingOffsetParent !== getWindow2(element)) {
return false;
}
return isFixed;
}
function getBoundingClientRect(element, includeScale, isFixedStrategy, offsetParent) {
if (includeScale === void 0) {
includeScale = false;
}
if (isFixedStrategy === void 0) {
isFixedStrategy = false;
}
const clientRect = element.getBoundingClientRect();
const domElement = unwrapElement(element);
let scale = createCoords(1);
if (includeScale) {
if (offsetParent) {
if (isElement3(offsetParent)) {
scale = getScale(offsetParent);
}
} else {
scale = getScale(element);
}
}
const visualOffsets = shouldAddVisualOffsets(domElement, isFixedStrategy, offsetParent) ? getVisualOffsets(domElement) : createCoords(0);
let x = (clientRect.left + visualOffsets.x) / scale.x;
let y = (clientRect.top + visualOffsets.y) / scale.y;
let width = clientRect.width / scale.x;
let height = clientRect.height / scale.y;
if (domElement) {
const win = getWindow2(domElement);
const offsetWin = offsetParent && isElement3(offsetParent) ? getWindow2(offsetParent) : offsetParent;
let currentIFrame = win.frameElement;
while (currentIFrame && offsetParent && offsetWin !== win) {
const iframeScale = getScale(currentIFrame);
const iframeRect = currentIFrame.getBoundingClientRect();
const css = getComputedStyle2(currentIFrame);
const left = iframeRect.left + (currentIFrame.clientLeft + parseFloat(css.paddingLeft)) * iframeScale.x;
const top = iframeRect.top + (currentIFrame.clientTop + parseFloat(css.paddingTop)) * iframeScale.y;
x *= iframeScale.x;
y *= iframeScale.y;
width *= iframeScale.x;
height *= iframeScale.y;
x += left;
y += top;
currentIFrame = getWindow2(currentIFrame).frameElement;
}
}
return rectToClientRect({
width,
height,
x,
y
});
}
function convertOffsetParentRelativeRectToViewportRelativeRect(_ref) {
let {
rect,
offsetParent,
strategy
} = _ref;
const isOffsetParentAnElement = isHTMLElement2(offsetParent);
const documentElement = getDocumentElement(offsetParent);
if (offsetParent === documentElement) {
return rect;
}
let scroll = {
scrollLeft: 0,
scrollTop: 0
};
let scale = createCoords(1);
const offsets = createCoords(0);
if (isOffsetParentAnElement || !isOffsetParentAnElement && strategy !== "fixed") {
if (getNodeName(offsetParent) !== "body" || isOverflowElement(documentElement)) {
scroll = getNodeScroll(offsetParent);
}
if (isHTMLElement2(offsetParent)) {
const offsetRect = getBoundingClientRect(offsetParent);
scale = getScale(offsetParent);
offsets.x = offsetRect.x + offsetParent.clientLeft;
offsets.y = offsetRect.y + offsetParent.clientTop;
}
}
return {
width: rect.width * scale.x,
height: rect.height * scale.y,
x: rect.x * scale.x - scroll.scrollLeft * scale.x + offsets.x,
y: rect.y * scale.y - scroll.scrollTop * scale.y + offsets.y
};
}
function getClientRects(element) {
return Array.from(element.getClientRects());
}
function getWindowScrollBarX(element) {
return getBoundingClientRect(getDocumentElement(element)).left + getNodeScroll(element).scrollLeft;
}
function getDocumentRect(element) {
const html = getDocumentElement(element);
const scroll = getNodeScroll(element);
const body = element.ownerDocument.body;
const width = max(html.scrollWidth, html.clientWidth, body.scrollWidth, body.clientWidth);
const height = max(html.scrollHeight, html.clientHeight, body.scrollHeight, body.clientHeight);
let x = -scroll.scrollLeft + getWindowScrollBarX(element);
const y = -scroll.scrollTop;
if (getComputedStyle2(body).direction === "rtl") {
x += max(html.clientWidth, body.clientWidth) - width;
}
return {
width,
height,
x,
y
};
}
function getViewportRect(element, strategy) {
const win = getWindow2(element);
const html = getDocumentElement(element);
const visualViewport = win.visualViewport;
let width = html.clientWidth;
let height = html.clientHeight;
let x = 0;
let y = 0;
if (visualViewport) {
width = visualViewport.width;
height = visualViewport.height;
const visualViewportBased = isWebKit();
if (!visualViewportBased || visualViewportBased && strategy === "fixed") {
x = visualViewport.offsetLeft;
y = visualViewport.offsetTop;
}
}
return {
width,
height,
x,
y
};
}
function getInnerBoundingClientRect(element, strategy) {
const clientRect = getBoundingClientRect(element, true, strategy === "fixed");
const top = clientRect.top + element.clientTop;
const left = clientRect.left + element.clientLeft;
const scale = isHTMLElement2(element) ? getScale(element) : createCoords(1);
const width = element.clientWidth * scale.x;
const height = element.clientHeight * scale.y;
const x = left * scale.x;
const y = top * scale.y;
return {
width,
height,
x,
y
};
}
function getClientRectFromClippingAncestor(element, clippingAncestor, strategy) {
let rect;
if (clippingAncestor === "viewport") {
rect = getViewportRect(element, strategy);
} else if (clippingAncestor === "document") {
rect = getDocumentRect(getDocumentElement(element));
} else if (isElement3(clippingAncestor)) {
rect = getInnerBoundingClientRect(clippingAncestor, strategy);
} else {
const visualOffsets = getVisualOffsets(element);
rect = {
...clippingAncestor,
x: clippingAncestor.x - visualOffsets.x,
y: clippingAncestor.y - visualOffsets.y
};
}
return rectToClientRect(rect);
}
function hasFixedPositionAncestor(element, stopNode) {
const parentNode = getParentNode(element);
if (parentNode === stopNode || !isElement3(parentNode) || isLastTraversableNode(parentNode)) {
return false;
}
return getComputedStyle2(parentNode).position === "fixed" || hasFixedPositionAncestor(parentNode, stopNode);
}
function getClippingElementAncestors(element, cache) {
const cachedResult = cache.get(element);
if (cachedResult) {
return cachedResult;
}
let result = getOverflowAncestors(element, [], false).filter((el) => isElement3(el) && getNodeName(el) !== "body");
let currentContainingBlockComputedStyle = null;
const elementIsFixed = getComputedStyle2(element).position === "fixed";
let currentNode = elementIsFixed ? getParentNode(element) : element;
while (isElement3(currentNode) && !isLastTraversableNode(currentNode)) {
const computedStyle = getComputedStyle2(currentNode);
const currentNodeIsContaining = isContainingBlock(currentNode);
if (!currentNodeIsContaining && computedStyle.position === "fixed") {
currentContainingBlockComputedStyle = null;
}
const shouldDropCurrentNode = elementIsFixed ? !currentNodeIsContaining && !currentContainingBlockComputedStyle : !currentNodeIsContaining && computedStyle.position === "static" && !!currentContainingBlockComputedStyle && ["absolute", "fixed"].includes(currentContainingBlockComputedStyle.position) || isOverflowElement(currentNode) && !currentNodeIsContaining && hasFixedPositionAncestor(element, currentNode);
if (shouldDropCurrentNode) {
result = result.filter((ancestor) => ancestor !== currentNode);
} else {
currentContainingBlockComputedStyle = computedStyle;
}
currentNode = getParentNode(currentNode);
}
cache.set(element, result);
return result;
}
function getClippingRect(_ref) {
let {
element,
boundary,
rootBoundary,
strategy
} = _ref;
const elementClippingAncestors = boundary === "clippingAncestors" ? getClippingElementAncestors(element, this._c) : [].concat(boundary);
const clippingAncestors = [...elementClippingAncestors, rootBoundary];
const firstClippingAncestor = clippingAncestors[0];
const clippingRect = clippingAncestors.reduce((accRect, clippingAncestor) => {
const rect = getClientRectFromClippingAncestor(element, clippingAncestor, strategy);
accRect.top = max(rect.top, accRect.top);
accRect.right = min(rect.right, accRect.right);
accRect.bottom = min(rect.bottom, accRect.bottom);
accRect.left = max(rect.left, accRect.left);
return accRect;
}, getClientRectFromClippingAncestor(element, firstClippingAncestor, strategy));
return {
width: clippingRect.right - clippingRect.left,
height: clippingRect.bottom - clippingRect.top,
x: clippingRect.left,
y: clippingRect.top
};
}
function getDimensions(element) {
return getCssDimensions(element);
}
function getRectRelativeToOffsetParent(element, offsetParent, strategy) {
const isOffsetParentAnElement = isHTMLElement2(offsetParent);
const documentElement = getDocumentElement(offsetParent);
const isFixed = strategy === "fixed";
const rect = getBoundingClientRect(element, true, isFixed, offsetParent);
let scroll = {
scrollLeft: 0,
scrollTop: 0
};
const offsets = createCoords(0);
if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {
if (getNodeName(offsetParent) !== "body" || isOverflowElement(documentElement)) {
scroll = getNodeScroll(offsetParent);
}
if (isOffsetParentAnElement) {
const offsetRect = getBoundingClientRect(offsetParent, true, isFixed, offsetParent);
offsets.x = offsetRect.x + offsetParent.clientLeft;
offsets.y = offsetRect.y + offsetParent.clientTop;
} else if (documentElement) {
offsets.x = getWindowScrollBarX(documentElement);
}
}
return {
x: rect.left + scroll.scrollLeft - offsets.x,
y: rect.top + scroll.scrollTop - offsets.y,
width: rect.width,
height: rect.height
};
}
function getTrueOffsetParent(element, polyfill) {
if (!isHTMLElement2(element) || getComputedStyle2(element).position === "fixed") {
return null;
}
if (polyfill) {
return polyfill(element);
}
return element.offsetParent;
}
function getOffsetParent(element, polyfill) {
const window2 = getWindow2(element);
if (!isHTMLElement2(element)) {
return window2;
}
let offsetParent = getTrueOffsetParent(element, polyfill);
while (offsetParent && isTableElement(offsetParent) && getComputedStyle2(offsetParent).position === "static") {
offsetParent = getTrueOffsetParent(offsetParent, polyfill);
}
if (offsetParent && (getNodeName(offsetParent) === "html" || getNodeName(offsetParent) === "body" && getComputedStyle2(offsetParent).position === "static" && !isContainingBlock(offsetParent))) {
return window2;
}
return offsetParent || getContainingBlock(element) || window2;
}
var getElementRects = async function(_ref) {
let {
reference,
floating,
strategy
} = _ref;
const getOffsetParentFn = this.getOffsetParent || getOffsetParent;
const getDimensionsFn = this.getDimensions;
return {
reference: getRectRelativeToOffsetParent(reference, await getOffsetParentFn(floating), strategy),
floating: {
x: 0,
y: 0,
...await getDimensionsFn(floating)
}
};
};
function isRTL(element) {
return getComputedStyle2(element).direction === "rtl";
}
var platform = {
convertOffsetParentRelativeRectToViewportRelativeRect,
getDocumentElement,
getClippingRect,
getOffsetParent,
getElementRects,
getClientRects,
getDimensions,
getScale,
isElement: isElement3,
isRTL
};
function observeMove(element, onMove) {
let io = null;
let timeoutId;
const root = getDocumentElement(element);
function cleanup() {
clearTimeout(timeoutId);
io && io.disconnect();
io = null;
}
function refresh(skip, threshold) {
if (skip === void 0) {
skip = false;
}
if (threshold === void 0) {
threshold = 1;
}
cleanup();
const {
left,
top,
width,
height
} = element.getBoundingClientRect();
if (!skip) {
onMove();
}
if (!width || !height) {
return;
}
const insetTop = floor(top);
const insetRight = floor(root.clientWidth - (left + width));
const insetBottom = floor(root.clientHeight - (top + height));
const insetLeft = floor(left);
const rootMargin = -insetTop + "px " + -insetRight + "px " + -insetBottom + "px " + -insetLeft + "px";
const options = {
rootMargin,
threshold: max(0, min(1, threshold)) || 1
};
let isFirstUpdate = true;
function handleObserve(entries) {
const ratio = entries[0].intersectionRatio;
if (ratio !== threshold) {
if (!isFirstUpdate) {
return refresh();
}
if (!ratio) {
timeoutId = setTimeout(() => {
refresh(false, 1e-7);
}, 100);
} else {
refresh(false, ratio);
}
}
isFirstUpdate = false;
}
try {
io = new IntersectionObserver(handleObserve, {
...options,
// Handle