react-kd-grid 2.2.4 → 3.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/components/GridRows.d.ts +10 -18
- package/dist/components/RowContextMenu.d.ts +6 -10
- package/dist/components/SearchToolbar.d.ts +2 -18
- package/dist/hooks/useExport.d.ts +1 -2
- package/dist/index.d.ts +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/index.esm.js.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/types.d.ts +310 -308
- package/package.json +3 -3
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../node_modules/react/cjs/react-jsx-runtime.production.js","../node_modules/react/cjs/react-jsx-runtime.development.js","../node_modules/react/jsx-runtime.js","../src/constants.ts","../src/components/FooterAggregate.tsx","../src/icons/index.tsx","../src/components/filters/TextFilter.tsx","../src/components/filters/NumberFilter.tsx","../src/components/ui/DatePicker.tsx","../src/utils/dateUtils.ts","../src/components/filters/DateFilter.tsx","../src/components/filters/MultiselectFilter.tsx","../src/components/filters/BooleanFilter.tsx","../src/components/filters/FilterContent.tsx","../src/components/GridHeader.tsx","../src/components/GridRows.tsx","../src/utils/highlightText.tsx","../src/components/GroupBar.tsx","../src/components/GroupHeader.tsx","../src/components/NoDataMessage.tsx","../src/components/PaginationControls.tsx","../src/components/CustomSelect.tsx","../src/components/ColumnFilterSelector.tsx","../node_modules/@floating-ui/utils/dist/floating-ui.utils.dom.mjs","../node_modules/@floating-ui/utils/dist/floating-ui.utils.mjs","../node_modules/@floating-ui/react/dist/floating-ui.react.utils.mjs","../node_modules/@floating-ui/core/dist/floating-ui.core.mjs","../node_modules/@floating-ui/dom/dist/floating-ui.dom.mjs","../node_modules/@floating-ui/react-dom/dist/floating-ui.react-dom.mjs","../node_modules/@floating-ui/react/dist/floating-ui.react.mjs","../src/components/Popover.tsx","../src/components/SearchToolbar.tsx","../src/hooks/useAdvancedFiltering.ts","../src/hooks/useDataWorker.ts","../src/hooks/useExport.ts","../src/hooks/useGrouping.ts","../src/hooks/usePagination.ts","../src/hooks/useSelection.ts","../src/hooks/useVirtualization.ts","../src/core/DataGrid.tsx"],"sourcesContent":["/**\n * @license React\n * react-jsx-runtime.production.js\n *\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n\"use strict\";\nvar REACT_ELEMENT_TYPE = Symbol.for(\"react.transitional.element\"),\n REACT_FRAGMENT_TYPE = Symbol.for(\"react.fragment\");\nfunction jsxProd(type, config, maybeKey) {\n var key = null;\n void 0 !== maybeKey && (key = \"\" + maybeKey);\n void 0 !== config.key && (key = \"\" + config.key);\n if (\"key\" in config) {\n maybeKey = {};\n for (var propName in config)\n \"key\" !== propName && (maybeKey[propName] = config[propName]);\n } else maybeKey = config;\n config = maybeKey.ref;\n return {\n $$typeof: REACT_ELEMENT_TYPE,\n type: type,\n key: key,\n ref: void 0 !== config ? config : null,\n props: maybeKey\n };\n}\nexports.Fragment = REACT_FRAGMENT_TYPE;\nexports.jsx = jsxProd;\nexports.jsxs = jsxProd;\n","/**\n * @license React\n * react-jsx-runtime.development.js\n *\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n\"use strict\";\n\"production\" !== process.env.NODE_ENV &&\n (function () {\n function getComponentNameFromType(type) {\n if (null == type) return null;\n if (\"function\" === typeof type)\n return type.$$typeof === REACT_CLIENT_REFERENCE\n ? null\n : type.displayName || type.name || null;\n if (\"string\" === typeof type) return type;\n switch (type) {\n case REACT_FRAGMENT_TYPE:\n return \"Fragment\";\n case REACT_PROFILER_TYPE:\n return \"Profiler\";\n case REACT_STRICT_MODE_TYPE:\n return \"StrictMode\";\n case REACT_SUSPENSE_TYPE:\n return \"Suspense\";\n case REACT_SUSPENSE_LIST_TYPE:\n return \"SuspenseList\";\n case REACT_ACTIVITY_TYPE:\n return \"Activity\";\n }\n if (\"object\" === typeof type)\n switch (\n (\"number\" === typeof type.tag &&\n console.error(\n \"Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue.\"\n ),\n type.$$typeof)\n ) {\n case REACT_PORTAL_TYPE:\n return \"Portal\";\n case REACT_CONTEXT_TYPE:\n return type.displayName || \"Context\";\n case REACT_CONSUMER_TYPE:\n return (type._context.displayName || \"Context\") + \".Consumer\";\n case REACT_FORWARD_REF_TYPE:\n var innerType = type.render;\n type = type.displayName;\n type ||\n ((type = innerType.displayName || innerType.name || \"\"),\n (type = \"\" !== type ? \"ForwardRef(\" + type + \")\" : \"ForwardRef\"));\n return type;\n case REACT_MEMO_TYPE:\n return (\n (innerType = type.displayName || null),\n null !== innerType\n ? innerType\n : getComponentNameFromType(type.type) || \"Memo\"\n );\n case REACT_LAZY_TYPE:\n innerType = type._payload;\n type = type._init;\n try {\n return getComponentNameFromType(type(innerType));\n } catch (x) {}\n }\n return null;\n }\n function testStringCoercion(value) {\n return \"\" + value;\n }\n function checkKeyStringCoercion(value) {\n try {\n testStringCoercion(value);\n var JSCompiler_inline_result = !1;\n } catch (e) {\n JSCompiler_inline_result = !0;\n }\n if (JSCompiler_inline_result) {\n JSCompiler_inline_result = console;\n var JSCompiler_temp_const = JSCompiler_inline_result.error;\n var JSCompiler_inline_result$jscomp$0 =\n (\"function\" === typeof Symbol &&\n Symbol.toStringTag &&\n value[Symbol.toStringTag]) ||\n value.constructor.name ||\n \"Object\";\n JSCompiler_temp_const.call(\n JSCompiler_inline_result,\n \"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.\",\n JSCompiler_inline_result$jscomp$0\n );\n return testStringCoercion(value);\n }\n }\n function getTaskName(type) {\n if (type === REACT_FRAGMENT_TYPE) return \"<>\";\n if (\n \"object\" === typeof type &&\n null !== type &&\n type.$$typeof === REACT_LAZY_TYPE\n )\n return \"<...>\";\n try {\n var name = getComponentNameFromType(type);\n return name ? \"<\" + name + \">\" : \"<...>\";\n } catch (x) {\n return \"<...>\";\n }\n }\n function getOwner() {\n var dispatcher = ReactSharedInternals.A;\n return null === dispatcher ? null : dispatcher.getOwner();\n }\n function UnknownOwner() {\n return Error(\"react-stack-top-frame\");\n }\n function hasValidKey(config) {\n if (hasOwnProperty.call(config, \"key\")) {\n var getter = Object.getOwnPropertyDescriptor(config, \"key\").get;\n if (getter && getter.isReactWarning) return !1;\n }\n return void 0 !== config.key;\n }\n function defineKeyPropWarningGetter(props, displayName) {\n function warnAboutAccessingKey() {\n specialPropKeyWarningShown ||\n ((specialPropKeyWarningShown = !0),\n console.error(\n \"%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)\",\n displayName\n ));\n }\n warnAboutAccessingKey.isReactWarning = !0;\n Object.defineProperty(props, \"key\", {\n get: warnAboutAccessingKey,\n configurable: !0\n });\n }\n function elementRefGetterWithDeprecationWarning() {\n var componentName = getComponentNameFromType(this.type);\n didWarnAboutElementRef[componentName] ||\n ((didWarnAboutElementRef[componentName] = !0),\n console.error(\n \"Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.\"\n ));\n componentName = this.props.ref;\n return void 0 !== componentName ? componentName : null;\n }\n function ReactElement(type, key, props, owner, debugStack, debugTask) {\n var refProp = props.ref;\n type = {\n $$typeof: REACT_ELEMENT_TYPE,\n type: type,\n key: key,\n props: props,\n _owner: owner\n };\n null !== (void 0 !== refProp ? refProp : null)\n ? Object.defineProperty(type, \"ref\", {\n enumerable: !1,\n get: elementRefGetterWithDeprecationWarning\n })\n : Object.defineProperty(type, \"ref\", { enumerable: !1, value: null });\n type._store = {};\n Object.defineProperty(type._store, \"validated\", {\n configurable: !1,\n enumerable: !1,\n writable: !0,\n value: 0\n });\n Object.defineProperty(type, \"_debugInfo\", {\n configurable: !1,\n enumerable: !1,\n writable: !0,\n value: null\n });\n Object.defineProperty(type, \"_debugStack\", {\n configurable: !1,\n enumerable: !1,\n writable: !0,\n value: debugStack\n });\n Object.defineProperty(type, \"_debugTask\", {\n configurable: !1,\n enumerable: !1,\n writable: !0,\n value: debugTask\n });\n Object.freeze && (Object.freeze(type.props), Object.freeze(type));\n return type;\n }\n function jsxDEVImpl(\n type,\n config,\n maybeKey,\n isStaticChildren,\n debugStack,\n debugTask\n ) {\n var children = config.children;\n if (void 0 !== children)\n if (isStaticChildren)\n if (isArrayImpl(children)) {\n for (\n isStaticChildren = 0;\n isStaticChildren < children.length;\n isStaticChildren++\n )\n validateChildKeys(children[isStaticChildren]);\n Object.freeze && Object.freeze(children);\n } else\n console.error(\n \"React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.\"\n );\n else validateChildKeys(children);\n if (hasOwnProperty.call(config, \"key\")) {\n children = getComponentNameFromType(type);\n var keys = Object.keys(config).filter(function (k) {\n return \"key\" !== k;\n });\n isStaticChildren =\n 0 < keys.length\n ? \"{key: someKey, \" + keys.join(\": ..., \") + \": ...}\"\n : \"{key: someKey}\";\n didWarnAboutKeySpread[children + isStaticChildren] ||\n ((keys =\n 0 < keys.length ? \"{\" + keys.join(\": ..., \") + \": ...}\" : \"{}\"),\n console.error(\n 'A props object containing a \"key\" prop is being spread into JSX:\\n let props = %s;\\n <%s {...props} />\\nReact keys must be passed directly to JSX without using spread:\\n let props = %s;\\n <%s key={someKey} {...props} />',\n isStaticChildren,\n children,\n keys,\n children\n ),\n (didWarnAboutKeySpread[children + isStaticChildren] = !0));\n }\n children = null;\n void 0 !== maybeKey &&\n (checkKeyStringCoercion(maybeKey), (children = \"\" + maybeKey));\n hasValidKey(config) &&\n (checkKeyStringCoercion(config.key), (children = \"\" + config.key));\n if (\"key\" in config) {\n maybeKey = {};\n for (var propName in config)\n \"key\" !== propName && (maybeKey[propName] = config[propName]);\n } else maybeKey = config;\n children &&\n defineKeyPropWarningGetter(\n maybeKey,\n \"function\" === typeof type\n ? type.displayName || type.name || \"Unknown\"\n : type\n );\n return ReactElement(\n type,\n children,\n maybeKey,\n getOwner(),\n debugStack,\n debugTask\n );\n }\n function validateChildKeys(node) {\n isValidElement(node)\n ? node._store && (node._store.validated = 1)\n : \"object\" === typeof node &&\n null !== node &&\n node.$$typeof === REACT_LAZY_TYPE &&\n (\"fulfilled\" === node._payload.status\n ? isValidElement(node._payload.value) &&\n node._payload.value._store &&\n (node._payload.value._store.validated = 1)\n : node._store && (node._store.validated = 1));\n }\n function isValidElement(object) {\n return (\n \"object\" === typeof object &&\n null !== object &&\n object.$$typeof === REACT_ELEMENT_TYPE\n );\n }\n var React = require(\"react\"),\n REACT_ELEMENT_TYPE = Symbol.for(\"react.transitional.element\"),\n REACT_PORTAL_TYPE = Symbol.for(\"react.portal\"),\n REACT_FRAGMENT_TYPE = Symbol.for(\"react.fragment\"),\n REACT_STRICT_MODE_TYPE = Symbol.for(\"react.strict_mode\"),\n REACT_PROFILER_TYPE = Symbol.for(\"react.profiler\"),\n REACT_CONSUMER_TYPE = Symbol.for(\"react.consumer\"),\n REACT_CONTEXT_TYPE = Symbol.for(\"react.context\"),\n REACT_FORWARD_REF_TYPE = Symbol.for(\"react.forward_ref\"),\n REACT_SUSPENSE_TYPE = Symbol.for(\"react.suspense\"),\n REACT_SUSPENSE_LIST_TYPE = Symbol.for(\"react.suspense_list\"),\n REACT_MEMO_TYPE = Symbol.for(\"react.memo\"),\n REACT_LAZY_TYPE = Symbol.for(\"react.lazy\"),\n REACT_ACTIVITY_TYPE = Symbol.for(\"react.activity\"),\n REACT_CLIENT_REFERENCE = Symbol.for(\"react.client.reference\"),\n ReactSharedInternals =\n React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,\n hasOwnProperty = Object.prototype.hasOwnProperty,\n isArrayImpl = Array.isArray,\n createTask = console.createTask\n ? console.createTask\n : function () {\n return null;\n };\n React = {\n react_stack_bottom_frame: function (callStackForError) {\n return callStackForError();\n }\n };\n var specialPropKeyWarningShown;\n var didWarnAboutElementRef = {};\n var unknownOwnerDebugStack = React.react_stack_bottom_frame.bind(\n React,\n UnknownOwner\n )();\n var unknownOwnerDebugTask = createTask(getTaskName(UnknownOwner));\n var didWarnAboutKeySpread = {};\n exports.Fragment = REACT_FRAGMENT_TYPE;\n exports.jsx = function (type, config, maybeKey) {\n var trackActualOwner =\n 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++;\n return jsxDEVImpl(\n type,\n config,\n maybeKey,\n !1,\n trackActualOwner\n ? Error(\"react-stack-top-frame\")\n : unknownOwnerDebugStack,\n trackActualOwner ? createTask(getTaskName(type)) : unknownOwnerDebugTask\n );\n };\n exports.jsxs = function (type, config, maybeKey) {\n var trackActualOwner =\n 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++;\n return jsxDEVImpl(\n type,\n config,\n maybeKey,\n !0,\n trackActualOwner\n ? Error(\"react-stack-top-frame\")\n : unknownOwnerDebugStack,\n trackActualOwner ? createTask(getTaskName(type)) : unknownOwnerDebugTask\n );\n };\n })();\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/react-jsx-runtime.production.js');\n} else {\n module.exports = require('./cjs/react-jsx-runtime.development.js');\n}\n","export const SELECT_COL_WIDTH = 48; // px\n","import React, { useMemo, memo } from \"react\";\nimport { GridColumn, GridRow } from \"../types\";\nimport { SELECT_COL_WIDTH } from \"../constants\";\n\ninterface FooterAggregateProps {\n columns: (GridColumn & { width: number })[];\n data: GridRow[];\n selectable: boolean;\n /** Resolved row height so footer matches density */\n rowHeight: number;\n /** Pinned columns (same semantics as grid body) */\n pinnedColumns?: Set<string>;\n getRowId?: (row: GridRow) => string | number;\n}\n\nconst FooterAggregateComponent: React.FC<FooterAggregateProps> = ({\n columns,\n data,\n selectable,\n rowHeight,\n pinnedColumns = new Set(),\n getRowId,\n}) => {\n const aggregateValues = useMemo(() => {\n const result: Record<string, any> = {};\n\n // Only compute aggregates for columns that have footer_aggregate defined\n const columnsWithFooterAgg = columns.filter((col) => col.footer_aggregate);\n\n if (columnsWithFooterAgg.length === 0) {\n return result;\n }\n\n columnsWithFooterAgg.forEach((col) => {\n const values = data.map((row) => row[col.key]);\n let aggValue: any = null;\n\n if (typeof col.footer_aggregate === \"function\") {\n try {\n aggValue = col.footer_aggregate(values);\n } catch (error) {\n console.warn(\n `Error computing custom footer aggregate for column ${col.key}:`,\n error,\n );\n aggValue = null;\n }\n } else {\n const isDateLike = (s: string) => {\n // Common date formats: YYYY-MM-DD, DD-MM-YYYY, with '/' too\n if (/^\\d{4}-\\d{2}-\\d{2}$/.test(s)) return true;\n if (/^\\d{2}-\\d{2}-\\d{4}$/.test(s)) return true;\n if (/^\\d{4}\\/\\d{2}\\/\\d{2}$/.test(s)) return true;\n if (/^\\d{2}\\/\\d{2}\\/\\d{4}$/.test(s)) return true;\n // Fallback: if Date.parse works and the string contains '-' or '/'\n if (\n (s.includes(\"-\") || s.includes(\"/\")) &&\n Number.isFinite(Date.parse(s))\n )\n return true;\n return false;\n };\n\n const nums = values\n .map((v) => {\n if (typeof v === \"number\") return v;\n if (v == null) return NaN;\n const sv = String(v);\n // Prevent treating date-like strings as numbers (e.g., \"2025-01-01\" -> 2025)\n if (isDateLike(sv)) return NaN;\n const n = parseFloat(sv.replace(/,/g, \"\"));\n return Number.isFinite(n) ? n : NaN;\n })\n .filter((n) => Number.isFinite(n)) as number[];\n\n const tryDateNumbers = () => {\n // Convert date-like values to timestamps for min/max\n const dateNums = values\n .map((v) => {\n if (v instanceof Date) return v.getTime();\n if (typeof v === \"string\" || typeof v === \"number\") {\n const t = Date.parse(String(v));\n return Number.isFinite(t) ? t : NaN;\n }\n return NaN;\n })\n .filter((t) => Number.isFinite(t)) as number[];\n return dateNums;\n };\n\n switch (col.footer_aggregate) {\n case \"count\":\n aggValue = data.length;\n break;\n case \"sum\":\n if (nums.length) {\n aggValue = nums.reduce((a, b) => a + b, 0);\n }\n break;\n case \"avg\":\n if (nums.length) {\n const sum = nums.reduce((a, b) => a + b, 0);\n aggValue = sum / nums.length;\n }\n break;\n case \"min\":\n if (nums.length) {\n aggValue = Math.min(...nums);\n } else {\n const dateNums = tryDateNumbers();\n if (dateNums.length) {\n aggValue = new Date(Math.min(...dateNums));\n }\n }\n break;\n case \"max\":\n if (nums.length) {\n aggValue = Math.max(...nums);\n } else {\n const dateNums = tryDateNumbers();\n if (dateNums.length) {\n aggValue = new Date(Math.max(...dateNums));\n }\n }\n break;\n default:\n aggValue = null;\n }\n }\n\n if (aggValue !== null && aggValue !== undefined) {\n result[col.key] = aggValue;\n }\n });\n\n return result;\n }, [columns, data]);\n\n // Don't render if no columns have footer aggregates\n const hasFooterAggregates = columns.some((col) => col.footer_aggregate);\n if (!hasFooterAggregates) {\n return null;\n }\n\n const totalWidth = columns.reduce((sum, col) => sum + col.width, 0);\n\n // Precompute left offsets for pinned columns (mirrors GridRows logic)\n const leftOffsetByPinnedKey = useMemo(() => {\n const map = new Map<string, number>();\n const pinnedKeysInOrder = columns\n .filter((c) => pinnedColumns.has(c.key))\n .map((c) => c.key);\n let acc = selectable ? SELECT_COL_WIDTH : 0;\n for (const key of pinnedKeysInOrder) {\n map.set(key, acc);\n const w = columns.find((c) => c.key === key)?.width || 100;\n acc += w;\n }\n return map;\n }, [columns, pinnedColumns, selectable]);\n\n return (\n <div\n className=\"flex h-full\"\n style={{\n minWidth: `${totalWidth + (selectable ? SELECT_COL_WIDTH : 0)}px`,\n height: `${rowHeight}px`,\n }}\n >\n {selectable && (\n <div\n key=\"select-footer-cell\"\n className=\"w-12 p-3 border-r border-gray-200 dark:border-gray-700 flex items-center justify-center sticky left-0 bg-white dark:bg-gray-900 z-30\"\n style={{ height: `${rowHeight}px` }}\n >\n <span className=\"text-xs font-medium text-gray-600 dark:text-gray-300\">\n Total\n </span>\n </div>\n )}\n {columns.map((col) => {\n const width = col.width;\n const rawValue = aggregateValues[col.key];\n const hasAggregate = col.footer_aggregate && rawValue !== undefined;\n\n // Format value\n let displayValue = \"\";\n if (hasAggregate) {\n const formatter = col.footerAggregateFormatter || col.formatter;\n if (formatter) {\n try {\n displayValue = formatter(rawValue);\n } catch {\n displayValue = String(rawValue);\n }\n } else {\n if (typeof rawValue === \"number\") {\n displayValue =\n rawValue % 1 === 0 ? rawValue.toString() : rawValue.toFixed(2);\n } else {\n displayValue = String(rawValue?.toFixed);\n }\n }\n }\n\n const isPinned = pinnedColumns.has(col.key);\n const leftOffset = isPinned\n ? leftOffsetByPinnedKey.get(col.key) || 0\n : 0;\n const alignClass =\n col.align === \"center\"\n ? \"text-center\"\n : col.align === \"right\"\n ? \"text-right\"\n : \"text-left\";\n const justifyClass =\n col.align === \"center\"\n ? \"justify-center\"\n : col.align === \"right\"\n ? \"justify-end\"\n : \"justify-start\";\n const paddingClass = col.noPadding ? \"p-0\" : \"p-3\";\n\n return (\n <div\n key={col.key}\n className={`border-r border-gray-200 dark:border-gray-700 last:border-r-0 ${paddingClass} text-sm flex items-center font-semibold text-gray-700 dark:text-gray-200 overflow-hidden ${justifyClass} ${alignClass} ${\n isPinned ? \"sticky bg-white dark:bg-gray-900 z-20\" : \"\"\n }`}\n style={{\n width: `${width}px`,\n minWidth: `${width}px`,\n maxWidth: `${width}px`,\n left: isPinned ? `${leftOffset}px` : \"auto\",\n height: `${rowHeight}px`,\n }}\n title={hasAggregate ? `${col.header}: ${displayValue}` : undefined}\n >\n {hasAggregate && (\n <span className=\"truncate w-full\">{displayValue}</span>\n )}\n </div>\n );\n })}\n </div>\n );\n};\n\n// Memoize footer to avoid recomputing aggregates unless relevant inputs change\nexport const FooterAggregate = memo(FooterAggregateComponent, (prev, next) => {\n if (prev.selectable !== next.selectable) return false;\n if (prev.rowHeight !== next.rowHeight) return false;\n if (prev.getRowId !== next.getRowId) return false;\n if (prev.columns.length !== next.columns.length) return false;\n // Compare columns by key + width + aggregate spec reference\n for (let i = 0; i < prev.columns.length; i++) {\n const pc = prev.columns[i];\n const nc = next.columns[i];\n if (\n pc.key !== nc.key ||\n pc.width !== nc.width ||\n pc.footer_aggregate !== nc.footer_aggregate\n )\n return false;\n }\n // If data length changed or first/last row id changed, recompute\n if (prev.data.length !== next.data.length) return false;\n\n const extractId = (\n row: any,\n idx: number,\n getRowId?: (r: any) => string | number,\n ) => {\n if (getRowId) return getRowId(row);\n if (row.id !== undefined) return row.id;\n return idx;\n };\n\n const prevFirst =\n prev.data.length > 0\n ? extractId(prev.data[0], 0, prev.getRowId)\n : undefined;\n const nextFirst =\n next.data.length > 0\n ? extractId(next.data[0], 0, next.getRowId)\n : undefined;\n const prevLastIdx = prev.data.length - 1;\n const nextLastIdx = next.data.length - 1;\n const prevLast =\n prev.data.length > 0\n ? extractId(prev.data[prevLastIdx], prevLastIdx, prev.getRowId)\n : undefined;\n const nextLast =\n next.data.length > 0\n ? extractId(next.data[nextLastIdx], nextLastIdx, next.getRowId)\n : undefined;\n if (prevFirst !== nextFirst || prevLast !== nextLast) return false;\n if (prev.pinnedColumns?.size !== next.pinnedColumns?.size) return false;\n return true;\n});\n","/**\n * KDGrid Icon Library\n *\n * Hand-crafted inline SVG icons — zero external dependency.\n * Every icon accepts standard SVG props (className, style, etc.)\n * and defaults to currentColor so they inherit text color.\n *\n * All icons are 24×24 viewBox and stroke-based (strokeWidth=2),\n * matching Lucide's visual style exactly.\n */\nimport type { SVGProps } from \"react\";\n\ntype IconProps = SVGProps<SVGSVGElement> & { size?: number };\n\nconst Icon = ({\n size = 16,\n children,\n ...props\n}: IconProps & { children: React.ReactNode }) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n aria-hidden=\"true\"\n focusable=\"false\"\n {...props}\n >\n {children}\n </svg>\n);\n\n/* ─── Navigation ───────────────────────────────────────────────── */\n\nexport const ChevronLeft = (p: IconProps) => (\n <Icon {...p}>\n <polyline points=\"15 18 9 12 15 6\" />\n </Icon>\n);\n\nexport const ChevronRight = (p: IconProps) => (\n <Icon {...p}>\n <polyline points=\"9 18 15 12 9 6\" />\n </Icon>\n);\n\nexport const ChevronDown = (p: IconProps) => (\n <Icon {...p}>\n <polyline points=\"6 9 12 15 18 9\" />\n </Icon>\n);\n\nexport const ChevronsLeft = (p: IconProps) => (\n <Icon {...p}>\n <polyline points=\"11 17 6 12 11 7\" />\n <polyline points=\"18 17 13 12 18 7\" />\n </Icon>\n);\n\nexport const ChevronsRight = (p: IconProps) => (\n <Icon {...p}>\n <polyline points=\"13 17 18 12 13 7\" />\n <polyline points=\"6 17 11 12 6 7\" />\n </Icon>\n);\n\n/* ─── Arrows / Sort ─────────────────────────────────────────────── */\n\nexport const ArrowUp = (p: IconProps) => (\n <Icon {...p}>\n <line x1=\"12\" y1=\"19\" x2=\"12\" y2=\"5\" />\n <polyline points=\"5 12 12 5 19 12\" />\n </Icon>\n);\n\nexport const ArrowDown = (p: IconProps) => (\n <Icon {...p}>\n <line x1=\"12\" y1=\"5\" x2=\"12\" y2=\"19\" />\n <polyline points=\"19 12 12 19 5 12\" />\n </Icon>\n);\n\nexport const ArrowUpDown = (p: IconProps) => (\n <Icon {...p}>\n <path d=\"m21 16-4 4-4-4\" />\n <path d=\"M17 20V4\" />\n <path d=\"m3 8 4-4 4 4\" />\n <path d=\"M7 4v16\" />\n </Icon>\n);\n\n/* ─── Actions ───────────────────────────────────────────────────── */\n\nexport const X = (p: IconProps) => (\n <Icon {...p}>\n <line x1=\"18\" y1=\"6\" x2=\"6\" y2=\"18\" />\n <line x1=\"6\" y1=\"6\" x2=\"18\" y2=\"18\" />\n </Icon>\n);\n\nexport const Check = (p: IconProps) => (\n <Icon {...p}>\n <polyline points=\"20 6 9 17 4 12\" />\n </Icon>\n);\n\nexport const Copy = (p: IconProps) => (\n <Icon {...p}>\n <rect x=\"9\" y=\"9\" width=\"13\" height=\"13\" rx=\"2\" ry=\"2\" />\n <path d=\"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1\" />\n </Icon>\n);\n\nexport const Edit = (p: IconProps) => (\n <Icon {...p}>\n <path d=\"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7\" />\n <path d=\"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z\" />\n </Icon>\n);\n\nexport const Trash2 = (p: IconProps) => (\n <Icon {...p}>\n <polyline points=\"3 6 5 6 21 6\" />\n <path d=\"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6\" />\n <path d=\"M10 11v6\" />\n <path d=\"M14 11v6\" />\n <path d=\"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2\" />\n </Icon>\n);\n\nexport const Archive = (p: IconProps) => (\n <Icon {...p}>\n <polyline points=\"21 8 21 21 3 21 3 8\" />\n <rect x=\"1\" y=\"3\" width=\"22\" height=\"5\" />\n <line x1=\"10\" y1=\"12\" x2=\"14\" y2=\"12\" />\n </Icon>\n);\n\nexport const Download = (p: IconProps) => (\n <Icon {...p}>\n <path d=\"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4\" />\n <polyline points=\"7 10 12 15 17 10\" />\n <line x1=\"12\" y1=\"15\" x2=\"12\" y2=\"3\" />\n </Icon>\n);\n\n/* ─── Column / Grid Controls ────────────────────────────────────── */\n\nexport const Menu = (p: IconProps) => (\n <Icon {...p}>\n <line x1=\"3\" y1=\"12\" x2=\"21\" y2=\"12\" />\n <line x1=\"3\" y1=\"6\" x2=\"21\" y2=\"6\" />\n <line x1=\"3\" y1=\"18\" x2=\"21\" y2=\"18\" />\n </Icon>\n);\n\nexport const Filter = (p: IconProps) => (\n <Icon {...p}>\n <polygon points=\"22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3\" />\n </Icon>\n);\n\nexport const FilterX = (p: IconProps) => (\n <Icon {...p}>\n <path d=\"M13.013 3H2l8 9.46V19l4 2v-6.54l.9-1.055\" />\n <line x1=\"22\" y1=\"3\" x2=\"11\" y2=\"14\" />\n </Icon>\n);\n\nexport const Settings = (p: IconProps) => (\n <Icon {...p}>\n <circle cx=\"12\" cy=\"12\" r=\"3\" />\n <path d=\"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z\" />\n </Icon>\n);\n\nexport const Pin = (p: IconProps) => (\n <Icon {...p}>\n <line x1=\"12\" y1=\"17\" x2=\"12\" y2=\"22\" />\n <path d=\"M5 17h14v-1.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V6h1a2 2 0 0 0 0-4H8a2 2 0 0 0 0 4h1v4.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24Z\" />\n </Icon>\n);\n\nexport const PinOff = (p: IconProps) => (\n <Icon {...p}>\n <line x1=\"2\" y1=\"2\" x2=\"22\" y2=\"22\" />\n <line x1=\"12\" y1=\"17\" x2=\"12\" y2=\"22\" />\n <path d=\"M9 9v1.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V17h12\" />\n <path d=\"M15 9.34V6h1a2 2 0 0 0 0-4H7.89\" />\n </Icon>\n);\n\nexport const Group = (p: IconProps) => (\n <Icon {...p}>\n <path d=\"M3 7V5c0-1.1.9-2 2-2h2\" />\n <path d=\"M17 3h2c1.1 0 2 .9 2 2v2\" />\n <path d=\"M21 17v2c0 1.1-.9 2-2 2h-2\" />\n <path d=\"M7 21H5c-1.1 0-2-.9-2-2v-2\" />\n <rect x=\"7\" y=\"7\" width=\"10\" height=\"10\" rx=\"1\" />\n </Icon>\n);\n\nexport const Ungroup = (p: IconProps) => (\n <Icon {...p}>\n <path d=\"M3 7V5c0-1.1.9-2 2-2h2\" />\n <path d=\"M17 3h2c1.1 0 2 .9 2 2v2\" />\n <path d=\"M21 17v2c0 1.1-.9 2-2 2h-2\" />\n <path d=\"M7 21H5c-1.1 0-2-.9-2-2v-2\" />\n <rect x=\"7\" y=\"7\" width=\"4\" height=\"4\" rx=\"1\" />\n <rect x=\"13\" y=\"13\" width=\"4\" height=\"4\" rx=\"1\" />\n </Icon>\n);\n\nexport const MoreHorizontal = (p: IconProps) => (\n <Icon {...p}>\n <circle cx=\"12\" cy=\"12\" r=\"1\" />\n <circle cx=\"19\" cy=\"12\" r=\"1\" />\n <circle cx=\"5\" cy=\"12\" r=\"1\" />\n </Icon>\n);\n\n/* ─── Visibility ────────────────────────────────────────────────── */\n\nexport const Eye = (p: IconProps) => (\n <Icon {...p}>\n <path d=\"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z\" />\n <circle cx=\"12\" cy=\"12\" r=\"3\" />\n </Icon>\n);\n\nexport const EyeOff = (p: IconProps) => (\n <Icon {...p}>\n <path d=\"M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94\" />\n <path d=\"M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19\" />\n <line x1=\"1\" y1=\"1\" x2=\"23\" y2=\"23\" />\n </Icon>\n);\n\n/* ─── Data / Files ──────────────────────────────────────────────── */\n\nexport const Search = (p: IconProps) => (\n <Icon {...p}>\n <circle cx=\"11\" cy=\"11\" r=\"8\" />\n <line x1=\"21\" y1=\"21\" x2=\"16.65\" y2=\"16.65\" />\n </Icon>\n);\n\nexport const Database = (p: IconProps) => (\n <Icon {...p}>\n <ellipse cx=\"12\" cy=\"5\" rx=\"9\" ry=\"3\" />\n <path d=\"M3 5v14c0 1.66 4.03 3 9 3s9-1.34 9-3V5\" />\n <path d=\"M3 12c0 1.66 4.03 3 9 3s9-1.34 9-3\" />\n </Icon>\n);\n\nexport const FileText = (p: IconProps) => (\n <Icon {...p}>\n <path d=\"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z\" />\n <polyline points=\"14 2 14 8 20 8\" />\n <line x1=\"16\" y1=\"13\" x2=\"8\" y2=\"13\" />\n <line x1=\"16\" y1=\"17\" x2=\"8\" y2=\"17\" />\n <polyline points=\"10 9 9 9 8 9\" />\n </Icon>\n);\n\nexport const Table = (p: IconProps) => (\n <Icon {...p}>\n <rect x=\"3\" y=\"3\" width=\"18\" height=\"18\" rx=\"2\" />\n <path d=\"M3 9h18\" />\n <path d=\"M3 15h18\" />\n <path d=\"M9 3v18\" />\n </Icon>\n);\n\nexport const Users = (p: IconProps) => (\n <Icon {...p}>\n <path d=\"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2\" />\n <circle cx=\"9\" cy=\"7\" r=\"4\" />\n <path d=\"M23 21v-2a4 4 0 0 0-3-3.87\" />\n <path d=\"M16 3.13a4 4 0 0 1 0 7.75\" />\n </Icon>\n);\n\n/* ─── Misc ──────────────────────────────────────────────────────── */\n\nexport const LocateFixed = (p: IconProps) => (\n <Icon {...p}>\n <line x1=\"2\" y1=\"12\" x2=\"6\" y2=\"12\" />\n <line x1=\"18\" y1=\"12\" x2=\"22\" y2=\"12\" />\n <line x1=\"12\" y1=\"2\" x2=\"12\" y2=\"6\" />\n <line x1=\"12\" y1=\"18\" x2=\"12\" y2=\"22\" />\n <circle cx=\"12\" cy=\"12\" r=\"4\" />\n <circle cx=\"12\" cy=\"12\" r=\"1\" fill=\"currentColor\" />\n </Icon>\n);\n\nexport const Loader2 = (p: IconProps) => (\n <Icon {...p}>\n <path d=\"M21 12a9 9 0 1 1-6.219-8.56\" />\n </Icon>\n);\n","import { useState } from \"react\";\nimport { ColumnFilterValue } from \"../../types\";\n\ninterface TextFilterProps {\n value: ColumnFilterValue | null;\n onChange: (value: ColumnFilterValue | null) => void;\n placeholder?: string;\n}\n\nexport const TextFilter = ({\n value,\n onChange,\n placeholder = \"Enter text to filter...\",\n}: TextFilterProps) => {\n const [textValue, setTextValue] = useState(value?.value || \"\");\n const [operator, setOperator] = useState<\n \"contains\" | \"equals\" | \"startsWith\" | \"endsWith\"\n >((value?.operator as any) || \"contains\");\n\n const handleTextChange = (newText: string) => {\n setTextValue(newText);\n if (newText.trim()) {\n onChange({\n type: \"text\",\n value: newText,\n operator: operator as any,\n });\n } else {\n onChange(null);\n }\n };\n\n const handleOperatorChange = (newOperator: string) => {\n const op = newOperator as \"contains\" | \"equals\" | \"startsWith\" | \"endsWith\";\n setOperator(op);\n if (textValue.trim()) {\n onChange({\n type: \"text\",\n value: textValue,\n operator: op,\n });\n }\n };\n\n return (\n <div className=\"space-y-3\">\n <div>\n <label className=\"block text-sm font-medium text-gray-700 mb-1\">\n Filter Type\n </label>\n <select\n value={operator}\n onChange={(e) => handleOperatorChange(e.target.value)}\n className=\"w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500\"\n >\n <option value=\"contains\">Contains</option>\n <option value=\"equals\">Equals</option>\n <option value=\"startsWith\">Starts with</option>\n <option value=\"endsWith\">Ends with</option>\n </select>\n </div>\n\n <div>\n <label className=\"block text-sm font-medium text-gray-700 mb-1\">\n Text Value\n </label>\n <input\n type=\"text\"\n value={textValue}\n onChange={(e) => handleTextChange(e.target.value)}\n placeholder={placeholder}\n className=\"w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500\"\n />\n </div>\n </div>\n );\n};\n","import { useState } from \"react\";\nimport { ColumnFilterValue } from \"../../types\";\n\ninterface NumberFilterProps {\n value: ColumnFilterValue | null;\n onChange: (value: ColumnFilterValue | null) => void;\n min?: number;\n max?: number;\n}\n\nexport const NumberFilter = ({\n value,\n onChange,\n min,\n max,\n}: NumberFilterProps) => {\n const [numberValue, setNumberValue] = useState(value?.value || \"\");\n const [secondValue, setSecondValue] = useState(value?.secondValue || \"\");\n const [operator, setOperator] = useState<\n \"equals\" | \"gt\" | \"gte\" | \"lt\" | \"lte\" | \"between\"\n >((value?.operator as any) || \"equals\");\n\n const handleValueChange = (newValue: string, isSecond = false) => {\n if (isSecond) {\n setSecondValue(newValue);\n } else {\n setNumberValue(newValue);\n }\n\n const numValue = parseFloat(newValue);\n const numSecondValue = parseFloat(secondValue);\n\n if (operator === \"between\") {\n if (!isNaN(numValue) && !isNaN(numSecondValue)) {\n onChange({\n type: \"number\",\n value: Math.min(numValue, numSecondValue),\n secondValue: Math.max(numValue, numSecondValue),\n operator: \"between\",\n });\n } else {\n onChange(null);\n }\n } else {\n if (!isNaN(numValue)) {\n onChange({\n type: \"number\",\n value: numValue,\n operator: operator as any,\n });\n } else {\n onChange(null);\n }\n }\n };\n\n const handleOperatorChange = (newOperator: string) => {\n const op = newOperator as\n | \"equals\"\n | \"gt\"\n | \"gte\"\n | \"lt\"\n | \"lte\"\n | \"between\";\n setOperator(op);\n\n if (op === \"between\") {\n const numValue = parseFloat(numberValue);\n const numSecondValue = parseFloat(secondValue);\n if (!isNaN(numValue) && !isNaN(numSecondValue)) {\n onChange({\n type: \"number\",\n value: Math.min(numValue, numSecondValue),\n secondValue: Math.max(numValue, numSecondValue),\n operator: \"between\",\n });\n }\n } else {\n const numValue = parseFloat(numberValue);\n if (!isNaN(numValue)) {\n onChange({\n type: \"number\",\n value: numValue,\n operator: op,\n });\n }\n }\n };\n\n return (\n <div className=\"space-y-3\">\n <div>\n <label className=\"block text-sm font-medium text-gray-700 mb-1\">\n Filter Type\n </label>\n <select\n value={operator}\n onChange={(e) => handleOperatorChange(e.target.value)}\n className=\"w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500\"\n >\n <option value=\"equals\">Equals</option>\n <option value=\"gt\">Greater than</option>\n <option value=\"gte\">Greater than or equal</option>\n <option value=\"lt\">Less than</option>\n <option value=\"lte\">Less than or equal</option>\n <option value=\"between\">Between</option>\n </select>\n </div>\n\n <div>\n <label className=\"block text-sm font-medium text-gray-700 mb-1\">\n {operator === \"between\" ? \"From Value\" : \"Number Value\"}\n </label>\n <input\n type=\"number\"\n value={numberValue}\n onChange={(e) => handleValueChange(e.target.value)}\n min={min}\n max={max}\n className=\"w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500\"\n />\n </div>\n\n {operator === \"between\" && (\n <div>\n <label className=\"block text-sm font-medium text-gray-700 mb-1\">\n To Value\n </label>\n <input\n type=\"number\"\n value={secondValue}\n onChange={(e) => handleValueChange(e.target.value, true)}\n min={min}\n max={max}\n className=\"w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500\"\n />\n </div>\n )}\n </div>\n );\n};\n","import React from 'react';\n\ninterface DatePickerProps {\n name?: string;\n label?: string;\n value: string | null;\n onChange: (value: string | null) => void;\n className?: string;\n}\n\nexport const DatePicker: React.FC<DatePickerProps> = ({\n name,\n label,\n value,\n onChange,\n className = '',\n}) => {\n return (\n <div className={`space-y-1 ${className}`}>\n {label && (\n <label className=\"text-sm font-medium text-gray-700\">\n {label}\n </label>\n )}\n <input\n type=\"date\"\n name={name}\n value={value || ''}\n onChange={(e) => onChange(e.target.value || null)}\n className=\"w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500\"\n />\n </div>\n );\n};","/**\n * Minimal inline date utilities — replaces the date-fns dependency so\n * consumers don't need to install date-fns to use KDGrid.\n *\n * We only use two operations from date-fns across the entire library:\n * format(date, \"yyyy-MM-dd\") → toYMD(date)\n * parse(str, \"yyyy-MM-dd\", referenceDate) → fromYMD(str)\n *\n * These ~20 lines are far cheaper than shipping a 30 KB peer dependency.\n */\n\n/** Format a Date to \"yyyy-MM-dd\" (ISO date portion only). */\nexport const toYMD = (d: Date): string => {\n const y = d.getFullYear();\n const m = String(d.getMonth() + 1).padStart(2, \"0\");\n const day = String(d.getDate()).padStart(2, \"0\");\n return `${y}-${m}-${day}`;\n};\n\n/** Parse a \"yyyy-MM-dd\" string into a Date (local midnight). Returns Invalid Date on failure. */\nexport const fromYMD = (s: string): Date => {\n // Avoid UTC-shift that `new Date(\"yyyy-MM-dd\")` causes in all browsers.\n const [y, m, d] = s.split(\"-\").map(Number);\n if (!y || !m || !d) return new Date(NaN);\n return new Date(y, m - 1, d);\n};\n\n/** Format a Date to human-readable \"dd-MM-yyyy\" for display. */\nexport const toDMY = (d: Date): string => {\n const day = String(d.getDate()).padStart(2, \"0\");\n const m = String(d.getMonth() + 1).padStart(2, \"0\");\n const y = d.getFullYear();\n return `${day}-${m}-${y}`;\n};\n","import { useState, useEffect, useMemo } from \"react\";\nimport { ColumnFilterValue } from \"../../types\";\nimport { DatePicker } from \"../ui/DatePicker\";\nimport { toYMD, fromYMD } from \"../../utils/dateUtils\";\n\ninterface DateFilterProps {\n value: ColumnFilterValue | null;\n onChange: (value: ColumnFilterValue | null) => void;\n min?: number;\n max?: number;\n}\n\nexport const DateFilter = ({ value, onChange, min, max }: DateFilterProps) => {\n // Local UI state uses Date objects; stored values use \"yyyy-MM-dd\"\n const toDateObj = (v?: string | Date | null): Date | null => {\n if (!v) return null;\n if (v instanceof Date) return isNaN(v.getTime()) ? null : v;\n // Try parse yyyy-MM-dd first\n try {\n const d = fromYMD(String(v));\n return isNaN(d.getTime()) ? null : d;\n } catch (e) {\n const d = new Date(v);\n return isNaN(d.getTime()) ? null : d;\n }\n };\n const toStored = (d: Date | null): string => (d ? toYMD(d) : \"\");\n\n const [dateValue, setDateValue] = useState<Date | null>(\n toDateObj(value?.value as any),\n );\n const [secondDateValue, setSecondDateValue] = useState<Date | null>(\n value?.operator === \"between\"\n ? toDateObj((value?.secondValue as any) ?? (value?.value as any))\n : null,\n );\n const [operator, setOperator] = useState<\n \"equals\" | \"gt\" | \"gte\" | \"lt\" | \"lte\" | \"between\"\n >((value?.operator as any) || \"between\");\n\n // Sync local state when parent value changes (e.g., clear/apply from outside)\n useEffect(() => {\n setOperator((value?.operator as any) || \"between\");\n setDateValue(toDateObj(value?.value as any));\n setSecondDateValue(\n value?.operator === \"between\"\n ? toDateObj((value?.secondValue as any) ?? (value?.value as any))\n : null,\n );\n }, [value?.value, value?.secondValue, value?.operator]);\n\n // Handle operator changes\n useEffect(() => {\n if (operator === \"between\" && !secondDateValue && dateValue) {\n // If switching to between mode and second date is not set, initialize it with first date\n setSecondDateValue(dateValue);\n }\n }, [operator, dateValue, secondDateValue]);\n\n const clampDate = (date: Date | null, minDate?: Date, maxDate?: Date) => {\n if (!date) return null;\n if (minDate && date < minDate) return null;\n if (maxDate && date > maxDate) return null;\n return date;\n };\n\n const handleDateChange = (newDate: Date | null, isSecond = false) => {\n const nextFirst = isSecond ? dateValue : newDate;\n const nextSecond = isSecond ? newDate : secondDateValue;\n\n const maxForFirst =\n operator === \"between\" && secondDateValue ? secondDateValue : maxDateObj;\n const minForSecond = dateValue ?? minDateObj ?? undefined;\n\n const clampedDate = isSecond\n ? clampDate(newDate, minForSecond, maxDateObj)\n : clampDate(newDate, minDateObj, maxForFirst);\n\n if (isSecond) setSecondDateValue(clampedDate);\n else setDateValue(clampedDate);\n\n if (operator === \"between\") {\n if (nextFirst && nextSecond) {\n const start = nextFirst <= nextSecond ? nextFirst : nextSecond;\n const end = nextFirst >= nextSecond ? nextFirst : nextSecond;\n onChange({\n type: \"date\",\n value: toStored(start),\n secondValue: toStored(end),\n operator: \"between\",\n });\n } else {\n onChange(null);\n }\n } else {\n if (clampedDate) {\n onChange({\n type: \"date\",\n value: toStored(clampedDate),\n operator: operator as any,\n });\n } else {\n onChange(null);\n }\n }\n };\n\n const handleOperatorChange = (newOperator: string) => {\n const op = newOperator as\n | \"equals\"\n | \"gt\"\n | \"gte\"\n | \"lt\"\n | \"lte\"\n | \"between\";\n setOperator(op);\n\n if (op === \"between\") {\n if (dateValue && secondDateValue) {\n const start =\n dateValue <= secondDateValue ? dateValue : secondDateValue;\n const end = dateValue >= secondDateValue ? dateValue : secondDateValue;\n onChange({\n type: \"date\",\n value: start,\n secondValue: end,\n operator: \"between\",\n });\n }\n } else {\n if (dateValue) {\n onChange({\n type: \"date\",\n value: dateValue,\n operator: op,\n });\n }\n }\n };\n\n const minDateObj = useMemo(() => (min ? new Date(min) : undefined), [min]);\n const maxDateObj = useMemo(() => (max ? new Date(max) : undefined), [max]);\n\n return (\n <div className=\"space-y-3\">\n <div>\n <label className=\"block text-sm font-medium text-gray-700 mb-1\">\n Filter Type\n </label>\n <select\n value={operator}\n onChange={(e) => handleOperatorChange(e.target.value)}\n className=\"w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500\"\n >\n <option value=\"equals\">On Date</option>\n <option value=\"gt\">After</option>\n <option value=\"gte\">On or After</option>\n <option value=\"lt\">Before</option>\n <option value=\"lte\">On or Before</option>\n <option value=\"between\">Between Dates</option>\n </select>\n </div>\n\n <div>\n <label className=\"block text-sm font-medium text-gray-700 mb-1\">\n {operator === \"between\" ? \"From Date\" : \"Date\"}\n </label>\n <DatePicker\n name=\"date_filter_start\"\n value={dateValue ? toYMD(dateValue) : null}\n onChange={(d) => handleDateChange(d ? fromYMD(d) : null, false)}\n className=\"w-full\"\n />\n </div>\n\n {operator === \"between\" && (\n <div>\n <label className=\"block text-sm font-medium text-gray-700 mb-1\">\n To Date\n </label>\n <DatePicker\n name=\"date_filter_end\"\n value={secondDateValue ? toYMD(secondDateValue) : null}\n onChange={(d) => handleDateChange(d ? fromYMD(d) : null, true)}\n className=\"w-full\"\n />\n </div>\n )}\n </div>\n );\n};\n","import { useState, useMemo, useEffect } from \"react\";\nimport { Search, Check } from \"../../icons\";\nimport { ColumnFilterValue, FilterOption, GridRow } from \"../../types\";\n\ninterface MultiselectFilterProps {\n value: ColumnFilterValue | null;\n onChange: (value: ColumnFilterValue | null) => void;\n options?: FilterOption[];\n data: GridRow[];\n columnKey: string;\n}\n\nexport const MultiselectFilter = ({\n value,\n onChange,\n options,\n data,\n columnKey,\n}: MultiselectFilterProps) => {\n const [searchText, setSearchText] = useState(\"\");\n const [selectedValues, setSelectedValues] = useState<Set<any>>(\n new Set(value?.value || []),\n );\n\n // Sync selectedValues when value prop changes\n useEffect(() => {\n setSelectedValues(new Set(value?.value || []));\n }, [value]);\n\n // Generate options from data if not provided\n const availableOptions = useMemo(() => {\n let opts: FilterOption[] = [];\n\n // Helper to check if a value is blank\n const isBlankValue = (val: any): boolean => {\n return (\n val === null ||\n val === undefined ||\n val === \"\" ||\n (typeof val === \"string\" && val.trim() === \"\")\n );\n };\n\n if (options && options.length > 0) {\n opts = options;\n } else {\n // Normalize blank values to null and collect unique values\n const normalizedValues = data.map((row) => {\n const val = row[columnKey];\n return isBlankValue(val) ? null : val;\n });\n\n const uniqueValues = [...new Set(normalizedValues)];\n\n opts = uniqueValues.map((val) => ({\n label: val === null ? \"Blank\" : String(val),\n value: val,\n }));\n }\n\n // Transform blank/null/empty values to display as \"Blank\"\n // and sort them to the end of the list\n const processedOptions = opts.map((opt) => {\n const isBlank = isBlankValue(opt.value);\n\n return {\n ...opt,\n label: isBlank ? \"Blank\" : opt.label,\n value: isBlank ? null : opt.value, // Normalize all blank values to null\n isBlank,\n };\n });\n\n // Remove duplicates after normalization (in case options had multiple blank types)\n const uniqueProcessed = Array.from(\n new Map(\n processedOptions.map((opt) => [\n opt.isBlank ? \"__blank__\" : opt.value,\n opt,\n ]),\n ).values(),\n );\n\n // Sort: non-blank items first (alphabetically), then blank items at the end\n return uniqueProcessed.sort((a, b) => {\n if (a.isBlank && !b.isBlank) return 1;\n if (!a.isBlank && b.isBlank) return -1;\n return String(a.label).localeCompare(String(b.label));\n });\n }, [options, data, columnKey]);\n\n // Filter options based on search\n const filteredOptions = useMemo(() => {\n if (!searchText) return availableOptions;\n const searchLower = searchText.toLowerCase();\n return availableOptions.filter(\n (option) =>\n option.label.toLowerCase().includes(searchLower) ||\n String(option.value).toLowerCase().includes(searchLower) ||\n (searchLower === \"blank\" && (option as any).isBlank),\n );\n }, [availableOptions, searchText]);\n\n const handleToggleValue = (optionValue: any) => {\n const newSelected = new Set(selectedValues);\n\n if (newSelected.has(optionValue)) {\n newSelected.delete(optionValue);\n } else {\n newSelected.add(optionValue);\n }\n\n setSelectedValues(newSelected);\n\n // Update the temp filter state but don't apply immediately\n if (newSelected.size > 0) {\n onChange({\n type: \"multiselect\",\n value: Array.from(newSelected),\n operator: \"equals\",\n });\n } else {\n onChange(null);\n }\n };\n\n const handleSelectAll = () => {\n const allValues = new Set(filteredOptions.map((opt) => opt.value));\n setSelectedValues(allValues);\n onChange({\n type: \"multiselect\",\n value: Array.from(allValues),\n operator: \"equals\",\n });\n };\n\n const handleClearAll = () => {\n setSelectedValues(new Set());\n onChange(null);\n };\n\n return (\n <div className=\"space-y-3\">\n {/* Search */}\n <div className=\"relative\">\n <Search className=\"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4\" />\n <input\n type=\"text\"\n value={searchText}\n onChange={(e) => setSearchText(e.target.value)}\n placeholder=\"Search options...\"\n className=\"w-full pl-10 pr-4 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500\"\n />\n </div>\n\n {/* Actions */}\n <div className=\"flex justify-between items-center text-sm\">\n <span className=\"text-gray-600\">\n {selectedValues.size} of {availableOptions.length} selected\n </span>\n <div className=\"flex gap-2\">\n <button\n onClick={handleSelectAll}\n className=\"text-blue-600 hover:text-blue-800 transition-colors\"\n >\n Select All\n </button>\n <button\n onClick={handleClearAll}\n className=\"text-gray-600 hover:text-gray-800 transition-colors\"\n >\n Clear All\n </button>\n </div>\n </div>\n\n {/* Options List */}\n <div className=\"max-h-48 overflow-y-auto border border-gray-200 rounded-md\">\n {filteredOptions.length === 0 ? (\n <div className=\"p-3 text-sm text-gray-500 text-center\">\n No options found\n </div>\n ) : (\n filteredOptions.map((option, index) => {\n const isSelected = selectedValues.has(option.value);\n return (\n <div\n key={index}\n onClick={() => handleToggleValue(option.value)}\n className={`flex items-center gap-3 p-2 cursor-pointer hover:bg-gray-50 transition-colors ${\n isSelected ? \"bg-blue-50\" : \"\"\n }`}\n >\n <div\n className={`w-4 h-4 border-2 rounded flex items-center justify-center ${\n isSelected\n ? \"bg-blue-600 border-blue-600 text-white\"\n : \"border-gray-300\"\n }`}\n >\n {isSelected && <Check className=\"w-3 h-3\" />}\n </div>\n <span\n className={`text-sm ${\n isSelected ? \"text-blue-900 font-medium\" : \"text-gray-700\"\n } ${(option as any).isBlank ? \"italic text-gray-500\" : \"\"}`}\n >\n {option.label}\n </span>\n </div>\n );\n })\n )}\n </div>\n </div>\n );\n};\n","import { useState } from \"react\";\nimport { ColumnFilterValue } from \"../../types\";\n\ninterface BooleanFilterProps {\n value: ColumnFilterValue | null;\n onChange: (value: ColumnFilterValue | null) => void;\n}\n\nexport const BooleanFilter = ({ value, onChange }: BooleanFilterProps) => {\n const [booleanValue, setBooleanValue] = useState<string>(\n value?.value !== undefined ? String(value.value) : \"\"\n );\n\n const handleValueChange = (newValue: string) => {\n setBooleanValue(newValue);\n\n if (newValue === \"\") {\n onChange(null);\n } else {\n onChange({\n type: \"boolean\",\n value: newValue === \"true\",\n operator: \"equals\",\n });\n }\n };\n\n return (\n <div className=\"space-y-3\">\n <div>\n <label className=\"block text-sm font-medium text-gray-700 mb-1\">\n Boolean Value\n </label>\n <select\n value={booleanValue}\n onChange={(e) => handleValueChange(e.target.value)}\n className=\"w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500\"\n >\n <option value=\"\">All values</option>\n <option value=\"true\">True</option>\n <option value=\"false\">False</option>\n </select>\n </div>\n </div>\n );\n};\n","import { useMemo } from \"react\";\nimport { ColumnFilterValue, ColumnFilter, GridColumn, GridRow } from \"../../types\";\nimport { TextFilter } from \"./TextFilter\";\nimport { NumberFilter } from \"./NumberFilter\";\nimport { DateFilter } from \"./DateFilter\";\nimport { MultiselectFilter } from \"./MultiselectFilter\";\nimport { BooleanFilter } from \"./BooleanFilter\";\n\ninterface FilterContentProps {\n column: GridColumn;\n data: GridRow[];\n value: ColumnFilterValue | null;\n onChange: (val: ColumnFilterValue | null) => void;\n}\n\nexport const FilterContent = ({ column, data, value, onChange }: FilterContentProps) => {\n const filterConfig: ColumnFilter = useMemo(() => {\n if (typeof column.filterable === \"object\") return column.filterable;\n\n // Auto-detect filter type based on data\n const sampleValues = data\n .slice(0, 100)\n .map((row) => row[column.key])\n .filter((val) => val != null);\n\n if (sampleValues.length === 0) return { type: \"text\" };\n\n const firstValue = sampleValues[0];\n if (typeof firstValue === \"boolean\") return { type: \"boolean\" };\n if (typeof firstValue === \"number\") return { type: \"number\" };\n if (\n firstValue instanceof Date ||\n (typeof firstValue === \"string\" && !isNaN(Date.parse(firstValue)))\n ) {\n return { type: \"date\" };\n }\n\n const uniqueValues = [...new Set(sampleValues)];\n if (uniqueValues.length <= 20) {\n return {\n type: \"multiselect\",\n options: uniqueValues.map((val) => ({ label: String(val), value: val })),\n };\n }\n\n return { type: \"text\" };\n }, [column.filterable, column.key, data]);\n\n switch (filterConfig.type) {\n case \"text\":\n return (\n <TextFilter value={value} onChange={onChange} placeholder={filterConfig.placeholder} />\n );\n case \"number\":\n return (\n <NumberFilter value={value} onChange={onChange} min={filterConfig.min} max={filterConfig.max} />\n );\n case \"date\":\n return (\n <DateFilter value={value} onChange={onChange} min={filterConfig.min} max={filterConfig.max} />\n );\n case \"multiselect\":\n return (\n <MultiselectFilter\n value={value}\n onChange={onChange}\n options={filterConfig.options || []}\n data={data}\n columnKey={column.key}\n />\n );\n case \"boolean\":\n return <BooleanFilter value={value} onChange={onChange} />;\n default:\n return null;\n }\n};\n","import React, { memo, useEffect, useState } from \"react\";\nimport type { MouseEvent as ReactMouseEvent } from \"react\";\nimport {\n Filter,\n FilterX,\n Menu,\n Pin,\n PinOff,\n Group,\n Ungroup,\n ArrowUp,\n ArrowDown,\n ArrowUpDown,\n} from \"../icons\";\nimport {\n GridColumn,\n SortConfig,\n ActiveFilters,\n ColumnFilterValue,\n GridRow,\n} from \"../types\";\nimport { SELECT_COL_WIDTH } from \"../constants\";\nimport { FilterContent } from \"./filters/FilterContent\";\n\ninterface GridHeaderProps {\n pinnedColumns: GridColumn[];\n unpinnedColumns: GridColumn[];\n hvPadLeft?: number;\n hvPadRight?: number;\n // Fixed header height in px (use density-controlled row height)\n headerHeight: number;\n sortConfig: SortConfig;\n columnFilters: ActiveFilters;\n selectable: boolean;\n selectedRows: Set<string | number>;\n totalRows: number;\n data: GridRow[];\n onSort: (key: string) => void;\n onColumnFilter: (key: string, filter: ColumnFilterValue | null) => void;\n onSelectAll: () => void;\n onColumnResize?: (columnKey: string, width: number) => void;\n pinnedKeySet?: Set<string>;\n onColumnPin?: (columnKey: string, pinned: boolean) => void;\n groupable?: boolean;\n // Back-compat single grouped column\n groupedByColumn?: string | null;\n onGroupBy?: (columnKey: string | null) => void;\n // New multi-group API\n groupedByColumns?: string[];\n onGroupToggle?: (columnKey: string, nextGrouped: boolean) => void;\n onAutosizeColumn?: (columnKey: string) => void;\n onAutosizeAllColumns?: () => void;\n onResetColumns?: () => void;\n // Reorder props\n columnOrder: string[];\n onColumnOrderChange: (order: string[]) => void;\n // Pagination mode for auto-apply filtering\n paginationMode?: \"client\" | \"server\" | null;\n}\n\nconst GridHeaderComponent = ({\n pinnedColumns,\n unpinnedColumns,\n hvPadLeft = 0,\n hvPadRight = 0,\n headerHeight,\n sortConfig,\n columnFilters,\n selectable,\n selectedRows,\n totalRows,\n data,\n onSort,\n onColumnFilter,\n onSelectAll,\n onColumnResize,\n pinnedKeySet = new Set<string>(),\n onColumnPin,\n groupable = false,\n groupedByColumn,\n onGroupBy,\n groupedByColumns = [],\n onGroupToggle,\n onAutosizeColumn,\n onAutosizeAllColumns,\n onResetColumns,\n columnOrder,\n onColumnOrderChange,\n paginationMode = \"client\",\n}: GridHeaderProps) => {\n // Memoize so that re-renders don't allocate a new array every cycle\n const allColumns = React.useMemo(\n () => [...pinnedColumns, ...unpinnedColumns],\n [pinnedColumns, unpinnedColumns],\n );\n const [activeColumnMenu, setActiveColumnMenu] = useState<string | null>(null);\n const [menuPosition, setMenuPosition] = useState<{\n top: number;\n left: number;\n containerRect: DOMRect;\n } | null>(null);\n const [isResizing, setIsResizing] = useState<string | null>(null);\n const [startX, setStartX] = useState<number>(0);\n const [startWidth, setStartWidth] = useState<number>(0);\n const [activeTab, setActiveTab] = useState<\"menu\" | \"filter\" | \"reorder\">(\n \"menu\",\n );\n const [tempFilter, setTempFilter] = useState<ColumnFilterValue | null>(null);\n const [isTouchDevice, setIsTouchDevice] = useState(false);\n\n useEffect(() => {\n setIsTouchDevice(\n \"ontouchstart\" in window ||\n navigator.maxTouchPoints > 0 ||\n window.matchMedia(\"(pointer: coarse)\").matches,\n );\n }, []);\n\n // Reorder-in-menu state\n const [menuReorderDraggingKey, setMenuReorderDraggingKey] = useState<\n string | null\n >(null);\n const [menuReorderDragOver, setMenuReorderDragOver] = useState<{\n key: string;\n position: \"before\" | \"after\";\n } | null>(null);\n\n const isAllSelected = selectedRows.size === totalRows && totalRows > 0;\n const isIndeterminate =\n selectedRows.size > 0 && selectedRows.size < totalRows;\n\n const handleColumnMenuClick = (\n columnKey: string,\n event: ReactMouseEvent<HTMLButtonElement>,\n ) => {\n event.stopPropagation();\n if (activeColumnMenu === columnKey) {\n setActiveColumnMenu(null);\n } else {\n setActiveColumnMenu(columnKey);\n setActiveTab(\"menu\");\n setTempFilter(columnFilters[columnKey] || null);\n\n // Store button position and clamp to grid container bounds\n const rect = event.currentTarget.getBoundingClientRect();\n // Find the nearest grid container for boundary clamping\n const containerEl = event.currentTarget.closest(\n \"[data-grid-container]\",\n ) as HTMLElement | null;\n const containerRect = containerEl\n ? containerEl.getBoundingClientRect()\n : new DOMRect(0, 0, window.innerWidth, window.innerHeight);\n\n const MENU_WIDTH = 320; // matches dropdown width below\n const PADDING = 10;\n\n // Clamp left so the menu stays inside the grid container horizontally\n const minLeft = containerRect.left + PADDING;\n const maxLeft = containerRect.right - MENU_WIDTH - PADDING;\n const clampedLeft = Math.max(minLeft, Math.min(rect.left, maxLeft));\n\n setMenuPosition({\n top: rect.bottom + 4,\n left: clampedLeft,\n containerRect,\n });\n }\n };\n\n const handleApplyFilter = (columnKey: string) => {\n onColumnFilter(columnKey, tempFilter || null);\n setActiveColumnMenu(null);\n };\n\n const hasActiveFilter = (columnKey: string) => {\n return columnFilters[columnKey] != null;\n };\n\n const handleResizeStart = (columnKey: string, event: ReactMouseEvent) => {\n event.preventDefault();\n setIsResizing(columnKey);\n setStartX(event.clientX);\n const column = [...pinnedColumns, ...unpinnedColumns].find(\n (col) => col.key === columnKey,\n );\n setStartWidth(column?.width || 100);\n };\n\n const handleResizeMove = (event: globalThis.MouseEvent) => {\n if (!isResizing || !onColumnResize) return;\n\n const deltaX = event.clientX - startX;\n const newWidth = Math.max(50, startWidth + deltaX); // Minimum width of 50px\n onColumnResize(isResizing, newWidth);\n };\n\n const handleResizeEnd = () => {\n setIsResizing(null);\n setStartX(0);\n setStartWidth(0);\n };\n\n // Drag & Drop state for reordering\n const [draggingKey, setDraggingKey] = useState<string | null>(null);\n const [dragOver, setDragOver] = useState<{\n key: string;\n position: \"before\" | \"after\";\n } | null>(null);\n\n // (no-op helper removed; ordering is computed inline in handleDrop)\n\n const handleDragStart = (\n columnKey: string,\n e: React.DragEvent<HTMLDivElement>,\n ) => {\n setDraggingKey(columnKey);\n e.dataTransfer.effectAllowed = \"move\";\n e.dataTransfer.setData(\"text/plain\", columnKey);\n };\n\n const handleDragOver = (\n targetKey: string,\n e: React.DragEvent<HTMLDivElement>,\n ) => {\n // Allow drop\n e.preventDefault();\n e.dataTransfer.dropEffect = \"move\";\n const rect = (e.currentTarget as HTMLDivElement).getBoundingClientRect();\n const midpoint = rect.left + rect.width / 2;\n const position = e.clientX < midpoint ? \"before\" : \"after\";\n setDragOver({ key: targetKey, position });\n };\n\n const handleDrop = (targetKey: string) => {\n const sourceKey = draggingKey;\n if (!sourceKey || sourceKey === targetKey) return;\n\n // Prevent cross pinned/unpinned moves for clearer UX\n const sourcePinned = pinnedKeySet.has(sourceKey);\n const targetPinned = pinnedKeySet.has(targetKey);\n if (sourcePinned !== targetPinned) {\n setDraggingKey(null);\n setDragOver(null);\n return;\n }\n\n const before =\n dragOver?.key === targetKey ? dragOver?.position === \"before\" : true;\n const base = columnOrder.filter((k) => k !== sourceKey);\n let idx = base.indexOf(targetKey);\n if (idx === -1) {\n onColumnOrderChange(base);\n setDraggingKey(null);\n setDragOver(null);\n return;\n }\n if (!before) idx += 1;\n base.splice(idx, 0, sourceKey);\n const next = base;\n onColumnOrderChange(next);\n setDraggingKey(null);\n setDragOver(null);\n };\n\n const handleDragEnd = () => {\n setDraggingKey(null);\n setDragOver(null);\n };\n\n // --- Reorder handlers for the popup list ---\n const handleMenuReorderDragStart = (\n columnKey: string,\n e: React.DragEvent<HTMLDivElement>,\n ) => {\n setMenuReorderDraggingKey(columnKey);\n e.dataTransfer.effectAllowed = \"move\";\n e.dataTransfer.setData(\"text/plain\", columnKey);\n };\n\n const handleMenuReorderDragOver = (\n targetKey: string,\n e: React.DragEvent<HTMLDivElement>,\n ) => {\n e.preventDefault();\n e.dataTransfer.dropEffect = \"move\";\n const rect = (e.currentTarget as HTMLDivElement).getBoundingClientRect();\n const midpoint = rect.top + rect.height / 2;\n const position = e.clientY < midpoint ? \"before\" : \"after\";\n setMenuReorderDragOver({ key: targetKey, position });\n };\n\n const handleMenuReorderDrop = (targetKey: string) => {\n const sourceKey = menuReorderDraggingKey;\n if (!sourceKey || sourceKey === targetKey) return;\n\n // Prevent cross pinned/unpinned moves\n const sourcePinned = pinnedKeySet.has(sourceKey);\n const targetPinned = pinnedKeySet.has(targetKey);\n if (sourcePinned !== targetPinned) {\n setMenuReorderDraggingKey(null);\n setMenuReorderDragOver(null);\n return;\n }\n\n const before =\n menuReorderDragOver?.key === targetKey\n ? menuReorderDragOver?.position === \"before\"\n : true;\n const base = columnOrder.filter((k) => k !== sourceKey);\n let idx = base.indexOf(targetKey);\n if (idx === -1) {\n onColumnOrderChange(base);\n setMenuReorderDraggingKey(null);\n setMenuReorderDragOver(null);\n return;\n }\n if (!before) idx += 1;\n base.splice(idx, 0, sourceKey);\n onColumnOrderChange(base);\n setMenuReorderDraggingKey(null);\n setMenuReorderDragOver(null);\n };\n\n const handleMenuReorderDragEnd = () => {\n setMenuReorderDraggingKey(null);\n setMenuReorderDragOver(null);\n };\n\n // Add global mouse event listeners for resizing\n useEffect(() => {\n if (isResizing) {\n document.addEventListener(\"mousemove\", handleResizeMove);\n document.addEventListener(\"mouseup\", handleResizeEnd);\n document.body.style.cursor = \"col-resize\";\n document.body.style.userSelect = \"none\";\n\n return () => {\n document.removeEventListener(\"mousemove\", handleResizeMove);\n document.removeEventListener(\"mouseup\", handleResizeEnd);\n document.body.style.cursor = \"\";\n document.body.style.userSelect = \"\";\n };\n }\n }, [isResizing, startX, startWidth, onColumnResize]);\n\n // Close menu on outside click\n useEffect(() => {\n const handleClickOutside = (event: MouseEvent) => {\n const target = event.target as Element;\n if (activeColumnMenu && !target.closest(\"[data-column-menu]\")) {\n setActiveColumnMenu(null);\n }\n };\n\n if (activeColumnMenu) {\n document.addEventListener(\"mousedown\", handleClickOutside);\n return () =>\n document.removeEventListener(\"mousedown\", handleClickOutside);\n }\n }, [activeColumnMenu]);\n\n return (\n <>\n <div\n className=\"bg-blue-50 dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700\"\n style={{ height: headerHeight }}\n role=\"row\"\n aria-label=\"Column headers\"\n >\n <div className=\"flex h-full\">\n {selectable && (\n <div\n className=\"px-3 border-r border-gray-200 dark:border-gray-700 flex items-center justify-center bg-blue-50 dark:bg-gray-800 sticky left-0 z-3 h-full\"\n style={{ width: SELECT_COL_WIDTH, height: headerHeight }}\n role=\"columnheader\"\n aria-label=\"Select all rows\"\n >\n <input\n type=\"checkbox\"\n checked={isAllSelected}\n ref={(el) => {\n if (el) el.indeterminate = isIndeterminate;\n }}\n onChange={onSelectAll}\n onKeyDown={(e) => {\n if (e.key === \" \" || e.key === \"Enter\") {\n e.preventDefault();\n onSelectAll();\n }\n }}\n className=\"rounded border-gray-300 dark:border-gray-600 text-blue-600 cursor-pointer disabled:cursor-not-allowed disabled:opacity-50 h-4 w-4 transition-all duration-150\"\n aria-label={\n isAllSelected\n ? \"Deselect all rows\"\n : isIndeterminate\n ? `${selectedRows.size} rows selected. Click to select all`\n : \"Select all rows\"\n }\n title={\n isAllSelected\n ? `Deselect all ${totalRows} rows`\n : isIndeterminate\n ? `${selectedRows.size} of ${totalRows} rows selected`\n : `Select all ${totalRows} rows`\n }\n />\n </div>\n )}\n\n {/* Pinned columns */}\n {pinnedColumns.map((column, index) => {\n const isPinned = pinnedKeySet.has(column.key);\n const pinnedKeysInOrder = pinnedColumns\n .filter((c) => pinnedKeySet.has(c.key))\n .map((c) => c.key);\n const pinnedIndex = pinnedKeysInOrder.indexOf(column.key);\n const leftOffset = isPinned\n ? pinnedKeysInOrder.slice(0, pinnedIndex).reduce(\n (sum, key) => {\n const col = pinnedColumns.find((c) => c.key === key);\n return sum + (col?.width || 100);\n },\n selectable ? SELECT_COL_WIDTH : 0,\n )\n : 0;\n\n const headerJustify =\n column.headerAlign === \"center\"\n ? \"justify-center\"\n : column.headerAlign === \"right\"\n ? \"justify-end\"\n : \"justify-start\";\n\n // Determine effective sortable (default true unless explicitly false)\n const colSortable = column.sortable !== false;\n return (\n <div\n key={column.key + index}\n className={`flex-none border-r border-gray-200 dark:border-gray-700 last:border-r-0 relative ${\n isPinned\n ? \"bg-blue-50 dark:bg-blue-900/20 border-blue-200 dark:border-blue-700 sticky z-2\"\n : \"\"\n } `}\n style={{\n width: column.width || 100,\n left: isPinned ? `${leftOffset}px` : \"auto\",\n height: headerHeight,\n }}\n data-column-key={column.key}\n draggable\n onDragStart={(e) => handleDragStart(column.key, e)}\n onDragOver={(e) => handleDragOver(column.key, e)}\n onDrop={() => handleDrop(column.key)}\n onDragEnd={handleDragEnd}\n >\n {/* Drop indicator */}\n {dragOver?.key === column.key && (\n <div\n className=\"absolute top-0 bottom-0 w-0.5 bg-blue-600 z-4\"\n style={{\n left: dragOver?.position === \"before\" ? 0 : undefined,\n right: dragOver?.position === \"after\" ? 0 : undefined,\n }}\n />\n )}\n <div className=\"px-3 h-full\">\n {/* Header with sort */}\n <div className=\"flex items-center justify-between gap-1 group h-full\">\n <div\n className={`flex items-center min-w-0 flex-1 ${headerJustify} ${\n colSortable ? \"cursor-pointer hover:text-blue-600\" : \"\"\n }`}\n onClick={() => colSortable && onSort(column.key)}\n >\n <div className=\"flex items-center gap-2 min-w-0\">\n {/* Filter indicator */}\n {hasActiveFilter(column.key) && (\n <div\n className=\"w-2 h-2 bg-red-500 rounded-full shrink-0\"\n title=\"Filter applied\"\n />\n )}\n <span className=\"font-medium text-gray-900 dark:text-gray-100 text-sm truncate min-w-0\">\n {column.header}\n </span>\n </div>\n {colSortable && sortConfig.key === column.key && (\n <div className=\"ml-1 shrink-0 pointer-events-none select-none\">\n {sortConfig.direction === \"asc\" ? (\n <ArrowUp className=\"w-3 h-3 text-blue-600 dark:text-blue-400\" />\n ) : (\n <ArrowDown className=\"w-3 h-3 text-blue-600 dark:text-blue-400\" />\n )}\n </div>\n )}\n </div>\n\n {/* Three-dot menu */}\n {(column.filterable || onColumnPin || groupable) && (\n <div\n className={`relative ${\n activeColumnMenu === column.key || isTouchDevice\n ? \"block\"\n : \"hidden group-hover:block\"\n }`}\n data-column-menu\n >\n <button\n className=\"p-1 hover:bg-gray-200 dark:hover:bg-gray-700 rounded shrink-0\"\n onClick={(e) => handleColumnMenuClick(column.key, e)}\n data-menu-trigger\n >\n <Menu className=\"w-4 h-4 text-gray-500 dark:text-gray-400\" />\n </button>\n\n {/* Dropdown Menu with Tabs */}\n {activeColumnMenu === column.key && menuPosition && (\n <div\n className=\"fixed bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-md shadow-lg z-1000 w-[320px] overflow-auto\"\n style={{\n top: `${menuPosition.top}px`,\n left: `${menuPosition.left}px`,\n // Ensure the menu height never exceeds available space within the grid container\n maxHeight: `${Math.max(\n 160,\n menuPosition.containerRect.bottom -\n 12 -\n menuPosition.top,\n )}px`,\n }}\n data-column-menu\n >\n {/* Tabs */}\n <div className=\"flex items-center border-b border-gray-200 dark:border-gray-700\">\n <button\n className={`px-3 py-2 text-sm flex items-center gap-2 ${\n activeTab === \"menu\"\n ? \"border-b-2 border-blue-600 text-blue-600\"\n : \"text-gray-600\"\n }`}\n onClick={() => setActiveTab(\"menu\")}\n >\n <Menu className=\"w-4 h-4\" />\n </button>\n {column.filterable && (\n <button\n className={`px-3 py-2 text-sm flex items-center gap-2 ${\n activeTab === \"filter\"\n ? \"border-b-2 border-blue-600 text-blue-600\"\n : \"text-gray-600\"\n }`}\n onClick={() => setActiveTab(\"filter\")}\n >\n <Filter className=\"w-4 h-4\" />\n </button>\n )}\n <button\n className={`px-3 py-2 text-sm flex items-center gap-2 ${\n activeTab === \"reorder\"\n ? \"border-b-2 border-blue-600 text-blue-600\"\n : \"text-gray-600\"\n }`}\n onClick={() => setActiveTab(\"reorder\")}\n >\n <ArrowUpDown className=\"w-4 h-4\" />\n </button>\n </div>\n {/* Tab Content */}\n {activeTab === \"menu\" && (\n <div className=\"py-1\">\n {onColumnPin &&\n (groupedByColumn === column.key ? (\n <div className=\"w-full px-3 py-2 text-left text-sm flex items-center gap-2 text-blue-600\">\n <Pin className=\"w-4 h-4\" />\n Pinned by grouping\n </div>\n ) : (\n <button\n className=\"w-full px-3 py-2 text-left text-sm hover:bg-gray-50 flex items-center gap-2\"\n onClick={(e) => {\n e.stopPropagation();\n setActiveColumnMenu(null);\n onColumnPin?.(\n column.key,\n !pinnedKeySet.has(column.key),\n );\n }}\n >\n {pinnedKeySet.has(column.key) ? (\n <>\n <PinOff className=\"w-4 h-4\" />\n Unpin Column\n </>\n ) : (\n <>\n <Pin className=\"w-4 h-4\" />\n Pin Column\n </>\n )}\n </button>\n ))}\n\n {onAutosizeColumn && (\n <button\n className=\"w-full px-3 py-2 text-left text-sm hover:bg-gray-50\"\n onClick={() => {\n onAutosizeColumn?.(column.key);\n setActiveColumnMenu(null);\n }}\n >\n Autosize This Column\n </button>\n )}\n {onAutosizeAllColumns && (\n <button\n className=\"w-full px-3 py-2 text-left text-sm hover:bg-gray-50\"\n onClick={() => {\n onAutosizeAllColumns?.();\n setActiveColumnMenu(null);\n }}\n >\n Autosize All Columns\n </button>\n )}\n\n {groupable && (\n <button\n className=\"w-full px-3 py-2 text-left text-sm hover:bg-gray-50 flex items-center gap-2\"\n onClick={(e) => {\n e.stopPropagation();\n setActiveColumnMenu(null);\n const isGrouped =\n groupedByColumns?.includes(\n column.key,\n ) || groupedByColumn === column.key;\n if (onGroupToggle)\n onGroupToggle(column.key, !isGrouped);\n else\n onGroupBy?.(\n isGrouped ? null : column.key,\n );\n }}\n >\n {groupedByColumn === column.key ||\n groupedByColumns?.includes(column.key) ? (\n <>\n <Ungroup className=\"w-4 h-4\" />\n Ungroup\n </>\n ) : (\n <>\n <Group className=\"w-4 h-4\" />\n Group by {column.header}\n </>\n )}\n </button>\n )}\n\n {onResetColumns && (\n <button\n className=\"w-full px-3 py-2 text-left text-sm hover:bg-gray-50\"\n onClick={() => {\n onResetColumns?.();\n setActiveColumnMenu(null);\n }}\n >\n Reset Columns\n </button>\n )}\n </div>\n )}\n {activeTab === \"filter\" && (\n <div className=\"p-3 w-full\">\n {/* Filter Tab */}\n {hasActiveFilter(column.key) && (\n <button\n className=\"mb-2 text-xs text-red-600 hover:underline flex items-center gap-1\"\n onClick={() => {\n setTempFilter(null);\n onColumnFilter(column.key, null);\n setActiveColumnMenu(null);\n }}\n >\n <FilterX className=\"w-3 h-3\" /> Clear Filter\n </button>\n )}\n <div className=\"max-h-75 overflow-auto pr-1\">\n <FilterContent\n column={column}\n data={data}\n value={tempFilter}\n onChange={(val) => {\n setTempFilter(val);\n // Auto-apply for client-side or no pagination\n if (paginationMode !== \"server\") {\n onColumnFilter(column.key, val);\n }\n }}\n />\n </div>\n {paginationMode === \"server\" ? (\n <div className=\"flex justify-end gap-2 mt-3\">\n <button\n className=\"px-3 py-1.5 text-sm bg-gray-100 text-gray-700 rounded-md hover:bg-gray-200\"\n onClick={() => setActiveColumnMenu(null)}\n >\n Cancel\n </button>\n <button\n className=\"px-3 py-1.5 text-sm bg-blue-600 text-white rounded-md hover:bg-blue-700\"\n onClick={() =>\n handleApplyFilter(column.key)\n }\n >\n Apply\n </button>\n </div>\n ) : (\n <div className=\"flex justify-end mt-3\">\n <button\n className=\"px-3 py-1.5 text-sm bg-blue-600 text-white rounded-md hover:bg-blue-700\"\n onClick={() => setActiveColumnMenu(null)}\n >\n Close\n </button>\n </div>\n )}\n </div>\n )}\n {activeTab === \"reorder\" && (\n <div className=\"px-3 py-2\">\n <div className=\"text-xs font-medium text-gray-500 mb-1\">\n Reorder Columns\n </div>\n <div className=\"max-h-60 overflow-auto border border-gray-200 rounded-md\">\n {(() => {\n // Build ordered array by columnOrder using allColumns\n const ordered = [\n ...columnOrder\n .map((k) =>\n allColumns.find((c) => c.key === k),\n )\n .filter(Boolean),\n // add any missing\n ...allColumns.filter(\n (c) => !columnOrder.includes(c.key),\n ),\n ] as GridColumn[];\n\n return ordered.map((c) => {\n const isPinnedItem = pinnedKeySet.has(\n c.key,\n );\n return (\n <div\n key={c.key}\n className={`flex items-center justify-between px-2 py-1 text-sm bg-white hover:bg-gray-50 border-b last:border-b-0 relative ${\n menuReorderDraggingKey === c.key\n ? \"opacity-60\"\n : \"\"\n } ${\n isPinnedItem ? \"bg-blue-50/40\" : \"\"\n }`}\n draggable\n onDragStart={(e) =>\n handleMenuReorderDragStart(c.key, e)\n }\n onDragOver={(e) =>\n handleMenuReorderDragOver(c.key, e)\n }\n onDrop={() =>\n handleMenuReorderDrop(c.key)\n }\n onDragEnd={handleMenuReorderDragEnd}\n >\n {/* drop indicator */}\n {menuReorderDragOver?.key ===\n c.key && (\n <div\n className=\"absolute left-0 right-0 h-0.5 bg-blue-600\"\n style={{\n top:\n menuReorderDragOver?.position ===\n \"before\"\n ? 0\n : undefined,\n bottom:\n menuReorderDragOver?.position ===\n \"after\"\n ? 0\n : undefined,\n }}\n />\n )}\n <div className=\"flex items-center gap-2\">\n <span className=\"text-gray-400 select-none\">\n ⋮⋮\n </span>\n <span className=\"text-gray-800 truncate max-w-45\">\n {c.header}\n {isPinnedItem && (\n <span className=\"ml-1 text-[10px] text-blue-600\">\n (pinned)\n </span>\n )}\n </span>\n </div>\n </div>\n );\n });\n })()}\n </div>\n <div className=\"text-[10px] text-gray-400 mt-1\">\n Tip: You can only reorder within pinned or\n unpinned groups.\n </div>\n </div>\n )}\n </div>\n )}\n </div>\n )}\n </div>\n </div>\n\n {/* Resize handle */}\n {index < pinnedColumns.length - 1 && onColumnResize && (\n <div\n className=\"absolute top-0 right-0 w-1 h-full cursor-col-resize hover:bg-blue-300 transition-colors group\"\n onMouseDown={(e) => handleResizeStart(column.key, e)}\n onDoubleClick={(e) => {\n e.preventDefault();\n e.stopPropagation();\n onAutosizeColumn?.(column.key);\n }}\n title=\"Drag to resize • Double‑click to autosize\"\n >\n <div className=\"w-full h-full group-hover:bg-blue-400\" />\n </div>\n )}\n </div>\n );\n })}\n\n {/* Spacer before first visible unpinned col */}\n {hvPadLeft > 0 && (\n <div\n style={{ width: hvPadLeft, height: headerHeight }}\n className=\"flex-none\"\n />\n )}\n\n {/* Unpinned visible columns */}\n {unpinnedColumns.map((column, index) => {\n // unpinned visible segment\n const headerJustify =\n column.headerAlign === \"center\"\n ? \"justify-center\"\n : column.headerAlign === \"right\"\n ? \"justify-end\"\n : \"justify-start\";\n\n const colSortable = column.sortable !== false;\n return (\n <div\n key={column.key + index}\n className={`flex-none border-r border-gray-200 dark:border-gray-700 last:border-r-0 relative`}\n style={{ width: column.width || 100, height: headerHeight }}\n data-column-key={column.key}\n draggable\n onDragStart={(e) => handleDragStart(column.key, e)}\n onDragOver={(e) => handleDragOver(column.key, e)}\n onDrop={() => handleDrop(column.key)}\n onDragEnd={handleDragEnd}\n >\n {/* Drop indicator */}\n {dragOver?.key === column.key && (\n <div\n className=\"absolute top-0 bottom-0 w-0.5 bg-blue-600 z-4\"\n style={{\n left: dragOver?.position === \"before\" ? 0 : undefined,\n right: dragOver?.position === \"after\" ? 0 : undefined,\n }}\n />\n )}\n <div className=\"px-3 h-full\">\n {/* Header with sort */}\n <div className=\"flex items-center justify-between gap-1 group h-full\">\n <div\n className={`flex items-center min-w-0 flex-1 ${headerJustify} ${\n colSortable ? \"cursor-pointer hover:text-blue-600\" : \"\"\n }`}\n onClick={() => colSortable && onSort(column.key)}\n >\n <div className=\"flex items-center gap-2 min-w-0\">\n {/* Filter indicator */}\n {hasActiveFilter(column.key) && (\n <div\n className=\"w-2 h-2 bg-red-500 rounded-full shrink-0\"\n title=\"Filter applied\"\n />\n )}\n <span className=\"font-medium text-gray-900 dark:text-gray-100 text-sm truncate min-w-0\">\n {column.header}\n </span>\n </div>\n {colSortable && sortConfig.key === column.key && (\n <div className=\"ml-1 shrink-0 pointer-events-none select-none\">\n {sortConfig.direction === \"asc\" ? (\n <ArrowUp className=\"w-3 h-3 text-blue-600 dark:text-blue-400\" />\n ) : (\n <ArrowDown className=\"w-3 h-3 text-blue-600 dark:text-blue-400\" />\n )}\n </div>\n )}\n </div>\n\n {/* Three-dot menu */}\n {(column.filterable || onColumnPin || groupable) && (\n <div\n className={`relative ${\n activeColumnMenu === column.key || isTouchDevice\n ? \"block\"\n : \"hidden group-hover:block\"\n }`}\n data-column-menu\n >\n <button\n className=\"p-1 hover:bg-gray-200 dark:hover:bg-gray-700 rounded shrink-0\"\n onClick={(e) => handleColumnMenuClick(column.key, e)}\n data-menu-trigger\n >\n <Menu className=\"w-4 h-4 text-gray-500 dark:text-gray-400\" />\n </button>\n\n {/* Dropdown Menu with Tabs */}\n {activeColumnMenu === column.key && menuPosition && (\n <div\n className=\"fixed bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-md shadow-lg z-10 w-[320px] overflow-auto\"\n style={{\n top: `${menuPosition.top}px`,\n left: `${menuPosition.left}px`,\n // Ensure the menu height never exceeds available space within the grid container\n maxHeight: `${Math.max(\n 160,\n menuPosition.containerRect.bottom -\n 12 -\n menuPosition.top,\n )}px`,\n }}\n data-column-menu\n >\n {/* Tabs */}\n <div className=\"flex items-center border-b border-gray-200 dark:border-gray-700\">\n <button\n className={`px-3 py-2 text-sm flex items-center gap-2 ${\n activeTab === \"menu\"\n ? \"border-b-2 border-blue-600 text-blue-600\"\n : \"text-gray-600\"\n }`}\n onClick={() => setActiveTab(\"menu\")}\n >\n <Menu className=\"w-4 h-4\" />\n </button>\n {column.filterable && (\n <button\n className={`px-3 py-2 text-sm flex items-center gap-2 ${\n activeTab === \"filter\"\n ? \"border-b-2 border-blue-600 text-blue-600\"\n : \"text-gray-600\"\n }`}\n onClick={() => setActiveTab(\"filter\")}\n >\n <Filter className=\"w-4 h-4\" />\n </button>\n )}\n <button\n className={`px-3 py-2 text-sm flex items-center gap-2 ${\n activeTab === \"reorder\"\n ? \"border-b-2 border-blue-600 text-blue-600\"\n : \"text-gray-600\"\n }`}\n onClick={() => setActiveTab(\"reorder\")}\n >\n <ArrowUpDown className=\"w-4 h-4\" />\n </button>\n </div>\n {/* Tab Content (reusing existing code paths) */}\n {activeTab === \"menu\" && (\n <div className=\"py-1\">\n {onColumnPin && (\n <button\n className=\"w-full px-3 py-2 text-left text-sm hover:bg-gray-50 flex items-center gap-2\"\n onClick={(e) => {\n e.stopPropagation();\n setActiveColumnMenu(null);\n const nextPinned = !pinnedKeySet.has(\n column.key,\n );\n onColumnPin?.(column.key, nextPinned);\n }}\n >\n {pinnedKeySet.has(column.key) ? (\n <>\n <PinOff className=\"w-4 h-4\" />\n Unpin Column\n </>\n ) : (\n <>\n <Pin className=\"w-4 h-4\" />\n Pin Column\n </>\n )}\n </button>\n )}\n {onAutosizeColumn && (\n <button\n className=\"w-full px-3 py-2 text-left text-sm hover:bg-gray-50\"\n onClick={() => {\n onAutosizeColumn?.(column.key);\n setActiveColumnMenu(null);\n }}\n >\n Autosize This Column\n </button>\n )}\n {onAutosizeAllColumns && (\n <button\n className=\"w-full px-3 py-2 text-left text-sm hover:bg-gray-50\"\n onClick={() => {\n onAutosizeAllColumns?.();\n setActiveColumnMenu(null);\n }}\n >\n Autosize All Columns\n </button>\n )}\n\n {groupable && (\n <button\n className=\"w-full px-3 py-2 text-left text-sm hover:bg-gray-50 flex items-center gap-2\"\n onClick={(e) => {\n e.stopPropagation();\n setActiveColumnMenu(null);\n const isGrouped =\n groupedByColumns?.includes(\n column.key,\n ) || groupedByColumn === column.key;\n if (onGroupToggle)\n onGroupToggle(column.key, !isGrouped);\n else\n onGroupBy?.(\n isGrouped ? null : column.key,\n );\n }}\n >\n {groupedByColumn === column.key ||\n groupedByColumns?.includes(column.key) ? (\n <>\n <Ungroup className=\"w-4 h-4\" />\n Ungroup\n </>\n ) : (\n <>\n <Group className=\"w-4 h-4\" />\n Group by {column.header}\n </>\n )}\n </button>\n )}\n\n {onResetColumns && (\n <button\n className=\"w-full px-3 py-2 text-left text-sm hover:bg-gray-50\"\n onClick={() => {\n onResetColumns?.();\n setActiveColumnMenu(null);\n }}\n >\n Reset Columns\n </button>\n )}\n </div>\n )}\n {activeTab === \"filter\" && (\n <div className=\"p-3 w-full\">\n <div className=\"max-h-75 overflow-auto pr-1\">\n <FilterContent\n column={column}\n data={data}\n value={tempFilter}\n onChange={(val) => {\n setTempFilter(val);\n // Auto-apply for client-side or no pagination\n if (paginationMode !== \"server\") {\n onColumnFilter(column.key, val);\n }\n }}\n />\n </div>\n <div className=\"flex justify-end gap-2 mt-3\">\n {hasActiveFilter(column.key) && (\n <button\n className=\"px-3 py-1.5 text-sm bg-red-500 text-white rounded-md hover:bg-red-600 flex items-center gap-2 cursor-pointer\"\n onClick={() => {\n setTempFilter(null);\n onColumnFilter(column.key, null);\n setActiveColumnMenu(null);\n }}\n >\n <FilterX className=\"w-3 h-3\" /> Clear\n Filter\n </button>\n )}\n <button\n className=\"px-3 py-1.5 text-sm bg-green-100 text-green-700 rounded-md hover:bg-green-200 cursor-pointer\"\n onClick={() => setActiveColumnMenu(null)}\n >\n Apply\n </button>\n {paginationMode === \"server\" && (\n <button\n className=\"px-3 py-1.5 text-sm bg-blue-600 text-white rounded-md hover:bg-blue-700\"\n onClick={() =>\n handleApplyFilter(column.key)\n }\n >\n Apply\n </button>\n )}\n </div>\n </div>\n )}\n {activeTab === \"reorder\" && (\n <div className=\"px-3 py-2\">\n <div className=\"text-xs font-medium text-gray-500 mb-1\">\n Reorder Columns\n </div>\n <div className=\"max-h-60 overflow-auto border border-gray-200 rounded-md\">\n {(() => {\n const ordered = [\n ...columnOrder\n .map((k) =>\n allColumns.find((c) => c.key === k),\n )\n .filter(Boolean),\n ...allColumns.filter(\n (c) => !columnOrder.includes(c.key),\n ),\n ] as GridColumn[];\n\n return ordered.map((c) => {\n const isPinnedItem = pinnedKeySet.has(\n c.key,\n );\n return (\n <div\n key={c.key}\n className={`flex items-center justify-between px-2 py-1 text-sm bg-white hover:bg-gray-50 border-b last:border-b-0 relative ${\n menuReorderDraggingKey === c.key\n ? \"opacity-60\"\n : \"\"\n } ${\n isPinnedItem ? \"bg-blue-50/40\" : \"\"\n }`}\n draggable\n onDragStart={(e) =>\n handleMenuReorderDragStart(c.key, e)\n }\n onDragOver={(e) =>\n handleMenuReorderDragOver(c.key, e)\n }\n onDrop={() =>\n handleMenuReorderDrop(c.key)\n }\n onDragEnd={handleMenuReorderDragEnd}\n >\n {menuReorderDragOver?.key ===\n c.key && (\n <div\n className=\"absolute left-0 right-0 h-0.5 bg-blue-600\"\n style={{\n top:\n menuReorderDragOver?.position ===\n \"before\"\n ? 0\n : undefined,\n bottom:\n menuReorderDragOver?.position ===\n \"after\"\n ? 0\n : undefined,\n }}\n />\n )}\n <div className=\"flex items-center gap-2\">\n <span className=\"text-gray-400 select-none\">\n ⋮⋮\n </span>\n <span className=\"text-gray-800 truncate max-w-45\">\n {c.header}\n {isPinnedItem && (\n <span className=\"ml-1 text-[10px] text-blue-600\">\n (pinned)\n </span>\n )}\n </span>\n </div>\n </div>\n );\n });\n })()}\n </div>\n <div className=\"text-[10px] text-gray-400 mt-1\">\n Tip: You can only reorder within pinned or\n unpinned groups.\n </div>\n </div>\n )}\n </div>\n )}\n </div>\n )}\n </div>\n </div>\n\n {/* Resize handle */}\n {index < unpinnedColumns.length - 1 && onColumnResize && (\n <div\n className=\"absolute top-0 right-0 w-1 h-full cursor-col-resize hover:bg-blue-300 transition-colors group\"\n onMouseDown={(e) => handleResizeStart(column.key, e)}\n onDoubleClick={(e) => {\n e.preventDefault();\n e.stopPropagation();\n onAutosizeColumn?.(column.key);\n }}\n title=\"Drag to resize • Double‑click to autosize\"\n >\n <div className=\"w-full h-full group-hover:bg-blue-400\" />\n </div>\n )}\n </div>\n );\n })}\n\n {/* Spacer after last visible unpinned col */}\n {hvPadRight > 0 && (\n <div\n style={{ width: hvPadRight, height: headerHeight }}\n className=\"flex-none\"\n />\n )}\n </div>\n </div>\n\n {/* Inline filter handled in dropdown tabs */}\n </>\n );\n};\n\nGridHeaderComponent.displayName = \"GridHeader\";\nexport const GridHeader = /*#__PURE__*/ memo(GridHeaderComponent);\n","import { CSSProperties, MouseEvent, memo, useMemo } from \"react\";\nimport { GridRow, GridColumn, VirtualizedRange } from \"../types\";\nimport { SELECT_COL_WIDTH } from \"../constants\";\nimport { highlightText, containsSearchQuery } from \"../utils/highlightText\";\n\ninterface GridRowsProps {\n data: GridRow[];\n columns: GridColumn[];\n selectedRows: Set<string | number>;\n virtualized: boolean;\n virtualizedRange: VirtualizedRange;\n rowHeight: number;\n selectable: boolean;\n isRowSelectable?: (row: GridRow) => boolean;\n onRowSelect: (rowId: string | number, isSelected: boolean) => void;\n pinnedColumns?: Set<string>;\n hvPadLeft?: number;\n hvPadRight?: number;\n rowStyle?: (row: GridRow) => CSSProperties | undefined;\n globalFilter?: string;\n onContextMenu?: (row: GridRow, event: MouseEvent) => void;\n onRowDoubleClick?: (row: GridRow, event: MouseEvent) => void;\n onRowClick?: (row: GridRow, event: MouseEvent) => void;\n onCellClick?: (args: {\n row: GridRow;\n column: GridColumn;\n value: any;\n event: MouseEvent;\n }) => void;\n // Cell focus & selection\n isCellFocused?: (rowId: string | number, columnKey: string) => boolean;\n isCellSelected?: (rowId: string | number, columnKey: string) => boolean;\n // Cell-level context menu (right-click)\n onCellContextMenu?: (args: {\n row: GridRow;\n column: GridColumn;\n value: any;\n displayValue: string;\n event: MouseEvent;\n }) => void;\n onCellMouseDown?: (args: {\n row: GridRow;\n column: GridColumn;\n event: MouseEvent;\n }) => void;\n onCellMouseEnter?: (args: {\n row: GridRow;\n column: GridColumn;\n event: MouseEvent;\n }) => void;\n getRowId?: (row: GridRow) => string | number;\n}\n\nconst GridRowsComponent = ({\n data,\n columns,\n selectedRows,\n virtualized,\n virtualizedRange,\n rowHeight,\n selectable,\n isRowSelectable,\n onRowSelect,\n pinnedColumns = new Set(),\n hvPadLeft = 0,\n hvPadRight = 0,\n rowStyle,\n globalFilter,\n onContextMenu,\n onRowDoubleClick,\n onRowClick,\n onCellClick,\n isCellFocused,\n isCellSelected,\n onCellContextMenu,\n onCellMouseDown,\n onCellMouseEnter,\n getRowId,\n}: GridRowsProps) => {\n // Helper to extract row ID\n const extractRowId = (row: GridRow, rowIndex?: number): string | number => {\n if (getRowId) {\n return getRowId(row);\n }\n if (row.id !== undefined) {\n return row.id;\n }\n // Fallback: use row index\n if (process.env.NODE_ENV === \"development\" && rowIndex === 0) {\n console.warn(\n \"[KDGrid] No row IDs found. Either:\\n\" +\n \" 1. Add 'id' property to each row object, or\\n\" +\n \" 2. Provide 'getRowId' prop to extract a unique identifier.\\n\" +\n \" Using row index as fallback ID, but this may cause issues with pagination/filtering.\",\n );\n }\n return rowIndex ?? 0;\n };\n const totalHeight = useMemo(\n () => data.length * rowHeight,\n [data.length, rowHeight],\n );\n\n // Precompute pinned metadata for left offsets efficiently - OPTIMIZED\n const { leftOffsetByPinnedKey } = useMemo(() => {\n // Early return if no pinned columns\n if (pinnedColumns.size === 0) {\n return { leftOffsetByPinnedKey: new Map<string, number>() };\n }\n\n const pinnedKeysInOrder = columns\n .filter((c) => pinnedColumns.has(c.key))\n .map((c) => c.key);\n\n // Use direct property access instead of Map for better performance\n const widthByKey = new Map<string, number>();\n for (const col of columns) {\n widthByKey.set(col.key, col.width || 100);\n }\n\n const leftOffsetByPinnedKey = new Map<string, number>();\n let acc = selectable ? SELECT_COL_WIDTH : 0;\n\n for (const key of pinnedKeysInOrder) {\n leftOffsetByPinnedKey.set(key, acc);\n acc += widthByKey.get(key) || 100;\n }\n\n return { leftOffsetByPinnedKey };\n }, [columns, pinnedColumns, selectable]);\n\n // Count how many columns are pinned in the provided visible columns list\n const pinnedCount = useMemo(\n () => columns.reduce((n, c) => n + (pinnedColumns.has(c.key) ? 1 : 0), 0),\n [columns, pinnedColumns],\n );\n\n const handleContextMenu = (e: MouseEvent, row: GridRow) => {\n e.preventDefault();\n onContextMenu?.(row, e);\n };\n\n const handleDoubleClick = (e: MouseEvent, row: GridRow) => {\n onRowDoubleClick?.(row, e);\n };\n\n const handleRowClick = (e: MouseEvent, row: GridRow) => {\n onRowClick?.(row, e);\n };\n\n const handleCellClick = (\n e: MouseEvent,\n row: GridRow,\n column: GridColumn,\n value: any,\n ) => {\n onCellClick?.({ row, column, value, event: e });\n };\n\n return (\n <div\n style={{\n height: virtualized ? `${totalHeight}px` : \"auto\",\n position: \"relative\",\n }}\n >\n <div\n style={{\n transform: virtualized\n ? `translate3d(0, ${virtualizedRange.offsetY}px, 0)`\n : \"none\",\n position: virtualized ? \"absolute\" : \"static\",\n top: 0,\n left: 0,\n right: 0,\n }}\n >\n {data.map((row, index) => {\n const actualIndex = virtualized\n ? virtualizedRange.startIndex + index\n : index;\n const customRowStyles = rowStyle?.(row);\n const rowId = extractRowId(row, actualIndex);\n const defaultRowColor =\n actualIndex % 2 === 0\n ? \"bg-white dark:bg-gray-900\"\n : \"bg-gray-25 dark:bg-gray-800\";\n const selectedRowColor = selectedRows.has(rowId)\n ? \"bg-blue-50 dark:bg-blue-900/20\"\n : \"\";\n\n return (\n <div\n key={`${rowId}-${actualIndex}`}\n className={`flex border-b border-gray-100 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-700 ${\n selectedRowColor || (customRowStyles ? \"\" : defaultRowColor)\n }`}\n style={{\n height: `${rowHeight}px`,\n ...customRowStyles,\n }}\n onContextMenu={(e) => handleContextMenu(e, row)}\n onDoubleClick={(e) => handleDoubleClick(e, row)}\n onClick={(e) => handleRowClick(e, row)}\n >\n {selectable && (\n <div\n className=\"flex items-center justify-center sticky left-0 bg-white dark:bg-gray-900 z-2 border-r border-gray-200 dark:border-gray-700\"\n style={{ width: SELECT_COL_WIDTH }}\n >\n <input\n type=\"checkbox\"\n checked={selectedRows.has(rowId)}\n disabled={isRowSelectable ? !isRowSelectable(row) : false}\n onChange={(e) => onRowSelect(rowId, e.target.checked)}\n onKeyDown={(e) => {\n if (e.key === \" \" || e.key === \"Enter\") {\n e.preventDefault();\n onRowSelect(rowId, !selectedRows.has(rowId));\n }\n }}\n className=\"rounded border-gray-300 dark:border-gray-600 text-blue-600 cursor-pointer disabled:cursor-not-allowed disabled:opacity-50 h-4 w-4 transition-all duration-150\"\n aria-label={`Select row ${rowId}`}\n tabIndex={0}\n />\n </div>\n )}\n\n {columns.map((column, colIndex) => {\n const isPinned = pinnedColumns.has(column.key);\n const leftOffset = isPinned\n ? leftOffsetByPinnedKey.get(column.key) || 0\n : 0;\n\n // Optimized cell value processing\n const rawCell = row[column.key];\n let renderedValue: React.ReactNode;\n let displayValue: string | undefined;\n\n // Optimize cell renderer calls\n if (column.cellRenderer) {\n renderedValue = column.cellRenderer(rawCell, row);\n // Only compute display value if needed for tooltip\n if (\n typeof rawCell === \"string\" ||\n typeof rawCell === \"number\" ||\n typeof rawCell === \"boolean\"\n ) {\n displayValue = String(rawCell);\n }\n } else if (column.formatter) {\n renderedValue = column.formatter(rawCell);\n displayValue = String(renderedValue);\n } else {\n renderedValue = rawCell ?? \"\";\n displayValue = renderedValue\n ? String(renderedValue)\n : undefined;\n }\n\n // Apply highlighting for global filter if present and no custom renderer\n if (\n globalFilter &&\n globalFilter.trim() &&\n !column.cellRenderer &&\n renderedValue\n ) {\n const textValue = String(renderedValue);\n if (containsSearchQuery(textValue, globalFilter)) {\n renderedValue = highlightText(textValue, globalFilter);\n }\n }\n\n // Clean up empty display values\n if (displayValue && displayValue.trim().length === 0) {\n displayValue = undefined;\n }\n\n // Pre-compute CSS classes for better performance\n const alignClass =\n column.align === \"center\"\n ? \"text-center\"\n : column.align === \"right\"\n ? \"text-right\"\n : \"text-left\";\n const justifyClass =\n column.align === \"center\"\n ? \"justify-center\"\n : column.align === \"right\"\n ? \"justify-end\"\n : \"justify-start\";\n const paddingClass = column.noPadding ? \"p-0\" : \"p-3\";\n\n // Optimize dynamic class/style computation\n const extraCellClass =\n typeof column.className === \"function\"\n ? column.className(rawCell, row)\n : column.className || \"\";\n const extraCellStyle =\n typeof column.cellStyle === \"function\"\n ? column.cellStyle(rawCell, row)\n : column.cellStyle || undefined;\n\n const cell = (\n <div\n key={`${column.key}-${colIndex}`}\n className={`border-r border-gray-200 last:border-r-0 ${paddingClass} text-sm flex items-center ${\n isCellSelected?.(rowId, column.key)\n ? \"bg-blue-100/60 dark:bg-blue-900/30\"\n : \"\"\n } ${\n isPinned\n ? isCellFocused?.(rowId, column.key)\n ? \"sticky z-2 bg-inherit\"\n : \"sticky z-1 bg-inherit\"\n : \"\"\n } ${\n isCellFocused?.(rowId, column.key) ? \"relative\" : \"\"\n } ${alignClass} ${justifyClass} ${extraCellClass}`}\n style={{\n width: `${column.width || 100}px`,\n left: isPinned ? `${leftOffset}px` : \"auto\",\n ...extraCellStyle,\n }}\n // Show native tooltip only when a meaningful value exists (non-empty string after trimming)\n title={displayValue}\n onClick={(e) =>\n handleCellClick(e, row, column, row[column.key])\n }\n onContextMenu={(e) => {\n // Only handle for real data rows\n if (\n (row as any)._isGroupHeader ||\n (row as any)._isGroupFooter\n )\n return;\n if (onCellContextMenu) {\n e.preventDefault();\n e.stopPropagation();\n onCellContextMenu({\n row,\n column,\n value: (row as any)[column.key],\n displayValue: displayValue ?? \"\",\n event: e as any,\n });\n }\n // If no onCellContextMenu prop, fall back to row-level handler (do not stop propagation)\n }}\n onMouseDown={(e) =>\n onCellMouseDown?.({ row, column, event: e })\n }\n onMouseEnter={(e) =>\n onCellMouseEnter?.({ row, column, event: e })\n }\n >\n {isCellFocused?.(rowId, column.key) && (\n <div className=\"pointer-events-none absolute inset-0 border border-blue-400\" />\n )}\n {column.wrapCellContent === false ? (\n <>{renderedValue}</>\n ) : (\n <div className=\"truncate w-full\">{renderedValue}</div>\n )}\n </div>\n );\n // Insert left spacer once before the first unpinned visible column\n if (hvPadLeft > 0 && colIndex === pinnedCount) {\n return (\n <>\n <div style={{ width: hvPadLeft }} className=\"flex-none\" />\n {cell}\n </>\n );\n }\n\n return cell;\n })}\n {/* Spacer after last visible unpinned col */}\n {hvPadRight > 0 && (\n <div style={{ width: hvPadRight }} className=\"flex-none\" />\n )}\n </div>\n );\n })}\n </div>\n </div>\n );\n};\n\nconst areEqual = (prev: GridRowsProps, next: GridRowsProps) => {\n if (prev.rowHeight !== next.rowHeight) return false;\n if (prev.selectable !== next.selectable) return false;\n if (prev.virtualized !== next.virtualized) return false;\n if (prev.globalFilter !== next.globalFilter) return false;\n if (prev.virtualizedRange.startIndex !== next.virtualizedRange.startIndex)\n return false;\n if (prev.virtualizedRange.endIndex !== next.virtualizedRange.endIndex)\n return false;\n if (prev.virtualizedRange.offsetY !== next.virtualizedRange.offsetY)\n return false;\n // Re-render when focus/selection functions change identity (they depend on selection & focus states)\n if (prev.isCellSelected !== next.isCellSelected) return false;\n if (prev.isCellFocused !== next.isCellFocused) return false;\n // Re-render when drag-selection handlers change identity (closure depends on selectionAnchor/end)\n if (prev.onCellMouseDown !== next.onCellMouseDown) return false;\n if (prev.onCellMouseEnter !== next.onCellMouseEnter) return false;\n if (prev.getRowId !== next.getRowId) return false;\n if (prev.selectedRows.size !== next.selectedRows.size) return false;\n if (prev.pinnedColumns?.size !== next.pinnedColumns?.size) return false;\n const prevCols = prev.columns.map((c) => c.key).join(\"|\");\n const nextCols = next.columns.map((c) => c.key).join(\"|\");\n if (prevCols !== nextCols) return false;\n if (prev.data.length !== next.data.length) return false;\n\n // Fast path: same array reference → nothing changed\n if (prev.data === next.data) return true;\n\n // Full ID scan: detects mutations anywhere in the list (not just first/last).\n // O(n) but n = visible rows only (typically 20-80), not the entire dataset.\n const extractId = (\n row: GridRow,\n idx: number,\n getRowId?: (r: GridRow) => string | number,\n ) => {\n if (getRowId) return getRowId(row);\n if (row.id !== undefined) return row.id;\n return idx;\n };\n\n for (let i = 0; i < next.data.length; i++) {\n const pid = extractId(prev.data[i], i, prev.getRowId);\n const nid = extractId(next.data[i], i, next.getRowId);\n if (pid !== nid) return false;\n }\n\n return true;\n};\n\nGridRowsComponent.displayName = \"GridRows\";\nexport const GridRows = /*#__PURE__*/ memo(GridRowsComponent, areEqual);\n","import React from \"react\";\n\n/**\n * Highlights matching text within a string based on a search query\n * @param text - The text to highlight\n * @param searchQuery - The search query to match against\n * @returns JSX element with highlighted matches\n */\nexport const highlightText = (\n text: string,\n searchQuery: string\n): React.ReactNode => {\n if (!searchQuery || !text) {\n return text;\n }\n\n const query = searchQuery.toLowerCase().trim();\n const lowerText = text.toLowerCase();\n\n if (!query || !lowerText.includes(query)) {\n return text;\n }\n\n const parts: React.ReactNode[] = [];\n let lastIndex = 0;\n let searchIndex = 0;\n let keyCounter = 0; // Use counter for unique keys\n\n while ((searchIndex = lowerText.indexOf(query, lastIndex)) !== -1) {\n // Add text before the match\n if (searchIndex > lastIndex) {\n parts.push(text.slice(lastIndex, searchIndex));\n }\n\n // Add the highlighted match\n parts.push(\n <mark\n key={`highlight-${keyCounter++}`}\n className=\"bg-yellow-200 dark:bg-yellow-600/40 text-current font-medium px-0.5 py-0 rounded-sm\"\n style={{ margin: 0 }} // Ensure no unwanted margins\n >\n {text.slice(searchIndex, searchIndex + query.length)}\n </mark>\n );\n\n lastIndex = searchIndex + query.length;\n }\n\n // Add remaining text after the last match\n if (lastIndex < text.length) {\n parts.push(text.slice(lastIndex));\n }\n\n return <>{parts}</>;\n};\n\n/**\n * Checks if a value contains the search query (case-insensitive)\n * @param value - The value to check\n * @param searchQuery - The search query\n * @returns true if the value contains the search query\n */\nexport const containsSearchQuery = (\n value: any,\n searchQuery: string\n): boolean => {\n if (!searchQuery || value == null) {\n return false;\n }\n\n const query = searchQuery.toLowerCase().trim();\n if (!query) {\n return false;\n }\n\n const text = String(value).toLowerCase();\n return text.includes(query);\n};\n","import { useState } from \"react\";\nimport type { GridColumn } from \"../types\";\n\ninterface GroupBarProps {\n columns: GridColumn[];\n groupedKeys: string[];\n onRemove: (columnKey: string) => void;\n onReorder: (newOrder: string[]) => void;\n onDropColumnKey: (columnKey: string) => void;\n onToggleExpandAll?: () => void;\n isAnyExpanded?: boolean;\n}\n\nexport const GroupBar = ({\n columns,\n groupedKeys,\n onRemove,\n onReorder,\n onDropColumnKey,\n onToggleExpandAll,\n isAnyExpanded = false,\n}: GroupBarProps) => {\n const [dragKey, setDragKey] = useState<string | null>(null);\n const [dragOverKey, setDragOverKey] = useState<string | null>(null);\n const [dragOverBefore, setDragOverBefore] = useState<boolean>(true);\n\n const labelFor = (key: string) => columns.find((c) => c.key === key)?.header || key;\n\n const handleDropFromHeader: React.DragEventHandler<HTMLDivElement> = (e) => {\n e.preventDefault();\n const key = e.dataTransfer.getData(\"text/plain\");\n if (!key) return;\n if (!groupedKeys.includes(key)) onDropColumnKey(key);\n };\n\n const onDragOverBar: React.DragEventHandler<HTMLDivElement> = (e) => {\n e.preventDefault();\n };\n\n const handleChipDragStart = (key: string): React.DragEventHandler<HTMLDivElement> => (e) => {\n setDragKey(key);\n e.dataTransfer.effectAllowed = \"move\";\n e.dataTransfer.setData(\"application/x-group-key\", key);\n };\n\n const handleChipDragOver = (key: string): React.DragEventHandler<HTMLDivElement> => (e) => {\n e.preventDefault();\n const rect = (e.currentTarget as HTMLDivElement).getBoundingClientRect();\n const before = e.clientX < rect.left + rect.width / 2;\n setDragOverKey(key);\n setDragOverBefore(before);\n };\n\n const handleChipDrop = (targetKey: string): React.DragEventHandler<HTMLDivElement> => () => {\n if (!dragKey || dragKey === targetKey) {\n setDragKey(null);\n setDragOverKey(null);\n return;\n }\n const order = groupedKeys.filter((k) => k !== dragKey);\n const idx = order.indexOf(targetKey);\n if (idx === -1) return;\n if (!dragOverBefore) {\n order.splice(idx + 1, 0, dragKey);\n } else {\n order.splice(idx, 0, dragKey);\n }\n onReorder(order);\n setDragKey(null);\n setDragOverKey(null);\n };\n\n const clearDnD = () => {\n setDragKey(null);\n setDragOverKey(null);\n };\n\n return (\n <div\n className=\"flex items-center gap-2 px-3 py-2 bg-gray-50 border-b border-gray-200 text-sm\"\n onDrop={handleDropFromHeader}\n onDragOver={onDragOverBar}\n onDragEnd={clearDnD}\n >\n <span className=\"text-gray-600 whitespace-nowrap\">Group by:</span>\n {groupedKeys.length > 0 && (\n <button\n type=\"button\"\n className=\"ml-1 px-2 py-1 text-xs border border-gray-300 rounded hover:bg-gray-100\"\n title={isAnyExpanded ? \"Collapse all groups\" : \"Expand all groups\"}\n onClick={(e) => {\n e.preventDefault();\n e.stopPropagation();\n onToggleExpandAll?.();\n }}\n >\n {isAnyExpanded ? \"Collapse All\" : \"Expand All\"}\n </button>\n )}\n {groupedKeys.length === 0 && (\n <span className=\"text-gray-400\">Drag a column here</span>\n )}\n <div className=\"flex items-center gap-2 flex-wrap\">\n {groupedKeys.map((key) => (\n <div\n key={key}\n className=\"inline-flex items-center gap-2 bg-blue-100 text-blue-800 px-2 py-1 rounded-md border border-blue-200 cursor-move relative\"\n draggable\n onDragStart={handleChipDragStart(key)}\n onDragOver={handleChipDragOver(key)}\n onDrop={handleChipDrop(key)}\n title={labelFor(key)}\n >\n <span className=\"text-xs font-medium truncate max-w-[160px]\">{labelFor(key)}</span>\n <button\n className=\"text-blue-700 hover:text-blue-900\"\n onClick={() => onRemove(key)}\n aria-label={`Remove grouping ${labelFor(key)}`}\n >\n ×\n </button>\n {dragOverKey === key && (\n <span\n className=\"absolute top-0 bottom-0 w-0.5 bg-blue-600 dark:bg-blue-400 animate-pulse\"\n style={{ left: dragOverBefore ? 0 : undefined, right: dragOverBefore ? undefined : 0 }}\n aria-hidden=\"true\"\n />\n )}\n </div>\n ))}\n </div>\n </div>\n );\n};\n","import { memo } from \"react\";\nimport { ChevronDown, ChevronRight } from \"../icons\";\nimport { GridRow, KDGridProps } from \"../types\";\nimport { SELECT_COL_WIDTH } from \"../constants\";\n\ninterface GroupHeaderProps {\n row: GridRow & {\n _isGroupHeader?: boolean;\n _groupKey?: string;\n _groupCount?: number;\n };\n isExpanded: boolean;\n onToggle: (groupKey: string) => void;\n viewportWidth: number;\n selectable: boolean;\n rowHeight?: number;\n /**\n * Optional function to map a column key to its display label (header).\n * If not provided, the raw column key will be used as a fallback.\n */\n getHeaderLabel?: (columnKey: string) => string;\n /**\n * Optional function to map a column key and raw group value to a display label.\n * Useful to apply the column's formatter for group headers.\n */\n getValueLabel?: (columnKey: string, rawValue: any) => string;\n /**\n * Optional custom renderer for actions on grouped rows.\n */\n renderGroupActions?: KDGridProps[\"renderGroupActions\"];\n}\n\nexport const GroupHeader = memo(\n ({\n row,\n isExpanded,\n onToggle,\n viewportWidth,\n selectable,\n rowHeight = 40,\n getHeaderLabel,\n getValueLabel,\n renderGroupActions,\n }: GroupHeaderProps) => {\n const handleToggle = () => {\n if (row._groupKey) {\n onToggle(row._groupKey);\n }\n };\n\n return (\n <div\n className=\"flex items-center bg-blue-50 dark:bg-blue-900/20 border-b border-gray-200 dark:border-gray-800 hover:bg-blue-100/70 cursor-pointer sticky left-0 z-20 overflow-hidden\"\n style={{\n minWidth: `${viewportWidth + (selectable ? SELECT_COL_WIDTH : 0)}px`,\n height: `${rowHeight}px`,\n }}\n onClick={handleToggle}\n role=\"button\"\n tabIndex={0}\n aria-expanded={isExpanded}\n onKeyDown={(e) => {\n if (e.key === \"Enter\" || e.key === \" \") {\n e.preventDefault();\n handleToggle();\n }\n }}\n >\n {selectable && (\n <div className=\"w-12 flex items-center justify-center\">\n {/* Empty space for checkbox column */}\n </div>\n )}\n\n <div className=\"flex items-center px-4 py-2 flex-1\">\n <div\n className=\"flex items-center mr-3\"\n style={{\n paddingLeft: `${(row as any)._groupLevel ? ((row as any)._groupLevel as number) * 16 : 0}px`,\n }}\n >\n {isExpanded ? (\n <ChevronDown className=\"w-4 h-4 text-gray-600\" />\n ) : (\n <ChevronRight className=\"w-4 h-4 text-gray-600\" />\n )}\n </div>\n\n <div className=\"flex items-center gap-2\">\n <span className=\"font-medium text-gray-900\">\n {(row as any)._groupColumnKey\n ? `${getHeaderLabel ? getHeaderLabel((row as any)._groupColumnKey) : (row as any)._groupColumnKey}: `\n : \"\"}\n {getValueLabel && (row as any)._groupColumnKey\n ? getValueLabel(\n (row as any)._groupColumnKey,\n (row as any)._groupValue,\n )\n : ((row as any)._groupValue ?? (row._groupKey || \"Unknown\"))}\n </span>\n <span className=\"text-sm text-gray-600 bg-gray-200/70 px-2 py-1 rounded-full\">\n {row._groupCount} {row._groupCount === 1 ? \"item\" : \"items\"}\n </span>\n </div>\n\n {renderGroupActions && (\n <div\n className=\"flex items-center px-4\"\n onClick={(e) => e.stopPropagation()}\n >\n {renderGroupActions({\n groupKey: row._groupKey || \"\",\n columnKey: (row as any)._groupColumnKey || \"\",\n groupValue: (row as any)._groupValue,\n rows: (row as any)._groupRows || [],\n count: row._groupCount || 0,\n level: (row as any)._groupLevel || 0,\n })}\n </div>\n )}\n </div>\n </div>\n );\n },\n);\n","import { Search, Database } from \"../icons\";\n\ninterface NoDataMessageProps {\n hasFilters?: boolean;\n hasData?: boolean;\n message?: string;\n}\n\nexport const NoDataMessage = ({\n hasFilters = false,\n hasData = true,\n message,\n}: NoDataMessageProps) => {\n const getMessage = () => {\n if (message) {\n return {\n title: message,\n description: \"\",\n icon: Database,\n };\n }\n\n if (!hasData) {\n return {\n title: \"No Data Available\",\n description: \"There is no data to display in this table.\",\n icon: Database,\n };\n }\n\n if (hasFilters) {\n return {\n title: \"No Results Found\",\n description:\n \"No data matches your current search criteria. Try adjusting your filters.\",\n icon: Search,\n };\n }\n\n return {\n title: \"No Data to Display\",\n description: \"There are no items to show at the moment.\",\n icon: Database,\n };\n };\n\n const { title, description, icon: Icon } = getMessage();\n\n return (\n <div className=\"flex flex-col items-center justify-center pt-16 pb-10 px-4 text-center\">\n <div className=\"w-16 h-16 bg-gray-100 dark:bg-gray-800 rounded-full flex items-center justify-center mb-4\">\n <Icon className=\"w-8 h-8 text-gray-400 dark:text-gray-500\" />\n </div>\n <h3 className=\"text-lg font-medium text-gray-900 dark:text-gray-100 mb-2\">\n {title}\n </h3>\n <p className=\"text-sm text-gray-500 dark:text-gray-400 max-w-md\">\n {description}\n </p>\n </div>\n );\n};\n","import { memo } from \"react\";\nimport {\n ChevronLeft,\n ChevronRight,\n ChevronsLeft,\n ChevronsRight,\n Loader2,\n Users,\n Eye,\n Database,\n} from \"../icons\";\nimport { PaginationConfig } from \"../types\";\n\ninterface PaginationControlsProps {\n paginationConfig: PaginationConfig;\n currentPage: number;\n isServerLoading: boolean;\n selectedRowsCount: number;\n totalDataLength: number;\n filteredDataLength?: number;\n paginationMode?: \"client\" | \"server\";\n onPageChange: (page: number, pageSize: number) => void;\n onPageSizeChange: (pageSize: number) => void;\n showNoDataMessage?: boolean;\n}\n\nconst PaginationControlsComponent = ({\n paginationConfig,\n currentPage,\n isServerLoading,\n selectedRowsCount,\n totalDataLength,\n filteredDataLength,\n paginationMode = \"client\",\n onPageChange,\n onPageSizeChange,\n}: PaginationControlsProps) => {\n // Helper function to get the effective total count\n const getEffectiveTotalCount = () => {\n if (paginationMode === \"server\") {\n return paginationConfig.totalRows || totalDataLength;\n }\n return filteredDataLength || totalDataLength;\n };\n\n // Helper function to get the current page range\n const getCurrentPageRange = () => {\n const effectiveTotal = paginationConfig.enabled\n ? paginationConfig.totalRows || totalDataLength\n : getEffectiveTotalCount();\n\n const start = paginationConfig.enabled\n ? Math.min(\n (currentPage - 1) * paginationConfig.pageSize + 1,\n effectiveTotal,\n )\n : 1;\n\n const end = paginationConfig.enabled\n ? Math.min(currentPage * paginationConfig.pageSize, effectiveTotal)\n : effectiveTotal;\n\n return { start, end, total: effectiveTotal };\n };\n\n const { start, end, total } = getCurrentPageRange();\n const isFiltered =\n paginationMode === \"client\" &&\n filteredDataLength &&\n filteredDataLength !== totalDataLength;\n\n return (\n <div className=\"px-3 sm:px-6 py-2 border-t border-gray-200 dark:border-gray-700 bg-linear-to-r from-white via-gray-50 to-white dark:from-gray-900 dark:via-gray-800 dark:to-gray-900\">\n <div className=\"flex flex-col xl:flex-row gap-4 xl:gap-6 xl:justify-between xl:items-center\">\n {/* Left Section: Stats and Page Size */}\n <div className=\"flex flex-col sm:flex-row gap-3 sm:gap-4 items-start sm:items-center\">\n {/* Stats Section */}\n <div className=\"flex flex-wrap items-center gap-2 sm:gap-3\">\n {/* Total Count Badge - Only when pagination is disabled */}\n {!paginationConfig.enabled && (\n <div className=\"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-semibold bg-linear-to-r from-blue-500 to-blue-600 text-white shadow-lg ring-2 ring-blue-500/20\">\n <Database className=\"w-3 h-3\" />\n <span className=\"font-bold\">\n {total.toLocaleString()} {total === 1 ? \"Record\" : \"Records\"}\n </span>\n {isFiltered && (\n <span className=\"text-blue-100 font-normal\">\n (of {totalDataLength.toLocaleString()})\n </span>\n )}\n </div>\n )}\n\n {/* Selected Count Badge */}\n {selectedRowsCount > 0 && (\n <div className=\"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-semibold bg-linear-to-r from-primary to-primary text-white shadow-lg ring-2 ring-primary/20\">\n <Users className=\"w-3 h-3\" />\n <span>{selectedRowsCount.toLocaleString()} selected</span>\n </div>\n )}\n\n {/* Filtered Indicator */}\n {isFiltered && (\n <div className=\"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium bg-linear-to-r from-warning/10 to-warning/5 text-warning border border-warning/20\">\n <Eye className=\"w-3 h-3\" />\n <span>Filtered</span>\n </div>\n )}\n\n {/* Page Range Info (Desktop) */}\n {paginationConfig.enabled && (\n <div className=\"hidden sm:block text-sm text-gray-600 dark:text-gray-400 font-medium\">\n <span className=\"inline-flex items-center gap-1\">\n <span>Showing</span>\n <span className=\"px-2 py-0.5 bg-gray-100 dark:bg-gray-700 rounded-md font-bold text-gray-900 dark:text-gray-100\">\n {start.toLocaleString()}\n </span>\n <span>-</span>\n <span className=\"px-2 py-0.5 bg-gray-100 dark:bg-gray-700 rounded-md font-bold text-gray-900 dark:text-gray-100\">\n {end.toLocaleString()}\n </span>\n <span>of {total.toLocaleString()}</span>\n </span>\n </div>\n )}\n </div>\n\n {/* Page Size Selector */}\n {paginationConfig.enabled &&\n paginationConfig.showPageSizeSelector && (\n <div className=\"flex items-center gap-2\">\n <span className=\"text-sm font-medium text-gray-700 dark:text-gray-300 whitespace-nowrap\">\n Rows per page:\n </span>\n <select\n value={paginationConfig.pageSize}\n onChange={(e) => onPageSizeChange(Number(e.target.value))}\n className=\"border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 rounded-xl px-3 py-1 text-sm font-medium focus:ring-2 focus:ring-primary focus:border-primary disabled:opacity-50 disabled:cursor-not-allowed shadow-sm transition-all duration-200 hover:border-gray-400 dark:hover:border-gray-500\"\n disabled={isServerLoading}\n >\n {paginationConfig.pageSizeOptions?.map((size) => (\n <option key={size} value={size}>\n {size}\n </option>\n ))}\n </select>\n </div>\n )}\n </div>\n\n {/* Right Section: Pagination Controls */}\n {paginationConfig.enabled && (\n <div className=\"flex flex-col sm:flex-row items-start sm:items-center gap-3 sm:gap-4\">\n {/* Loading Indicator */}\n {isServerLoading && (\n <div className=\"flex items-center gap-2 px-3 py-1.5 bg-blue-50 dark:bg-blue-900/20 rounded-full border border-blue-200 dark:border-blue-800\">\n <Loader2 className=\"w-4 h-4 animate-spin text-primary\" />\n <span className=\"text-sm font-medium text-primary\">\n Loading...\n </span>\n </div>\n )}\n\n {/* Mobile Page Info */}\n <div className=\"sm:hidden text-sm text-gray-600 dark:text-gray-400 font-medium\">\n <div className=\"flex flex-col gap-1\">\n <span className=\"inline-flex items-center gap-1\">\n <span>Page</span>\n <span className=\"px-2 py-0.5 bg-gray-100 dark:bg-gray-700 rounded-md font-bold text-gray-900 dark:text-gray-100\">\n {currentPage.toLocaleString()}\n </span>\n <span>of</span>\n <span className=\"px-2 py-0.5 bg-gray-100 dark:bg-gray-700 rounded-md font-bold text-gray-900 dark:text-gray-100\">\n {paginationConfig.totalPages.toLocaleString()}\n </span>\n </span>\n <span className=\"text-xs text-gray-500 dark:text-gray-500\">\n {start.toLocaleString()} - {end.toLocaleString()} of{\" \"}\n {total.toLocaleString()}\n </span>\n </div>\n </div>\n\n {/* Pagination Navigation */}\n <div className=\"flex items-center gap-1 sm:gap-2\">\n {/* First Page Button */}\n <button\n onClick={() => onPageChange(1, paginationConfig.pageSize)}\n disabled={currentPage === 1 || isServerLoading}\n className=\"inline-flex items-center justify-center w-8 h-8 rounded-full border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer text-gray-600 dark:text-gray-300 hover:text-gray-900 dark:hover:text-gray-100 transition-all duration-200 hover:border-gray-400 dark:hover:border-gray-500 hover:shadow-md focus:ring-2 focus:ring-primary/20 focus:border-primary\"\n title=\"First page\"\n aria-label=\"Go to first page\"\n >\n <ChevronsLeft className=\"w-3.5 h-3.5\" />\n </button>\n\n {/* Previous Page Button */}\n <button\n onClick={() =>\n onPageChange(currentPage - 1, paginationConfig.pageSize)\n }\n disabled={currentPage === 1 || isServerLoading}\n className=\"inline-flex items-center justify-center w-8 h-8 rounded-full border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer text-gray-600 dark:text-gray-300 hover:text-gray-900 dark:hover:text-gray-100 transition-all duration-200 hover:border-gray-400 dark:hover:border-gray-500 hover:shadow-md focus:ring-2 focus:ring-primary/20 focus:border-primary\"\n title=\"Previous page\"\n aria-label=\"Go to previous page\"\n >\n <ChevronLeft className=\"w-3.5 h-3.5\" />\n </button>\n\n {/* Mobile Page Selector */}\n <div className=\"sm:hidden\">\n <select\n value={currentPage}\n onChange={(e) =>\n onPageChange(\n Number(e.target.value),\n paginationConfig.pageSize,\n )\n }\n className=\"border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 rounded-xl px-3 py-2 text-sm font-medium focus:ring-2 focus:ring-primary focus:border-primary disabled:opacity-50 disabled:cursor-not-allowed shadow-sm min-w-[80px]\"\n disabled={isServerLoading}\n aria-label=\"Select page\"\n >\n {Array.from(\n { length: paginationConfig.totalPages },\n (_, i) => i + 1,\n ).map((page) => (\n <option key={page} value={page}>\n {page}\n </option>\n ))}\n </select>\n </div>\n\n {/* Desktop Page Numbers */}\n <div className=\"hidden sm:flex items-center gap-1 mx-2\">\n {(() => {\n const pages = [];\n const totalPages = paginationConfig.totalPages;\n const current = currentPage;\n const maxVisible =\n typeof window !== \"undefined\" && window.innerWidth >= 768\n ? 7\n : 5;\n\n if (totalPages <= maxVisible) {\n for (let i = 1; i <= totalPages; i++) {\n pages.push(i);\n }\n } else {\n const delta = Math.floor(maxVisible / 2) - 1;\n if (current <= delta + 1) {\n for (let i = 1; i <= maxVisible - 2; i++) pages.push(i);\n pages.push(\"ellipsis1\");\n pages.push(totalPages);\n } else if (current >= totalPages - delta) {\n pages.push(1);\n pages.push(\"ellipsis1\");\n for (\n let i = totalPages - (maxVisible - 3);\n i <= totalPages;\n i++\n )\n pages.push(i);\n } else {\n pages.push(1);\n pages.push(\"ellipsis1\");\n for (let i = current - delta; i <= current + delta; i++)\n pages.push(i);\n pages.push(\"ellipsis2\");\n pages.push(totalPages);\n }\n }\n\n return pages.map((page) => {\n if (typeof page === \"string\") {\n return (\n <div\n key={page}\n className=\"flex items-center justify-center w-8 h-8 text-gray-400 dark:text-gray-500 select-none\"\n aria-hidden=\"true\"\n >\n <span className=\"text-lg leading-none\">⋯</span>\n </div>\n );\n }\n\n const isActive = page === current;\n return (\n <button\n key={page}\n onClick={() =>\n onPageChange(page, paginationConfig.pageSize)\n }\n disabled={isServerLoading}\n className={`inline-flex items-center justify-center w-8 h-8 rounded-full text-sm font-semibold transition-all duration-200 focus:ring-2 focus:ring-primary/20 focus:outline-none cursor-pointer ${\n isActive\n ? \"bg-linear-to-r from-primary to-primary text-white shadow-lg ring-2 ring-primary/20 transform scale-105 z-10 relative\"\n : \"border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 hover:border-gray-400 dark:hover:border-gray-500 hover:shadow-md disabled:opacity-40 disabled:cursor-not-allowed\"\n }`}\n aria-label={`Go to page ${page}`}\n aria-current={isActive ? \"page\" : undefined}\n >\n {page}\n </button>\n );\n });\n })()}\n </div>\n\n {/* Next Page Button */}\n <button\n onClick={() =>\n onPageChange(currentPage + 1, paginationConfig.pageSize)\n }\n disabled={\n currentPage === paginationConfig.totalPages || isServerLoading\n }\n className=\"inline-flex items-center justify-center w-8 h-8 rounded-full border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer text-gray-600 dark:text-gray-300 hover:text-gray-900 dark:hover:text-gray-100 transition-all duration-200 hover:border-gray-400 dark:hover:border-gray-500 hover:shadow-md focus:ring-2 focus:ring-primary/20 focus:border-primary\"\n title=\"Next page\"\n aria-label=\"Go to next page\"\n >\n <ChevronRight className=\"w-3.5 h-3.5\" />\n </button>\n\n {/* Last Page Button */}\n <button\n onClick={() =>\n onPageChange(\n paginationConfig.totalPages,\n paginationConfig.pageSize,\n )\n }\n disabled={\n currentPage === paginationConfig.totalPages || isServerLoading\n }\n className=\"inline-flex items-center justify-center w-8 h-8 rounded-full border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer text-gray-600 dark:text-gray-300 hover:text-gray-900 dark:hover:text-gray-100 transition-all duration-200 hover:border-gray-400 dark:hover:border-gray-500 hover:shadow-md focus:ring-2 focus:ring-primary/20 focus:border-primary\"\n title=\"Last page\"\n aria-label=\"Go to last page\"\n >\n <ChevronsRight className=\"w-3.5 h-3.5\" />\n </button>\n </div>\n </div>\n )}\n </div>\n </div>\n );\n};\n\nPaginationControlsComponent.displayName = \"PaginationControls\";\nexport const PaginationControls = /*#__PURE__*/ memo(\n PaginationControlsComponent,\n);\n","import { useState, useRef, useEffect, ChangeEvent } from \"react\";\nimport { ChevronDown, Check } from \"../icons\";\n\ninterface Option {\n label: string;\n value: string;\n}\n\ninterface CustomSelectProps {\n options: Option[];\n value?: string;\n placeholder?: string;\n onChange: (value: string) => void;\n searchable?: boolean;\n className?: string;\n}\n\nexport const CustomSelect = ({\n options,\n value,\n placeholder = \"Select an option...\",\n onChange,\n searchable = true,\n className = \"\",\n}: CustomSelectProps) => {\n const [isOpen, setIsOpen] = useState(false);\n const [searchTerm, setSearchTerm] = useState(\"\");\n const [highlightedIndex, setHighlightedIndex] = useState(-1);\n\n const containerRef = useRef<HTMLDivElement>(null);\n const inputRef = useRef<HTMLInputElement>(null);\n const listRef = useRef<HTMLUListElement>(null);\n\n const selectedOption = options.find((option) => option.value === value);\n\n const filteredOptions = searchable\n ? options.filter((option) =>\n option.label?.toLowerCase()?.includes(searchTerm?.toLowerCase()),\n )\n : options;\n\n // Close dropdown when clicking outside\n useEffect(() => {\n const handleClickOutside = (event: MouseEvent) => {\n if (\n containerRef.current &&\n !containerRef.current.contains(event.target as Node)\n ) {\n setIsOpen(false);\n setSearchTerm(\"\");\n setHighlightedIndex(-1);\n }\n };\n\n document.addEventListener(\"mousedown\", handleClickOutside);\n return () => document.removeEventListener(\"mousedown\", handleClickOutside);\n }, []);\n\n // Handle keyboard navigation\n useEffect(() => {\n const handleKeyDown = (event: KeyboardEvent) => {\n if (!isOpen) return;\n\n switch (event.key) {\n case \"ArrowDown\":\n event.preventDefault();\n setHighlightedIndex((prev) =>\n prev < filteredOptions.length - 1 ? prev + 1 : 0,\n );\n break;\n case \"ArrowUp\":\n event.preventDefault();\n setHighlightedIndex((prev) =>\n prev > 0 ? prev - 1 : filteredOptions.length - 1,\n );\n break;\n case \"Enter\":\n event.preventDefault();\n if (highlightedIndex >= 0 && filteredOptions[highlightedIndex]) {\n handleSelect(filteredOptions[highlightedIndex].value);\n }\n break;\n case \"Escape\":\n setIsOpen(false);\n setSearchTerm(\"\");\n setHighlightedIndex(-1);\n break;\n }\n };\n\n if (isOpen) {\n document.addEventListener(\"keydown\", handleKeyDown);\n return () => document.removeEventListener(\"keydown\", handleKeyDown);\n }\n }, [isOpen, highlightedIndex, filteredOptions]);\n\n // Scroll highlighted option into view\n useEffect(() => {\n if (highlightedIndex >= 0 && listRef.current) {\n const highlightedElement = listRef.current.children[\n highlightedIndex\n ] as HTMLElement;\n if (highlightedElement) {\n highlightedElement.scrollIntoView({\n block: \"nearest\",\n behavior: \"smooth\",\n });\n }\n }\n }, [highlightedIndex]);\n\n const handleSelect = (optionValue: string) => {\n onChange(optionValue);\n setIsOpen(false);\n setSearchTerm(\"\");\n setHighlightedIndex(-1);\n };\n\n const handleInputClick = () => {\n setIsOpen(!isOpen);\n if (searchable && !isOpen) {\n setTimeout(() => inputRef.current?.focus(), 0);\n }\n };\n\n const handleInputChange = (e: ChangeEvent<HTMLInputElement>) => {\n setSearchTerm(e.target.value);\n setHighlightedIndex(-1);\n if (!isOpen) setIsOpen(true);\n };\n\n return (\n <div className={`relative ${className}`} ref={containerRef}>\n <div\n className={`relative w-full cursor-pointer border border-gray-300 rounded-lg bg-white transition-all duration-200 ${\n isOpen\n ? \"ring-2 ring-blue-500 border-blue-500\"\n : \"hover:border-gray-400 focus-within:ring-2 focus-within:ring-blue-500 focus-within:border-blue-500\"\n }`}\n onClick={handleInputClick}\n >\n <div className=\"flex items-center justify-between px-3 py-2.5\">\n {searchable && isOpen ? (\n <input\n ref={inputRef}\n type=\"text\"\n className=\"flex-1 outline-none text-sm bg-transparent\"\n placeholder={`Search ${placeholder?.toLowerCase()}...`}\n value={searchTerm}\n onChange={handleInputChange}\n onClick={(e) => e.stopPropagation()}\n />\n ) : (\n <span\n className={`flex-1 text-sm truncate ${\n selectedOption ? \"text-gray-900\" : \"text-gray-500\"\n }`}\n >\n {selectedOption ? selectedOption.label : placeholder}\n </span>\n )}\n\n <ChevronDown\n className={`w-4 h-4 text-gray-400 transition-transform duration-200 ${\n isOpen ? \"rotate-180\" : \"\"\n }`}\n />\n </div>\n </div>\n\n {/* Dropdown List */}\n {isOpen && (\n <div className=\"absolute top-full left-0 right-0 mt-1 bg-white border border-gray-200 rounded-lg shadow-lg z-99999 max-h-80 overflow-hidden\">\n {filteredOptions.length > 0 ? (\n <ul ref={listRef} className=\"py-1 overflow-y-auto max-h-80\">\n {filteredOptions.map((option, index) => (\n <li\n key={option.value}\n className={`px-3 py-2 text-sm cursor-pointer flex items-center justify-between transition-colors ${\n index === highlightedIndex\n ? \"bg-blue-50 text-blue-700\"\n : \"text-gray-700 hover:bg-gray-50\"\n }`}\n onClick={() => handleSelect(option.value)}\n onMouseEnter={() => setHighlightedIndex(index)}\n >\n <span className=\"truncate\">{option.label}</span>\n {selectedOption?.value === option.value && (\n <Check className=\"w-4 h-4 text-blue-600 shrink-0 ml-2\" />\n )}\n </li>\n ))}\n </ul>\n ) : (\n <div className=\"px-3 py-2 text-sm text-gray-500 text-center\">\n No options found\n </div>\n )}\n </div>\n )}\n </div>\n );\n};\n","import { useState, useEffect } from \"react\";\nimport { X, Search } from \"../icons\";\nimport { CustomSelect } from \"./CustomSelect\";\nimport { DatePicker } from \"./ui/DatePicker\";\nimport { toYMD, fromYMD, toDMY } from \"../utils/dateUtils\";\n\ninterface ColumnFilterSelectorProps {\n columns: Array<{\n key: string;\n header: string;\n filterable?: {\n type?: string;\n options?: Array<{ label: string; value: string | number }>;\n placeholder?: string;\n };\n }>;\n columnFilters: Record<string, any>;\n onColumnFilter?: (columnKey: string, filter: any) => void;\n}\n\nexport const ColumnFilterSelector = ({\n columns,\n columnFilters,\n onColumnFilter,\n}: ColumnFilterSelectorProps) => {\n // Filter out columns that don't have filterable property\n const filterableColumns = columns.filter((col) => col.filterable);\n\n const [selectedColumn, setSelectedColumn] = useState<string>(\n filterableColumns.length > 0 ? filterableColumns[0].key : \"\",\n );\n // Multiselect search text (shared; reset on column change)\n const [multiSearch, setMultiSearch] = useState(\"\");\n const handleColumnSelect = (columnKey: string) => {\n setSelectedColumn(columnKey);\n };\n\n const handleActiveFilterClick = (columnKey: string) => {\n setSelectedColumn(columnKey);\n // Optionally, could add focus management here if the select is focusable via ref\n };\n\n // Convert columns to options for CustomSelect\n const columnOptions = filterableColumns.map((col) => ({\n label: col.header,\n value: col.key,\n }));\n\n const selectedColumnData = filterableColumns.find(\n (col) => col.key === selectedColumn,\n );\n\n // Reset multiselect search whenever the selected column changes\n useEffect(() => {\n setMultiSearch(\"\");\n }, [selectedColumn]);\n\n const renderFilterInput = () => {\n if (!selectedColumnData) return null;\n\n const filterType = selectedColumnData.filterable?.type || \"text\";\n const currentFilter = columnFilters[selectedColumn];\n\n if (\n filterType === \"multiselect\" &&\n selectedColumnData.filterable?.options\n ) {\n const lowered = multiSearch.toLowerCase();\n const filteredOptions = lowered\n ? selectedColumnData.filterable.options.filter(\n (opt) =>\n opt.label.toLowerCase().includes(lowered) ||\n String(opt.value).toLowerCase().includes(lowered),\n )\n : selectedColumnData.filterable.options;\n return (\n <div className=\"mt-3\">\n <label className=\"text-sm font-medium text-gray-700 mb-2 block\">\n Filter by {selectedColumnData.header}\n </label>\n <div className=\"relative mb-2\">\n <Search className=\"w-4 h-4 text-gray-400 absolute left-2 top-1/2 -translate-y-1/2\" />\n <input\n type=\"text\"\n value={multiSearch}\n onChange={(e) => setMultiSearch(e.target.value)}\n placeholder=\"Search options...\"\n className=\"w-full pl-8 pr-2 py-1.5 border border-gray-300 rounded-md text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500\"\n />\n {multiSearch && (\n <button\n type=\"button\"\n onClick={() => setMultiSearch(\"\")}\n className=\"absolute right-2 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600\"\n title=\"Clear search\"\n >\n <X className=\"w-3 h-3\" />\n </button>\n )}\n </div>\n <div className=\"max-h-32 overflow-y-auto border border-gray-300 rounded-md p-2 bg-white\">\n {filteredOptions.length === 0 && (\n <div className=\"text-xs text-gray-500 px-1 py-1\">No matches</div>\n )}\n {filteredOptions.map((option) => {\n const selectedValues = currentFilter?.value || [];\n const isSelected =\n Array.isArray(selectedValues) &&\n selectedValues.includes(option.value);\n return (\n <label\n key={option.value}\n className=\"flex items-center gap-2 py-1 hover:bg-gray-50 cursor-pointer\"\n >\n <input\n type=\"checkbox\"\n className=\"rounded border-gray-300 text-blue-600 focus:ring-blue-500\"\n checked={isSelected}\n onChange={(e) => {\n const currentValues = currentFilter?.value || [];\n let newValues;\n if (e.target.checked) {\n newValues = [...currentValues, option.value];\n } else {\n newValues = currentValues.filter(\n (v: any) => v !== option.value,\n );\n }\n if (newValues.length > 0) {\n onColumnFilter?.(selectedColumn, {\n type: \"multiselect\",\n value: newValues,\n operator: \"in\",\n });\n } else {\n onColumnFilter?.(selectedColumn, null);\n }\n }}\n />\n <span className=\"text-sm\">{option.label}</span>\n </label>\n );\n })}\n </div>\n </div>\n );\n }\n\n if (filterType === \"select\" && selectedColumnData.filterable?.options) {\n const selectOptions = [\n { label: `All ${selectedColumnData.header}`, value: \"\" },\n ...selectedColumnData.filterable.options.map((opt) => ({\n label: opt.label,\n value: String(opt.value),\n })),\n ];\n\n return (\n <div className=\"mt-3\">\n <label className=\"text-sm font-medium text-gray-700 mb-2 block\">\n Filter by {selectedColumnData.header}\n </label>\n <CustomSelect\n options={selectOptions}\n value={currentFilter?.value || \"\"}\n placeholder={`Select ${selectedColumnData.header.toLowerCase()}...`}\n onChange={(value) => {\n if (value) {\n onColumnFilter?.(selectedColumn, {\n type: \"select\",\n value: value,\n operator: \"between\",\n });\n } else {\n onColumnFilter?.(selectedColumn, null);\n }\n }}\n searchable={true}\n />\n </div>\n );\n }\n\n if (filterType === \"date\") {\n const parseInput = (val: any) => {\n if (!val) return null;\n if (val instanceof Date && !isNaN(val.getTime())) return val;\n // Accept both stored yyyy-MM-dd and other ISO/date strings\n const direct = fromYMD(String(val));\n if (!isNaN(direct.getTime())) return direct;\n const asDate = new Date(val);\n return isNaN(asDate.getTime()) ? null : asDate;\n };\n\n const primaryDate = parseInput(currentFilter?.value);\n const secondDate = parseInput(currentFilter?.secondValue);\n const effectiveOperator = currentFilter?.operator || \"between\";\n\n return (\n <div className=\"mt-3\">\n <label className=\"text-sm font-medium text-gray-700 mb-2 block\">\n Filter by {selectedColumnData.header}\n </label>\n <div className=\"mb-3\">\n <CustomSelect\n key={`date-operator-${selectedColumn}-${effectiveOperator}`}\n options={[\n { label: \"Between Dates\", value: \"between\" },\n { label: \"On Date\", value: \"equals\" },\n ]}\n value={effectiveOperator}\n placeholder=\"Select date filter...\"\n onChange={(operator) => {\n onColumnFilter?.(selectedColumn, {\n type: \"date\",\n value: currentFilter?.value || \"\",\n operator: operator as any,\n secondValue: currentFilter?.secondValue || \"\",\n });\n }}\n searchable={false}\n />\n </div>\n <div className=\"flex items-end gap-2\">\n <div className=\"flex-1 min-w-37.5\">\n <DatePicker\n name=\"column_filter_start\"\n label={effectiveOperator === \"between\" ? \"Start Date\" : \"Date\"}\n value={primaryDate ? toYMD(primaryDate) : null}\n onChange={(newValue) => {\n if (newValue) {\n const stored = toYMD(fromYMD(newValue));\n onColumnFilter?.(selectedColumn, {\n type: \"date\",\n value: stored,\n operator: effectiveOperator,\n secondValue: currentFilter?.secondValue || null,\n });\n } else {\n onColumnFilter?.(selectedColumn, null);\n }\n }}\n className=\"w-full\"\n />\n </div>\n {effectiveOperator === \"between\" && (\n <div className=\"flex-1 min-w-37.5\">\n <DatePicker\n name=\"column_filter_end\"\n label=\"End Date\"\n value={secondDate ? toYMD(secondDate) : null}\n onChange={(newValue) => {\n if (newValue && currentFilter) {\n const stored = toYMD(fromYMD(newValue));\n onColumnFilter?.(selectedColumn, {\n ...currentFilter,\n secondValue: stored,\n });\n }\n }}\n className=\"w-full\"\n />\n </div>\n )}\n </div>\n </div>\n );\n }\n\n // Default text input\n return (\n <div className=\"mt-3\">\n <label className=\"text-sm font-medium text-gray-700 mb-2 block\">\n Filter by {selectedColumnData.header}\n </label>\n <>\n <input\n type=\"text\"\n placeholder={\n selectedColumnData.filterable?.placeholder ||\n `Filter ${selectedColumnData.header.toLowerCase()}...`\n }\n className=\"w-full px-3 py-2.5 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-200\"\n value={currentFilter?.value || \"\"}\n onChange={(e) => {\n if (e.target.value) {\n onColumnFilter?.(selectedColumn, {\n type: \"text\",\n value: e.target.value,\n operator: \"contains\",\n });\n } else {\n onColumnFilter?.(selectedColumn, null);\n }\n }}\n />\n\n {/* Filter Operator Selector for text filters */}\n {currentFilter && (\n <div className=\"mt-2\">\n <CustomSelect\n options={[\n { label: \"Contains\", value: \"contains\" },\n { label: \"Equals\", value: \"equals\" },\n { label: \"Starts with\", value: \"startsWith\" },\n { label: \"Ends with\", value: \"endsWith\" },\n ]}\n value={currentFilter?.operator || \"contains\"}\n placeholder=\"Select operator...\"\n onChange={(operator) => {\n if (currentFilter) {\n onColumnFilter?.(selectedColumn, {\n ...currentFilter,\n operator: operator as any,\n });\n }\n }}\n searchable={false}\n />\n </div>\n )}\n </>\n </div>\n );\n };\n\n return (\n <div className=\"space-y-4\">\n {/* Column Selection Dropdown */}\n <div>\n <label className=\"text-sm font-medium text-gray-700 mb-2 block\">\n Select Column to Filter\n </label>\n <CustomSelect\n options={columnOptions}\n value={selectedColumn}\n placeholder=\"Choose a column...\"\n onChange={handleColumnSelect}\n searchable={true}\n />\n </div>\n\n {/* Filter Input for Selected Column */}\n {selectedColumn && renderFilterInput()}\n\n {/* Active Filters Display */}\n {Object.keys(columnFilters).length > 0 && (\n <div className=\"mt-4\">\n <label className=\"text-sm font-medium text-gray-700 mb-2 block\">\n Active Filters\n </label>\n <div className=\"space-y-2\">\n {Object.entries(columnFilters).map(([columnKey, filter]) => {\n const column = filterableColumns.find(\n (col) => col.key === columnKey,\n );\n if (!column) return null;\n\n return (\n <div\n key={columnKey}\n className=\"flex items-center justify-between bg-blue-50 border border-blue-200 rounded-md px-3 py-2 cursor-pointer hover:bg-blue-100\"\n role=\"button\"\n title={`Edit filter for ${column.header}`}\n onClick={() => handleActiveFilterClick(columnKey)}\n >\n <div className=\"flex-1\">\n <span className=\"text-sm font-medium text-blue-900\">\n {column.header}:\n </span>\n <span className=\"text-sm text-blue-700 ml-1\">\n {(() => {\n if (Array.isArray(filter.value)) {\n return `${filter.value.length} selected`;\n }\n\n // Handle date filters with operators\n if (filter.type === \"date\") {\n const formatDate = (dateValue: any) => {\n try {\n if (!dateValue) return \"\";\n if (\n dateValue instanceof Date &&\n !isNaN(dateValue.getTime())\n ) {\n return toDMY(dateValue);\n }\n if (typeof dateValue === \"string\") {\n const parsed = fromYMD(dateValue);\n if (!isNaN(parsed.getTime()))\n return toDMY(parsed);\n const asDate = new Date(dateValue);\n if (!isNaN(asDate.getTime()))\n return toDMY(asDate);\n }\n return String(dateValue);\n } catch {\n return String(dateValue ?? \"\");\n }\n };\n\n const operatorLabels: Record<string, string> = {\n equals: \"On\",\n gt: \"After\",\n gte: \"On or After\",\n lt: \"Before\",\n lte: \"On or Before\",\n between: \"Between\",\n };\n\n const operatorLabel =\n operatorLabels[filter.operator as string] || \"On\";\n\n if (\n filter.operator === \"between\" &&\n filter.secondValue\n ) {\n return `${operatorLabel} ${formatDate(\n filter.value,\n )} - ${formatDate(filter.secondValue)}`;\n }\n\n return `${operatorLabel} ${formatDate(filter.value)}`;\n }\n\n return filter.value;\n })()}\n </span>\n </div>\n <button\n onClick={(e) => {\n e.stopPropagation();\n onColumnFilter?.(columnKey, null);\n }}\n className=\"text-blue-400 hover:text-red-500 transition-colors\"\n title=\"Clear filter\"\n >\n <X className=\"w-4 h-4\" />\n </button>\n </div>\n );\n })}\n </div>\n </div>\n )}\n </div>\n );\n};\n","function hasWindow() {\n return typeof window !== 'undefined';\n}\nfunction getNodeName(node) {\n if (isNode(node)) {\n return (node.nodeName || '').toLowerCase();\n }\n // Mocked nodes in testing environments may not be instances of Node. By\n // returning `#document` an infinite loop won't occur.\n // https://github.com/floating-ui/floating-ui/issues/2317\n return '#document';\n}\nfunction getWindow(node) {\n var _node$ownerDocument;\n return (node == null || (_node$ownerDocument = node.ownerDocument) == null ? void 0 : _node$ownerDocument.defaultView) || window;\n}\nfunction getDocumentElement(node) {\n var _ref;\n return (_ref = (isNode(node) ? node.ownerDocument : node.document) || window.document) == null ? void 0 : _ref.documentElement;\n}\nfunction isNode(value) {\n if (!hasWindow()) {\n return false;\n }\n return value instanceof Node || value instanceof getWindow(value).Node;\n}\nfunction isElement(value) {\n if (!hasWindow()) {\n return false;\n }\n return value instanceof Element || value instanceof getWindow(value).Element;\n}\nfunction isHTMLElement(value) {\n if (!hasWindow()) {\n return false;\n }\n return value instanceof HTMLElement || value instanceof getWindow(value).HTMLElement;\n}\nfunction isShadowRoot(value) {\n if (!hasWindow() || typeof ShadowRoot === 'undefined') {\n return false;\n }\n return value instanceof ShadowRoot || value instanceof getWindow(value).ShadowRoot;\n}\nconst invalidOverflowDisplayValues = /*#__PURE__*/new Set(['inline', 'contents']);\nfunction isOverflowElement(element) {\n const {\n overflow,\n overflowX,\n overflowY,\n display\n } = getComputedStyle(element);\n return /auto|scroll|overlay|hidden|clip/.test(overflow + overflowY + overflowX) && !invalidOverflowDisplayValues.has(display);\n}\nconst tableElements = /*#__PURE__*/new Set(['table', 'td', 'th']);\nfunction isTableElement(element) {\n return tableElements.has(getNodeName(element));\n}\nconst topLayerSelectors = [':popover-open', ':modal'];\nfunction isTopLayer(element) {\n return topLayerSelectors.some(selector => {\n try {\n return element.matches(selector);\n } catch (_e) {\n return false;\n }\n });\n}\nconst transformProperties = ['transform', 'translate', 'scale', 'rotate', 'perspective'];\nconst willChangeValues = ['transform', 'translate', 'scale', 'rotate', 'perspective', 'filter'];\nconst containValues = ['paint', 'layout', 'strict', 'content'];\nfunction isContainingBlock(elementOrCss) {\n const webkit = isWebKit();\n const css = isElement(elementOrCss) ? getComputedStyle(elementOrCss) : elementOrCss;\n\n // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block\n // https://drafts.csswg.org/css-transforms-2/#individual-transforms\n return transformProperties.some(value => css[value] ? css[value] !== 'none' : false) || (css.containerType ? css.containerType !== 'normal' : false) || !webkit && (css.backdropFilter ? css.backdropFilter !== 'none' : false) || !webkit && (css.filter ? css.filter !== 'none' : false) || willChangeValues.some(value => (css.willChange || '').includes(value)) || containValues.some(value => (css.contain || '').includes(value));\n}\nfunction getContainingBlock(element) {\n let currentNode = getParentNode(element);\n while (isHTMLElement(currentNode) && !isLastTraversableNode(currentNode)) {\n if (isContainingBlock(currentNode)) {\n return currentNode;\n } else if (isTopLayer(currentNode)) {\n return null;\n }\n currentNode = getParentNode(currentNode);\n }\n return null;\n}\nfunction isWebKit() {\n if (typeof CSS === 'undefined' || !CSS.supports) return false;\n return CSS.supports('-webkit-backdrop-filter', 'none');\n}\nconst lastTraversableNodeNames = /*#__PURE__*/new Set(['html', 'body', '#document']);\nfunction isLastTraversableNode(node) {\n return lastTraversableNodeNames.has(getNodeName(node));\n}\nfunction getComputedStyle(element) {\n return getWindow(element).getComputedStyle(element);\n}\nfunction getNodeScroll(element) {\n if (isElement(element)) {\n return {\n scrollLeft: element.scrollLeft,\n scrollTop: element.scrollTop\n };\n }\n return {\n scrollLeft: element.scrollX,\n scrollTop: element.scrollY\n };\n}\nfunction getParentNode(node) {\n if (getNodeName(node) === 'html') {\n return node;\n }\n const result =\n // Step into the shadow DOM of the parent of a slotted node.\n node.assignedSlot ||\n // DOM Element detected.\n node.parentNode ||\n // ShadowRoot detected.\n isShadowRoot(node) && node.host ||\n // Fallback.\n getDocumentElement(node);\n return isShadowRoot(result) ? result.host : result;\n}\nfunction getNearestOverflowAncestor(node) {\n const parentNode = getParentNode(node);\n if (isLastTraversableNode(parentNode)) {\n return node.ownerDocument ? node.ownerDocument.body : node.body;\n }\n if (isHTMLElement(parentNode) && isOverflowElement(parentNode)) {\n return parentNode;\n }\n return getNearestOverflowAncestor(parentNode);\n}\nfunction getOverflowAncestors(node, list, traverseIframes) {\n var _node$ownerDocument2;\n if (list === void 0) {\n list = [];\n }\n if (traverseIframes === void 0) {\n traverseIframes = true;\n }\n const scrollableAncestor = getNearestOverflowAncestor(node);\n const isBody = scrollableAncestor === ((_node$ownerDocument2 = node.ownerDocument) == null ? void 0 : _node$ownerDocument2.body);\n const win = getWindow(scrollableAncestor);\n if (isBody) {\n const frameElement = getFrameElement(win);\n return list.concat(win, win.visualViewport || [], isOverflowElement(scrollableAncestor) ? scrollableAncestor : [], frameElement && traverseIframes ? getOverflowAncestors(frameElement) : []);\n }\n return list.concat(scrollableAncestor, getOverflowAncestors(scrollableAncestor, [], traverseIframes));\n}\nfunction getFrameElement(win) {\n return win.parent && Object.getPrototypeOf(win.parent) ? win.frameElement : null;\n}\n\nexport { getComputedStyle, getContainingBlock, getDocumentElement, getFrameElement, getNearestOverflowAncestor, getNodeName, getNodeScroll, getOverflowAncestors, getParentNode, getWindow, isContainingBlock, isElement, isHTMLElement, isLastTraversableNode, isNode, isOverflowElement, isShadowRoot, isTableElement, isTopLayer, isWebKit };\n","/**\n * Custom positioning reference element.\n * @see https://floating-ui.com/docs/virtual-elements\n */\n\nconst sides = ['top', 'right', 'bottom', 'left'];\nconst alignments = ['start', 'end'];\nconst placements = /*#__PURE__*/sides.reduce((acc, side) => acc.concat(side, side + \"-\" + alignments[0], side + \"-\" + alignments[1]), []);\nconst min = Math.min;\nconst max = Math.max;\nconst round = Math.round;\nconst floor = Math.floor;\nconst createCoords = v => ({\n x: v,\n y: v\n});\nconst oppositeSideMap = {\n left: 'right',\n right: 'left',\n bottom: 'top',\n top: 'bottom'\n};\nconst oppositeAlignmentMap = {\n start: 'end',\n end: 'start'\n};\nfunction clamp(start, value, end) {\n return max(start, min(value, end));\n}\nfunction evaluate(value, param) {\n return typeof value === 'function' ? value(param) : value;\n}\nfunction getSide(placement) {\n return placement.split('-')[0];\n}\nfunction getAlignment(placement) {\n return placement.split('-')[1];\n}\nfunction getOppositeAxis(axis) {\n return axis === 'x' ? 'y' : 'x';\n}\nfunction getAxisLength(axis) {\n return axis === 'y' ? 'height' : 'width';\n}\nconst yAxisSides = /*#__PURE__*/new Set(['top', 'bottom']);\nfunction getSideAxis(placement) {\n return yAxisSides.has(getSide(placement)) ? 'y' : 'x';\n}\nfunction getAlignmentAxis(placement) {\n return getOppositeAxis(getSideAxis(placement));\n}\nfunction getAlignmentSides(placement, rects, rtl) {\n if (rtl === void 0) {\n rtl = false;\n }\n const alignment = getAlignment(placement);\n const alignmentAxis = getAlignmentAxis(placement);\n const length = getAxisLength(alignmentAxis);\n let mainAlignmentSide = alignmentAxis === 'x' ? alignment === (rtl ? 'end' : 'start') ? 'right' : 'left' : alignment === 'start' ? 'bottom' : 'top';\n if (rects.reference[length] > rects.floating[length]) {\n mainAlignmentSide = getOppositePlacement(mainAlignmentSide);\n }\n return [mainAlignmentSide, getOppositePlacement(mainAlignmentSide)];\n}\nfunction getExpandedPlacements(placement) {\n const oppositePlacement = getOppositePlacement(placement);\n return [getOppositeAlignmentPlacement(placement), oppositePlacement, getOppositeAlignmentPlacement(oppositePlacement)];\n}\nfunction getOppositeAlignmentPlacement(placement) {\n return placement.replace(/start|end/g, alignment => oppositeAlignmentMap[alignment]);\n}\nconst lrPlacement = ['left', 'right'];\nconst rlPlacement = ['right', 'left'];\nconst tbPlacement = ['top', 'bottom'];\nconst btPlacement = ['bottom', 'top'];\nfunction getSideList(side, isStart, rtl) {\n switch (side) {\n case 'top':\n case 'bottom':\n if (rtl) return isStart ? rlPlacement : lrPlacement;\n return isStart ? lrPlacement : rlPlacement;\n case 'left':\n case 'right':\n return isStart ? tbPlacement : btPlacement;\n default:\n return [];\n }\n}\nfunction getOppositeAxisPlacements(placement, flipAlignment, direction, rtl) {\n const alignment = getAlignment(placement);\n let list = getSideList(getSide(placement), direction === 'start', rtl);\n if (alignment) {\n list = list.map(side => side + \"-\" + alignment);\n if (flipAlignment) {\n list = list.concat(list.map(getOppositeAlignmentPlacement));\n }\n }\n return list;\n}\nfunction getOppositePlacement(placement) {\n return placement.replace(/left|right|bottom|top/g, side => oppositeSideMap[side]);\n}\nfunction expandPaddingObject(padding) {\n return {\n top: 0,\n right: 0,\n bottom: 0,\n left: 0,\n ...padding\n };\n}\nfunction getPaddingObject(padding) {\n return typeof padding !== 'number' ? expandPaddingObject(padding) : {\n top: padding,\n right: padding,\n bottom: padding,\n left: padding\n };\n}\nfunction rectToClientRect(rect) {\n const {\n x,\n y,\n width,\n height\n } = rect;\n return {\n width,\n height,\n top: y,\n left: x,\n right: x + width,\n bottom: y + height,\n x,\n y\n };\n}\n\nexport { alignments, clamp, createCoords, evaluate, expandPaddingObject, floor, getAlignment, getAlignmentAxis, getAlignmentSides, getAxisLength, getExpandedPlacements, getOppositeAlignmentPlacement, getOppositeAxis, getOppositeAxisPlacements, getOppositePlacement, getPaddingObject, getSide, getSideAxis, max, min, placements, rectToClientRect, round, sides };\n","import { isShadowRoot, isHTMLElement } from '@floating-ui/utils/dom';\nimport * as React from 'react';\nimport { useLayoutEffect } from 'react';\nimport { floor } from '@floating-ui/utils';\nimport { tabbable } from 'tabbable';\n\n// Avoid Chrome DevTools blue warning.\nfunction getPlatform() {\n const uaData = navigator.userAgentData;\n if (uaData != null && uaData.platform) {\n return uaData.platform;\n }\n return navigator.platform;\n}\nfunction getUserAgent() {\n const uaData = navigator.userAgentData;\n if (uaData && Array.isArray(uaData.brands)) {\n return uaData.brands.map(_ref => {\n let {\n brand,\n version\n } = _ref;\n return brand + \"/\" + version;\n }).join(' ');\n }\n return navigator.userAgent;\n}\nfunction isSafari() {\n // Chrome DevTools does not complain about navigator.vendor\n return /apple/i.test(navigator.vendor);\n}\nfunction isAndroid() {\n const re = /android/i;\n return re.test(getPlatform()) || re.test(getUserAgent());\n}\nfunction isMac() {\n return getPlatform().toLowerCase().startsWith('mac') && !navigator.maxTouchPoints;\n}\nfunction isJSDOM() {\n return getUserAgent().includes('jsdom/');\n}\n\nconst FOCUSABLE_ATTRIBUTE = 'data-floating-ui-focusable';\nconst TYPEABLE_SELECTOR = \"input:not([type='hidden']):not([disabled]),\" + \"[contenteditable]:not([contenteditable='false']),textarea:not([disabled])\";\nconst ARROW_LEFT = 'ArrowLeft';\nconst ARROW_RIGHT = 'ArrowRight';\nconst ARROW_UP = 'ArrowUp';\nconst ARROW_DOWN = 'ArrowDown';\n\nfunction activeElement(doc) {\n let activeElement = doc.activeElement;\n while (((_activeElement = activeElement) == null || (_activeElement = _activeElement.shadowRoot) == null ? void 0 : _activeElement.activeElement) != null) {\n var _activeElement;\n activeElement = activeElement.shadowRoot.activeElement;\n }\n return activeElement;\n}\nfunction contains(parent, child) {\n if (!parent || !child) {\n return false;\n }\n const rootNode = child.getRootNode == null ? void 0 : child.getRootNode();\n\n // First, attempt with faster native method\n if (parent.contains(child)) {\n return true;\n }\n\n // then fallback to custom implementation with Shadow DOM support\n if (rootNode && isShadowRoot(rootNode)) {\n let next = child;\n while (next) {\n if (parent === next) {\n return true;\n }\n // @ts-ignore\n next = next.parentNode || next.host;\n }\n }\n\n // Give up, the result is false\n return false;\n}\nfunction getTarget(event) {\n if ('composedPath' in event) {\n return event.composedPath()[0];\n }\n\n // TS thinks `event` is of type never as it assumes all browsers support\n // `composedPath()`, but browsers without shadow DOM don't.\n return event.target;\n}\nfunction isEventTargetWithin(event, node) {\n if (node == null) {\n return false;\n }\n if ('composedPath' in event) {\n return event.composedPath().includes(node);\n }\n\n // TS thinks `event` is of type never as it assumes all browsers support composedPath, but browsers without shadow dom don't\n const e = event;\n return e.target != null && node.contains(e.target);\n}\nfunction isRootElement(element) {\n return element.matches('html,body');\n}\nfunction getDocument(node) {\n return (node == null ? void 0 : node.ownerDocument) || document;\n}\nfunction isTypeableElement(element) {\n return isHTMLElement(element) && element.matches(TYPEABLE_SELECTOR);\n}\nfunction isTypeableCombobox(element) {\n if (!element) return false;\n return element.getAttribute('role') === 'combobox' && isTypeableElement(element);\n}\nfunction matchesFocusVisible(element) {\n // We don't want to block focus from working with `visibleOnly`\n // (JSDOM doesn't match `:focus-visible` when the element has `:focus`)\n if (!element || isJSDOM()) return true;\n try {\n return element.matches(':focus-visible');\n } catch (_e) {\n return true;\n }\n}\nfunction getFloatingFocusElement(floatingElement) {\n if (!floatingElement) {\n return null;\n }\n // Try to find the element that has `{...getFloatingProps()}` spread on it.\n // This indicates the floating element is acting as a positioning wrapper, and\n // so focus should be managed on the child element with the event handlers and\n // aria props.\n return floatingElement.hasAttribute(FOCUSABLE_ATTRIBUTE) ? floatingElement : floatingElement.querySelector(\"[\" + FOCUSABLE_ATTRIBUTE + \"]\") || floatingElement;\n}\n\nfunction getNodeChildren(nodes, id, onlyOpenChildren) {\n if (onlyOpenChildren === void 0) {\n onlyOpenChildren = true;\n }\n const directChildren = nodes.filter(node => {\n var _node$context;\n return node.parentId === id && (!onlyOpenChildren || ((_node$context = node.context) == null ? void 0 : _node$context.open));\n });\n return directChildren.flatMap(child => [child, ...getNodeChildren(nodes, child.id, onlyOpenChildren)]);\n}\nfunction getDeepestNode(nodes, id) {\n let deepestNodeId;\n let maxDepth = -1;\n function findDeepest(nodeId, depth) {\n if (depth > maxDepth) {\n deepestNodeId = nodeId;\n maxDepth = depth;\n }\n const children = getNodeChildren(nodes, nodeId);\n children.forEach(child => {\n findDeepest(child.id, depth + 1);\n });\n }\n findDeepest(id, 0);\n return nodes.find(node => node.id === deepestNodeId);\n}\nfunction getNodeAncestors(nodes, id) {\n var _nodes$find;\n let allAncestors = [];\n let currentParentId = (_nodes$find = nodes.find(node => node.id === id)) == null ? void 0 : _nodes$find.parentId;\n while (currentParentId) {\n const currentNode = nodes.find(node => node.id === currentParentId);\n currentParentId = currentNode == null ? void 0 : currentNode.parentId;\n if (currentNode) {\n allAncestors = allAncestors.concat(currentNode);\n }\n }\n return allAncestors;\n}\n\nfunction stopEvent(event) {\n event.preventDefault();\n event.stopPropagation();\n}\nfunction isReactEvent(event) {\n return 'nativeEvent' in event;\n}\n\n// License: https://github.com/adobe/react-spectrum/blob/b35d5c02fe900badccd0cf1a8f23bb593419f238/packages/@react-aria/utils/src/isVirtualEvent.ts\nfunction isVirtualClick(event) {\n // FIXME: Firefox is now emitting a deprecation warning for `mozInputSource`.\n // Try to find a workaround for this. `react-aria` source still has the check.\n if (event.mozInputSource === 0 && event.isTrusted) {\n return true;\n }\n if (isAndroid() && event.pointerType) {\n return event.type === 'click' && event.buttons === 1;\n }\n return event.detail === 0 && !event.pointerType;\n}\nfunction isVirtualPointerEvent(event) {\n if (isJSDOM()) return false;\n return !isAndroid() && event.width === 0 && event.height === 0 || isAndroid() && event.width === 1 && event.height === 1 && event.pressure === 0 && event.detail === 0 && event.pointerType === 'mouse' ||\n // iOS VoiceOver returns 0.333• for width/height.\n event.width < 1 && event.height < 1 && event.pressure === 0 && event.detail === 0 && event.pointerType === 'touch';\n}\nfunction isMouseLikePointerType(pointerType, strict) {\n // On some Linux machines with Chromium, mouse inputs return a `pointerType`\n // of \"pen\": https://github.com/floating-ui/floating-ui/issues/2015\n const values = ['mouse', 'pen'];\n if (!strict) {\n values.push('', undefined);\n }\n return values.includes(pointerType);\n}\n\nvar isClient = typeof document !== 'undefined';\n\nvar noop = function noop() {};\nvar index = isClient ? useLayoutEffect : noop;\n\n// https://github.com/mui/material-ui/issues/41190#issuecomment-2040873379\nconst SafeReact = {\n ...React\n};\n\nfunction useLatestRef(value) {\n const ref = React.useRef(value);\n index(() => {\n ref.current = value;\n });\n return ref;\n}\nconst useInsertionEffect = SafeReact.useInsertionEffect;\nconst useSafeInsertionEffect = useInsertionEffect || (fn => fn());\nfunction useEffectEvent(callback) {\n const ref = React.useRef(() => {\n if (process.env.NODE_ENV !== \"production\") {\n throw new Error('Cannot call an event handler while rendering.');\n }\n });\n useSafeInsertionEffect(() => {\n ref.current = callback;\n });\n return React.useCallback(function () {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n return ref.current == null ? void 0 : ref.current(...args);\n }, []);\n}\n\nfunction isDifferentGridRow(index, cols, prevRow) {\n return Math.floor(index / cols) !== prevRow;\n}\nfunction isIndexOutOfListBounds(listRef, index) {\n return index < 0 || index >= listRef.current.length;\n}\nfunction getMinListIndex(listRef, disabledIndices) {\n return findNonDisabledListIndex(listRef, {\n disabledIndices\n });\n}\nfunction getMaxListIndex(listRef, disabledIndices) {\n return findNonDisabledListIndex(listRef, {\n decrement: true,\n startingIndex: listRef.current.length,\n disabledIndices\n });\n}\nfunction findNonDisabledListIndex(listRef, _temp) {\n let {\n startingIndex = -1,\n decrement = false,\n disabledIndices,\n amount = 1\n } = _temp === void 0 ? {} : _temp;\n let index = startingIndex;\n do {\n index += decrement ? -amount : amount;\n } while (index >= 0 && index <= listRef.current.length - 1 && isListIndexDisabled(listRef, index, disabledIndices));\n return index;\n}\nfunction getGridNavigatedIndex(listRef, _ref) {\n let {\n event,\n orientation,\n loop,\n rtl,\n cols,\n disabledIndices,\n minIndex,\n maxIndex,\n prevIndex,\n stopEvent: stop = false\n } = _ref;\n let nextIndex = prevIndex;\n if (event.key === ARROW_UP) {\n stop && stopEvent(event);\n if (prevIndex === -1) {\n nextIndex = maxIndex;\n } else {\n nextIndex = findNonDisabledListIndex(listRef, {\n startingIndex: nextIndex,\n amount: cols,\n decrement: true,\n disabledIndices\n });\n if (loop && (prevIndex - cols < minIndex || nextIndex < 0)) {\n const col = prevIndex % cols;\n const maxCol = maxIndex % cols;\n const offset = maxIndex - (maxCol - col);\n if (maxCol === col) {\n nextIndex = maxIndex;\n } else {\n nextIndex = maxCol > col ? offset : offset - cols;\n }\n }\n }\n if (isIndexOutOfListBounds(listRef, nextIndex)) {\n nextIndex = prevIndex;\n }\n }\n if (event.key === ARROW_DOWN) {\n stop && stopEvent(event);\n if (prevIndex === -1) {\n nextIndex = minIndex;\n } else {\n nextIndex = findNonDisabledListIndex(listRef, {\n startingIndex: prevIndex,\n amount: cols,\n disabledIndices\n });\n if (loop && prevIndex + cols > maxIndex) {\n nextIndex = findNonDisabledListIndex(listRef, {\n startingIndex: prevIndex % cols - cols,\n amount: cols,\n disabledIndices\n });\n }\n }\n if (isIndexOutOfListBounds(listRef, nextIndex)) {\n nextIndex = prevIndex;\n }\n }\n\n // Remains on the same row/column.\n if (orientation === 'both') {\n const prevRow = floor(prevIndex / cols);\n if (event.key === (rtl ? ARROW_LEFT : ARROW_RIGHT)) {\n stop && stopEvent(event);\n if (prevIndex % cols !== cols - 1) {\n nextIndex = findNonDisabledListIndex(listRef, {\n startingIndex: prevIndex,\n disabledIndices\n });\n if (loop && isDifferentGridRow(nextIndex, cols, prevRow)) {\n nextIndex = findNonDisabledListIndex(listRef, {\n startingIndex: prevIndex - prevIndex % cols - 1,\n disabledIndices\n });\n }\n } else if (loop) {\n nextIndex = findNonDisabledListIndex(listRef, {\n startingIndex: prevIndex - prevIndex % cols - 1,\n disabledIndices\n });\n }\n if (isDifferentGridRow(nextIndex, cols, prevRow)) {\n nextIndex = prevIndex;\n }\n }\n if (event.key === (rtl ? ARROW_RIGHT : ARROW_LEFT)) {\n stop && stopEvent(event);\n if (prevIndex % cols !== 0) {\n nextIndex = findNonDisabledListIndex(listRef, {\n startingIndex: prevIndex,\n decrement: true,\n disabledIndices\n });\n if (loop && isDifferentGridRow(nextIndex, cols, prevRow)) {\n nextIndex = findNonDisabledListIndex(listRef, {\n startingIndex: prevIndex + (cols - prevIndex % cols),\n decrement: true,\n disabledIndices\n });\n }\n } else if (loop) {\n nextIndex = findNonDisabledListIndex(listRef, {\n startingIndex: prevIndex + (cols - prevIndex % cols),\n decrement: true,\n disabledIndices\n });\n }\n if (isDifferentGridRow(nextIndex, cols, prevRow)) {\n nextIndex = prevIndex;\n }\n }\n const lastRow = floor(maxIndex / cols) === prevRow;\n if (isIndexOutOfListBounds(listRef, nextIndex)) {\n if (loop && lastRow) {\n nextIndex = event.key === (rtl ? ARROW_RIGHT : ARROW_LEFT) ? maxIndex : findNonDisabledListIndex(listRef, {\n startingIndex: prevIndex - prevIndex % cols - 1,\n disabledIndices\n });\n } else {\n nextIndex = prevIndex;\n }\n }\n }\n return nextIndex;\n}\n\n/** For each cell index, gets the item index that occupies that cell */\nfunction createGridCellMap(sizes, cols, dense) {\n const cellMap = [];\n let startIndex = 0;\n sizes.forEach((_ref2, index) => {\n let {\n width,\n height\n } = _ref2;\n if (width > cols) {\n if (process.env.NODE_ENV !== \"production\") {\n throw new Error(\"[Floating UI]: Invalid grid - item width at index \" + index + \" is greater than grid columns\");\n }\n }\n let itemPlaced = false;\n if (dense) {\n startIndex = 0;\n }\n while (!itemPlaced) {\n const targetCells = [];\n for (let i = 0; i < width; i++) {\n for (let j = 0; j < height; j++) {\n targetCells.push(startIndex + i + j * cols);\n }\n }\n if (startIndex % cols + width <= cols && targetCells.every(cell => cellMap[cell] == null)) {\n targetCells.forEach(cell => {\n cellMap[cell] = index;\n });\n itemPlaced = true;\n } else {\n startIndex++;\n }\n }\n });\n\n // convert into a non-sparse array\n return [...cellMap];\n}\n\n/** Gets cell index of an item's corner or -1 when index is -1. */\nfunction getGridCellIndexOfCorner(index, sizes, cellMap, cols, corner) {\n if (index === -1) return -1;\n const firstCellIndex = cellMap.indexOf(index);\n const sizeItem = sizes[index];\n switch (corner) {\n case 'tl':\n return firstCellIndex;\n case 'tr':\n if (!sizeItem) {\n return firstCellIndex;\n }\n return firstCellIndex + sizeItem.width - 1;\n case 'bl':\n if (!sizeItem) {\n return firstCellIndex;\n }\n return firstCellIndex + (sizeItem.height - 1) * cols;\n case 'br':\n return cellMap.lastIndexOf(index);\n }\n}\n\n/** Gets all cell indices that correspond to the specified indices */\nfunction getGridCellIndices(indices, cellMap) {\n return cellMap.flatMap((index, cellIndex) => indices.includes(index) ? [cellIndex] : []);\n}\nfunction isListIndexDisabled(listRef, index, disabledIndices) {\n if (typeof disabledIndices === 'function') {\n return disabledIndices(index);\n } else if (disabledIndices) {\n return disabledIndices.includes(index);\n }\n const element = listRef.current[index];\n return element == null || element.hasAttribute('disabled') || element.getAttribute('aria-disabled') === 'true';\n}\n\nconst getTabbableOptions = () => ({\n getShadowRoot: true,\n displayCheck:\n // JSDOM does not support the `tabbable` library. To solve this we can\n // check if `ResizeObserver` is a real function (not polyfilled), which\n // determines if the current environment is JSDOM-like.\n typeof ResizeObserver === 'function' && ResizeObserver.toString().includes('[native code]') ? 'full' : 'none'\n});\nfunction getTabbableIn(container, dir) {\n const list = tabbable(container, getTabbableOptions());\n const len = list.length;\n if (len === 0) return;\n const active = activeElement(getDocument(container));\n const index = list.indexOf(active);\n const nextIndex = index === -1 ? dir === 1 ? 0 : len - 1 : index + dir;\n return list[nextIndex];\n}\nfunction getNextTabbable(referenceElement) {\n return getTabbableIn(getDocument(referenceElement).body, 1) || referenceElement;\n}\nfunction getPreviousTabbable(referenceElement) {\n return getTabbableIn(getDocument(referenceElement).body, -1) || referenceElement;\n}\nfunction isOutsideEvent(event, container) {\n const containerElement = container || event.currentTarget;\n const relatedTarget = event.relatedTarget;\n return !relatedTarget || !contains(containerElement, relatedTarget);\n}\nfunction disableFocusInside(container) {\n const tabbableElements = tabbable(container, getTabbableOptions());\n tabbableElements.forEach(element => {\n element.dataset.tabindex = element.getAttribute('tabindex') || '';\n element.setAttribute('tabindex', '-1');\n });\n}\nfunction enableFocusInside(container) {\n const elements = container.querySelectorAll('[data-tabindex]');\n elements.forEach(element => {\n const tabindex = element.dataset.tabindex;\n delete element.dataset.tabindex;\n if (tabindex) {\n element.setAttribute('tabindex', tabindex);\n } else {\n element.removeAttribute('tabindex');\n }\n });\n}\n\nexport { activeElement, contains, createGridCellMap, disableFocusInside, enableFocusInside, findNonDisabledListIndex, getDeepestNode, getDocument, getFloatingFocusElement, getGridCellIndexOfCorner, getGridCellIndices, getGridNavigatedIndex, getMaxListIndex, getMinListIndex, getNextTabbable, getNodeAncestors, getNodeChildren, getPlatform, getPreviousTabbable, getTabbableOptions, getTarget, getUserAgent, isAndroid, isDifferentGridRow, isEventTargetWithin, isIndexOutOfListBounds, isJSDOM, isListIndexDisabled, isMac, isMouseLikePointerType, isOutsideEvent, isReactEvent, isRootElement, isSafari, isTypeableCombobox, isTypeableElement, isVirtualClick, isVirtualPointerEvent, matchesFocusVisible, stopEvent, useEffectEvent, useLatestRef, index as useModernLayoutEffect };\n","import { getSideAxis, getAlignmentAxis, getAxisLength, getSide, getAlignment, evaluate, getPaddingObject, rectToClientRect, min, clamp, placements, getAlignmentSides, getOppositeAlignmentPlacement, getOppositePlacement, getExpandedPlacements, getOppositeAxisPlacements, sides, max, getOppositeAxis } from '@floating-ui/utils';\nexport { rectToClientRect } from '@floating-ui/utils';\n\nfunction computeCoordsFromPlacement(_ref, placement, rtl) {\n let {\n reference,\n floating\n } = _ref;\n const sideAxis = getSideAxis(placement);\n const alignmentAxis = getAlignmentAxis(placement);\n const alignLength = getAxisLength(alignmentAxis);\n const side = getSide(placement);\n const isVertical = sideAxis === 'y';\n const commonX = reference.x + reference.width / 2 - floating.width / 2;\n const commonY = reference.y + reference.height / 2 - floating.height / 2;\n const commonAlign = reference[alignLength] / 2 - floating[alignLength] / 2;\n let coords;\n switch (side) {\n case 'top':\n coords = {\n x: commonX,\n y: reference.y - floating.height\n };\n break;\n case 'bottom':\n coords = {\n x: commonX,\n y: reference.y + reference.height\n };\n break;\n case 'right':\n coords = {\n x: reference.x + reference.width,\n y: commonY\n };\n break;\n case 'left':\n coords = {\n x: reference.x - floating.width,\n y: commonY\n };\n break;\n default:\n coords = {\n x: reference.x,\n y: reference.y\n };\n }\n switch (getAlignment(placement)) {\n case 'start':\n coords[alignmentAxis] -= commonAlign * (rtl && isVertical ? -1 : 1);\n break;\n case 'end':\n coords[alignmentAxis] += commonAlign * (rtl && isVertical ? -1 : 1);\n break;\n }\n return coords;\n}\n\n/**\n * Resolves with an object of overflow side offsets that determine how much the\n * element is overflowing a given clipping boundary on each side.\n * - positive = overflowing the boundary by that number of pixels\n * - negative = how many pixels left before it will overflow\n * - 0 = lies flush with the boundary\n * @see https://floating-ui.com/docs/detectOverflow\n */\nasync function detectOverflow(state, options) {\n var _await$platform$isEle;\n if (options === void 0) {\n options = {};\n }\n const {\n x,\n y,\n platform,\n rects,\n elements,\n strategy\n } = state;\n const {\n boundary = 'clippingAncestors',\n rootBoundary = 'viewport',\n elementContext = 'floating',\n altBoundary = false,\n padding = 0\n } = evaluate(options, state);\n const paddingObject = getPaddingObject(padding);\n const altContext = elementContext === 'floating' ? 'reference' : 'floating';\n const element = elements[altBoundary ? altContext : elementContext];\n const clippingClientRect = rectToClientRect(await platform.getClippingRect({\n element: ((_await$platform$isEle = await (platform.isElement == null ? void 0 : platform.isElement(element))) != null ? _await$platform$isEle : true) ? element : element.contextElement || (await (platform.getDocumentElement == null ? void 0 : platform.getDocumentElement(elements.floating))),\n boundary,\n rootBoundary,\n strategy\n }));\n const rect = elementContext === 'floating' ? {\n x,\n y,\n width: rects.floating.width,\n height: rects.floating.height\n } : rects.reference;\n const offsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(elements.floating));\n const offsetScale = (await (platform.isElement == null ? void 0 : platform.isElement(offsetParent))) ? (await (platform.getScale == null ? void 0 : platform.getScale(offsetParent))) || {\n x: 1,\n y: 1\n } : {\n x: 1,\n y: 1\n };\n const elementClientRect = rectToClientRect(platform.convertOffsetParentRelativeRectToViewportRelativeRect ? await platform.convertOffsetParentRelativeRectToViewportRelativeRect({\n elements,\n rect,\n offsetParent,\n strategy\n }) : rect);\n return {\n top: (clippingClientRect.top - elementClientRect.top + paddingObject.top) / offsetScale.y,\n bottom: (elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom) / offsetScale.y,\n left: (clippingClientRect.left - elementClientRect.left + paddingObject.left) / offsetScale.x,\n right: (elementClientRect.right - clippingClientRect.right + paddingObject.right) / offsetScale.x\n };\n}\n\n/**\n * Computes the `x` and `y` coordinates that will place the floating element\n * next to a given reference element.\n *\n * This export does not have any `platform` interface logic. You will need to\n * write one for the platform you are using Floating UI with.\n */\nconst computePosition = async (reference, floating, config) => {\n const {\n placement = 'bottom',\n strategy = 'absolute',\n middleware = [],\n platform\n } = config;\n const validMiddleware = middleware.filter(Boolean);\n const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(floating));\n let rects = await platform.getElementRects({\n reference,\n floating,\n strategy\n });\n let {\n x,\n y\n } = computeCoordsFromPlacement(rects, placement, rtl);\n let statefulPlacement = placement;\n let middlewareData = {};\n let resetCount = 0;\n for (let i = 0; i < validMiddleware.length; i++) {\n var _platform$detectOverf;\n const {\n name,\n fn\n } = validMiddleware[i];\n const {\n x: nextX,\n y: nextY,\n data,\n reset\n } = await fn({\n x,\n y,\n initialPlacement: placement,\n placement: statefulPlacement,\n strategy,\n middlewareData,\n rects,\n platform: {\n ...platform,\n detectOverflow: (_platform$detectOverf = platform.detectOverflow) != null ? _platform$detectOverf : detectOverflow\n },\n elements: {\n reference,\n floating\n }\n });\n x = nextX != null ? nextX : x;\n y = nextY != null ? nextY : y;\n middlewareData = {\n ...middlewareData,\n [name]: {\n ...middlewareData[name],\n ...data\n }\n };\n if (reset && resetCount <= 50) {\n resetCount++;\n if (typeof reset === 'object') {\n if (reset.placement) {\n statefulPlacement = reset.placement;\n }\n if (reset.rects) {\n rects = reset.rects === true ? await platform.getElementRects({\n reference,\n floating,\n strategy\n }) : reset.rects;\n }\n ({\n x,\n y\n } = computeCoordsFromPlacement(rects, statefulPlacement, rtl));\n }\n i = -1;\n }\n }\n return {\n x,\n y,\n placement: statefulPlacement,\n strategy,\n middlewareData\n };\n};\n\n/**\n * Provides data to position an inner element of the floating element so that it\n * appears centered to the reference element.\n * @see https://floating-ui.com/docs/arrow\n */\nconst arrow = options => ({\n name: 'arrow',\n options,\n async fn(state) {\n const {\n x,\n y,\n placement,\n rects,\n platform,\n elements,\n middlewareData\n } = state;\n // Since `element` is required, we don't Partial<> the type.\n const {\n element,\n padding = 0\n } = evaluate(options, state) || {};\n if (element == null) {\n return {};\n }\n const paddingObject = getPaddingObject(padding);\n const coords = {\n x,\n y\n };\n const axis = getAlignmentAxis(placement);\n const length = getAxisLength(axis);\n const arrowDimensions = await platform.getDimensions(element);\n const isYAxis = axis === 'y';\n const minProp = isYAxis ? 'top' : 'left';\n const maxProp = isYAxis ? 'bottom' : 'right';\n const clientProp = isYAxis ? 'clientHeight' : 'clientWidth';\n const endDiff = rects.reference[length] + rects.reference[axis] - coords[axis] - rects.floating[length];\n const startDiff = coords[axis] - rects.reference[axis];\n const arrowOffsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(element));\n let clientSize = arrowOffsetParent ? arrowOffsetParent[clientProp] : 0;\n\n // DOM platform can return `window` as the `offsetParent`.\n if (!clientSize || !(await (platform.isElement == null ? void 0 : platform.isElement(arrowOffsetParent)))) {\n clientSize = elements.floating[clientProp] || rects.floating[length];\n }\n const centerToReference = endDiff / 2 - startDiff / 2;\n\n // If the padding is large enough that it causes the arrow to no longer be\n // centered, modify the padding so that it is centered.\n const largestPossiblePadding = clientSize / 2 - arrowDimensions[length] / 2 - 1;\n const minPadding = min(paddingObject[minProp], largestPossiblePadding);\n const maxPadding = min(paddingObject[maxProp], largestPossiblePadding);\n\n // Make sure the arrow doesn't overflow the floating element if the center\n // point is outside the floating element's bounds.\n const min$1 = minPadding;\n const max = clientSize - arrowDimensions[length] - maxPadding;\n const center = clientSize / 2 - arrowDimensions[length] / 2 + centerToReference;\n const offset = clamp(min$1, center, max);\n\n // If the reference is small enough that the arrow's padding causes it to\n // to point to nothing for an aligned placement, adjust the offset of the\n // floating element itself. To ensure `shift()` continues to take action,\n // a single reset is performed when this is true.\n const shouldAddOffset = !middlewareData.arrow && getAlignment(placement) != null && center !== offset && rects.reference[length] / 2 - (center < min$1 ? minPadding : maxPadding) - arrowDimensions[length] / 2 < 0;\n const alignmentOffset = shouldAddOffset ? center < min$1 ? center - min$1 : center - max : 0;\n return {\n [axis]: coords[axis] + alignmentOffset,\n data: {\n [axis]: offset,\n centerOffset: center - offset - alignmentOffset,\n ...(shouldAddOffset && {\n alignmentOffset\n })\n },\n reset: shouldAddOffset\n };\n }\n});\n\nfunction getPlacementList(alignment, autoAlignment, allowedPlacements) {\n const allowedPlacementsSortedByAlignment = alignment ? [...allowedPlacements.filter(placement => getAlignment(placement) === alignment), ...allowedPlacements.filter(placement => getAlignment(placement) !== alignment)] : allowedPlacements.filter(placement => getSide(placement) === placement);\n return allowedPlacementsSortedByAlignment.filter(placement => {\n if (alignment) {\n return getAlignment(placement) === alignment || (autoAlignment ? getOppositeAlignmentPlacement(placement) !== placement : false);\n }\n return true;\n });\n}\n/**\n * Optimizes the visibility of the floating element by choosing the placement\n * that has the most space available automatically, without needing to specify a\n * preferred placement. Alternative to `flip`.\n * @see https://floating-ui.com/docs/autoPlacement\n */\nconst autoPlacement = function (options) {\n if (options === void 0) {\n options = {};\n }\n return {\n name: 'autoPlacement',\n options,\n async fn(state) {\n var _middlewareData$autoP, _middlewareData$autoP2, _placementsThatFitOnE;\n const {\n rects,\n middlewareData,\n placement,\n platform,\n elements\n } = state;\n const {\n crossAxis = false,\n alignment,\n allowedPlacements = placements,\n autoAlignment = true,\n ...detectOverflowOptions\n } = evaluate(options, state);\n const placements$1 = alignment !== undefined || allowedPlacements === placements ? getPlacementList(alignment || null, autoAlignment, allowedPlacements) : allowedPlacements;\n const overflow = await platform.detectOverflow(state, detectOverflowOptions);\n const currentIndex = ((_middlewareData$autoP = middlewareData.autoPlacement) == null ? void 0 : _middlewareData$autoP.index) || 0;\n const currentPlacement = placements$1[currentIndex];\n if (currentPlacement == null) {\n return {};\n }\n const alignmentSides = getAlignmentSides(currentPlacement, rects, await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating)));\n\n // Make `computeCoords` start from the right place.\n if (placement !== currentPlacement) {\n return {\n reset: {\n placement: placements$1[0]\n }\n };\n }\n const currentOverflows = [overflow[getSide(currentPlacement)], overflow[alignmentSides[0]], overflow[alignmentSides[1]]];\n const allOverflows = [...(((_middlewareData$autoP2 = middlewareData.autoPlacement) == null ? void 0 : _middlewareData$autoP2.overflows) || []), {\n placement: currentPlacement,\n overflows: currentOverflows\n }];\n const nextPlacement = placements$1[currentIndex + 1];\n\n // There are more placements to check.\n if (nextPlacement) {\n return {\n data: {\n index: currentIndex + 1,\n overflows: allOverflows\n },\n reset: {\n placement: nextPlacement\n }\n };\n }\n const placementsSortedByMostSpace = allOverflows.map(d => {\n const alignment = getAlignment(d.placement);\n return [d.placement, alignment && crossAxis ?\n // Check along the mainAxis and main crossAxis side.\n d.overflows.slice(0, 2).reduce((acc, v) => acc + v, 0) :\n // Check only the mainAxis.\n d.overflows[0], d.overflows];\n }).sort((a, b) => a[1] - b[1]);\n const placementsThatFitOnEachSide = placementsSortedByMostSpace.filter(d => d[2].slice(0,\n // Aligned placements should not check their opposite crossAxis\n // side.\n getAlignment(d[0]) ? 2 : 3).every(v => v <= 0));\n const resetPlacement = ((_placementsThatFitOnE = placementsThatFitOnEachSide[0]) == null ? void 0 : _placementsThatFitOnE[0]) || placementsSortedByMostSpace[0][0];\n if (resetPlacement !== placement) {\n return {\n data: {\n index: currentIndex + 1,\n overflows: allOverflows\n },\n reset: {\n placement: resetPlacement\n }\n };\n }\n return {};\n }\n };\n};\n\n/**\n * Optimizes the visibility of the floating element by flipping the `placement`\n * in order to keep it in view when the preferred placement(s) will overflow the\n * clipping boundary. Alternative to `autoPlacement`.\n * @see https://floating-ui.com/docs/flip\n */\nconst flip = function (options) {\n if (options === void 0) {\n options = {};\n }\n return {\n name: 'flip',\n options,\n async fn(state) {\n var _middlewareData$arrow, _middlewareData$flip;\n const {\n placement,\n middlewareData,\n rects,\n initialPlacement,\n platform,\n elements\n } = state;\n const {\n mainAxis: checkMainAxis = true,\n crossAxis: checkCrossAxis = true,\n fallbackPlacements: specifiedFallbackPlacements,\n fallbackStrategy = 'bestFit',\n fallbackAxisSideDirection = 'none',\n flipAlignment = true,\n ...detectOverflowOptions\n } = evaluate(options, state);\n\n // If a reset by the arrow was caused due to an alignment offset being\n // added, we should skip any logic now since `flip()` has already done its\n // work.\n // https://github.com/floating-ui/floating-ui/issues/2549#issuecomment-1719601643\n if ((_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) {\n return {};\n }\n const side = getSide(placement);\n const initialSideAxis = getSideAxis(initialPlacement);\n const isBasePlacement = getSide(initialPlacement) === initialPlacement;\n const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating));\n const fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipAlignment ? [getOppositePlacement(initialPlacement)] : getExpandedPlacements(initialPlacement));\n const hasFallbackAxisSideDirection = fallbackAxisSideDirection !== 'none';\n if (!specifiedFallbackPlacements && hasFallbackAxisSideDirection) {\n fallbackPlacements.push(...getOppositeAxisPlacements(initialPlacement, flipAlignment, fallbackAxisSideDirection, rtl));\n }\n const placements = [initialPlacement, ...fallbackPlacements];\n const overflow = await platform.detectOverflow(state, detectOverflowOptions);\n const overflows = [];\n let overflowsData = ((_middlewareData$flip = middlewareData.flip) == null ? void 0 : _middlewareData$flip.overflows) || [];\n if (checkMainAxis) {\n overflows.push(overflow[side]);\n }\n if (checkCrossAxis) {\n const sides = getAlignmentSides(placement, rects, rtl);\n overflows.push(overflow[sides[0]], overflow[sides[1]]);\n }\n overflowsData = [...overflowsData, {\n placement,\n overflows\n }];\n\n // One or more sides is overflowing.\n if (!overflows.every(side => side <= 0)) {\n var _middlewareData$flip2, _overflowsData$filter;\n const nextIndex = (((_middlewareData$flip2 = middlewareData.flip) == null ? void 0 : _middlewareData$flip2.index) || 0) + 1;\n const nextPlacement = placements[nextIndex];\n if (nextPlacement) {\n const ignoreCrossAxisOverflow = checkCrossAxis === 'alignment' ? initialSideAxis !== getSideAxis(nextPlacement) : false;\n if (!ignoreCrossAxisOverflow ||\n // We leave the current main axis only if every placement on that axis\n // overflows the main axis.\n overflowsData.every(d => getSideAxis(d.placement) === initialSideAxis ? d.overflows[0] > 0 : true)) {\n // Try next placement and re-run the lifecycle.\n return {\n data: {\n index: nextIndex,\n overflows: overflowsData\n },\n reset: {\n placement: nextPlacement\n }\n };\n }\n }\n\n // First, find the candidates that fit on the mainAxis side of overflow,\n // then find the placement that fits the best on the main crossAxis side.\n 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;\n\n // Otherwise fallback.\n if (!resetPlacement) {\n switch (fallbackStrategy) {\n case 'bestFit':\n {\n var _overflowsData$filter2;\n const placement = (_overflowsData$filter2 = overflowsData.filter(d => {\n if (hasFallbackAxisSideDirection) {\n const currentSideAxis = getSideAxis(d.placement);\n return currentSideAxis === initialSideAxis ||\n // Create a bias to the `y` side axis due to horizontal\n // reading directions favoring greater width.\n currentSideAxis === 'y';\n }\n return true;\n }).map(d => [d.placement, d.overflows.filter(overflow => overflow > 0).reduce((acc, overflow) => acc + overflow, 0)]).sort((a, b) => a[1] - b[1])[0]) == null ? void 0 : _overflowsData$filter2[0];\n if (placement) {\n resetPlacement = placement;\n }\n break;\n }\n case 'initialPlacement':\n resetPlacement = initialPlacement;\n break;\n }\n }\n if (placement !== resetPlacement) {\n return {\n reset: {\n placement: resetPlacement\n }\n };\n }\n }\n return {};\n }\n };\n};\n\nfunction getSideOffsets(overflow, rect) {\n return {\n top: overflow.top - rect.height,\n right: overflow.right - rect.width,\n bottom: overflow.bottom - rect.height,\n left: overflow.left - rect.width\n };\n}\nfunction isAnySideFullyClipped(overflow) {\n return sides.some(side => overflow[side] >= 0);\n}\n/**\n * Provides data to hide the floating element in applicable situations, such as\n * when it is not in the same clipping context as the reference element.\n * @see https://floating-ui.com/docs/hide\n */\nconst hide = function (options) {\n if (options === void 0) {\n options = {};\n }\n return {\n name: 'hide',\n options,\n async fn(state) {\n const {\n rects,\n platform\n } = state;\n const {\n strategy = 'referenceHidden',\n ...detectOverflowOptions\n } = evaluate(options, state);\n switch (strategy) {\n case 'referenceHidden':\n {\n const overflow = await platform.detectOverflow(state, {\n ...detectOverflowOptions,\n elementContext: 'reference'\n });\n const offsets = getSideOffsets(overflow, rects.reference);\n return {\n data: {\n referenceHiddenOffsets: offsets,\n referenceHidden: isAnySideFullyClipped(offsets)\n }\n };\n }\n case 'escaped':\n {\n const overflow = await platform.detectOverflow(state, {\n ...detectOverflowOptions,\n altBoundary: true\n });\n const offsets = getSideOffsets(overflow, rects.floating);\n return {\n data: {\n escapedOffsets: offsets,\n escaped: isAnySideFullyClipped(offsets)\n }\n };\n }\n default:\n {\n return {};\n }\n }\n }\n };\n};\n\nfunction getBoundingRect(rects) {\n const minX = min(...rects.map(rect => rect.left));\n const minY = min(...rects.map(rect => rect.top));\n const maxX = max(...rects.map(rect => rect.right));\n const maxY = max(...rects.map(rect => rect.bottom));\n return {\n x: minX,\n y: minY,\n width: maxX - minX,\n height: maxY - minY\n };\n}\nfunction getRectsByLine(rects) {\n const sortedRects = rects.slice().sort((a, b) => a.y - b.y);\n const groups = [];\n let prevRect = null;\n for (let i = 0; i < sortedRects.length; i++) {\n const rect = sortedRects[i];\n if (!prevRect || rect.y - prevRect.y > prevRect.height / 2) {\n groups.push([rect]);\n } else {\n groups[groups.length - 1].push(rect);\n }\n prevRect = rect;\n }\n return groups.map(rect => rectToClientRect(getBoundingRect(rect)));\n}\n/**\n * Provides improved positioning for inline reference elements that can span\n * over multiple lines, such as hyperlinks or range selections.\n * @see https://floating-ui.com/docs/inline\n */\nconst inline = function (options) {\n if (options === void 0) {\n options = {};\n }\n return {\n name: 'inline',\n options,\n async fn(state) {\n const {\n placement,\n elements,\n rects,\n platform,\n strategy\n } = state;\n // A MouseEvent's client{X,Y} coords can be up to 2 pixels off a\n // ClientRect's bounds, despite the event listener being triggered. A\n // padding of 2 seems to handle this issue.\n const {\n padding = 2,\n x,\n y\n } = evaluate(options, state);\n const nativeClientRects = Array.from((await (platform.getClientRects == null ? void 0 : platform.getClientRects(elements.reference))) || []);\n const clientRects = getRectsByLine(nativeClientRects);\n const fallback = rectToClientRect(getBoundingRect(nativeClientRects));\n const paddingObject = getPaddingObject(padding);\n function getBoundingClientRect() {\n // There are two rects and they are disjoined.\n if (clientRects.length === 2 && clientRects[0].left > clientRects[1].right && x != null && y != null) {\n // Find the first rect in which the point is fully inside.\n return clientRects.find(rect => x > rect.left - paddingObject.left && x < rect.right + paddingObject.right && y > rect.top - paddingObject.top && y < rect.bottom + paddingObject.bottom) || fallback;\n }\n\n // There are 2 or more connected rects.\n if (clientRects.length >= 2) {\n if (getSideAxis(placement) === 'y') {\n const firstRect = clientRects[0];\n const lastRect = clientRects[clientRects.length - 1];\n const isTop = getSide(placement) === 'top';\n const top = firstRect.top;\n const bottom = lastRect.bottom;\n const left = isTop ? firstRect.left : lastRect.left;\n const right = isTop ? firstRect.right : lastRect.right;\n const width = right - left;\n const height = bottom - top;\n return {\n top,\n bottom,\n left,\n right,\n width,\n height,\n x: left,\n y: top\n };\n }\n const isLeftSide = getSide(placement) === 'left';\n const maxRight = max(...clientRects.map(rect => rect.right));\n const minLeft = min(...clientRects.map(rect => rect.left));\n const measureRects = clientRects.filter(rect => isLeftSide ? rect.left === minLeft : rect.right === maxRight);\n const top = measureRects[0].top;\n const bottom = measureRects[measureRects.length - 1].bottom;\n const left = minLeft;\n const right = maxRight;\n const width = right - left;\n const height = bottom - top;\n return {\n top,\n bottom,\n left,\n right,\n width,\n height,\n x: left,\n y: top\n };\n }\n return fallback;\n }\n const resetRects = await platform.getElementRects({\n reference: {\n getBoundingClientRect\n },\n floating: elements.floating,\n strategy\n });\n if (rects.reference.x !== resetRects.reference.x || rects.reference.y !== resetRects.reference.y || rects.reference.width !== resetRects.reference.width || rects.reference.height !== resetRects.reference.height) {\n return {\n reset: {\n rects: resetRects\n }\n };\n }\n return {};\n }\n };\n};\n\nconst originSides = /*#__PURE__*/new Set(['left', 'top']);\n\n// For type backwards-compatibility, the `OffsetOptions` type was also\n// Derivable.\n\nasync function convertValueToCoords(state, options) {\n const {\n placement,\n platform,\n elements\n } = state;\n const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating));\n const side = getSide(placement);\n const alignment = getAlignment(placement);\n const isVertical = getSideAxis(placement) === 'y';\n const mainAxisMulti = originSides.has(side) ? -1 : 1;\n const crossAxisMulti = rtl && isVertical ? -1 : 1;\n const rawValue = evaluate(options, state);\n\n // eslint-disable-next-line prefer-const\n let {\n mainAxis,\n crossAxis,\n alignmentAxis\n } = typeof rawValue === 'number' ? {\n mainAxis: rawValue,\n crossAxis: 0,\n alignmentAxis: null\n } : {\n mainAxis: rawValue.mainAxis || 0,\n crossAxis: rawValue.crossAxis || 0,\n alignmentAxis: rawValue.alignmentAxis\n };\n if (alignment && typeof alignmentAxis === 'number') {\n crossAxis = alignment === 'end' ? alignmentAxis * -1 : alignmentAxis;\n }\n return isVertical ? {\n x: crossAxis * crossAxisMulti,\n y: mainAxis * mainAxisMulti\n } : {\n x: mainAxis * mainAxisMulti,\n y: crossAxis * crossAxisMulti\n };\n}\n\n/**\n * Modifies the placement by translating the floating element along the\n * specified axes.\n * A number (shorthand for `mainAxis` or distance), or an axes configuration\n * object may be passed.\n * @see https://floating-ui.com/docs/offset\n */\nconst offset = function (options) {\n if (options === void 0) {\n options = 0;\n }\n return {\n name: 'offset',\n options,\n async fn(state) {\n var _middlewareData$offse, _middlewareData$arrow;\n const {\n x,\n y,\n placement,\n middlewareData\n } = state;\n const diffCoords = await convertValueToCoords(state, options);\n\n // If the placement is the same and the arrow caused an alignment offset\n // then we don't need to change the positioning coordinates.\n if (placement === ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse.placement) && (_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) {\n return {};\n }\n return {\n x: x + diffCoords.x,\n y: y + diffCoords.y,\n data: {\n ...diffCoords,\n placement\n }\n };\n }\n };\n};\n\n/**\n * Optimizes the visibility of the floating element by shifting it in order to\n * keep it in view when it will overflow the clipping boundary.\n * @see https://floating-ui.com/docs/shift\n */\nconst shift = function (options) {\n if (options === void 0) {\n options = {};\n }\n return {\n name: 'shift',\n options,\n async fn(state) {\n const {\n x,\n y,\n placement,\n platform\n } = state;\n const {\n mainAxis: checkMainAxis = true,\n crossAxis: checkCrossAxis = false,\n limiter = {\n fn: _ref => {\n let {\n x,\n y\n } = _ref;\n return {\n x,\n y\n };\n }\n },\n ...detectOverflowOptions\n } = evaluate(options, state);\n const coords = {\n x,\n y\n };\n const overflow = await platform.detectOverflow(state, detectOverflowOptions);\n const crossAxis = getSideAxis(getSide(placement));\n const mainAxis = getOppositeAxis(crossAxis);\n let mainAxisCoord = coords[mainAxis];\n let crossAxisCoord = coords[crossAxis];\n if (checkMainAxis) {\n const minSide = mainAxis === 'y' ? 'top' : 'left';\n const maxSide = mainAxis === 'y' ? 'bottom' : 'right';\n const min = mainAxisCoord + overflow[minSide];\n const max = mainAxisCoord - overflow[maxSide];\n mainAxisCoord = clamp(min, mainAxisCoord, max);\n }\n if (checkCrossAxis) {\n const minSide = crossAxis === 'y' ? 'top' : 'left';\n const maxSide = crossAxis === 'y' ? 'bottom' : 'right';\n const min = crossAxisCoord + overflow[minSide];\n const max = crossAxisCoord - overflow[maxSide];\n crossAxisCoord = clamp(min, crossAxisCoord, max);\n }\n const limitedCoords = limiter.fn({\n ...state,\n [mainAxis]: mainAxisCoord,\n [crossAxis]: crossAxisCoord\n });\n return {\n ...limitedCoords,\n data: {\n x: limitedCoords.x - x,\n y: limitedCoords.y - y,\n enabled: {\n [mainAxis]: checkMainAxis,\n [crossAxis]: checkCrossAxis\n }\n }\n };\n }\n };\n};\n/**\n * Built-in `limiter` that will stop `shift()` at a certain point.\n */\nconst limitShift = function (options) {\n if (options === void 0) {\n options = {};\n }\n return {\n options,\n fn(state) {\n const {\n x,\n y,\n placement,\n rects,\n middlewareData\n } = state;\n const {\n offset = 0,\n mainAxis: checkMainAxis = true,\n crossAxis: checkCrossAxis = true\n } = evaluate(options, state);\n const coords = {\n x,\n y\n };\n const crossAxis = getSideAxis(placement);\n const mainAxis = getOppositeAxis(crossAxis);\n let mainAxisCoord = coords[mainAxis];\n let crossAxisCoord = coords[crossAxis];\n const rawOffset = evaluate(offset, state);\n const computedOffset = typeof rawOffset === 'number' ? {\n mainAxis: rawOffset,\n crossAxis: 0\n } : {\n mainAxis: 0,\n crossAxis: 0,\n ...rawOffset\n };\n if (checkMainAxis) {\n const len = mainAxis === 'y' ? 'height' : 'width';\n const limitMin = rects.reference[mainAxis] - rects.floating[len] + computedOffset.mainAxis;\n const limitMax = rects.reference[mainAxis] + rects.reference[len] - computedOffset.mainAxis;\n if (mainAxisCoord < limitMin) {\n mainAxisCoord = limitMin;\n } else if (mainAxisCoord > limitMax) {\n mainAxisCoord = limitMax;\n }\n }\n if (checkCrossAxis) {\n var _middlewareData$offse, _middlewareData$offse2;\n const len = mainAxis === 'y' ? 'width' : 'height';\n const isOriginSide = originSides.has(getSide(placement));\n const limitMin = rects.reference[crossAxis] - rects.floating[len] + (isOriginSide ? ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse[crossAxis]) || 0 : 0) + (isOriginSide ? 0 : computedOffset.crossAxis);\n const limitMax = rects.reference[crossAxis] + rects.reference[len] + (isOriginSide ? 0 : ((_middlewareData$offse2 = middlewareData.offset) == null ? void 0 : _middlewareData$offse2[crossAxis]) || 0) - (isOriginSide ? computedOffset.crossAxis : 0);\n if (crossAxisCoord < limitMin) {\n crossAxisCoord = limitMin;\n } else if (crossAxisCoord > limitMax) {\n crossAxisCoord = limitMax;\n }\n }\n return {\n [mainAxis]: mainAxisCoord,\n [crossAxis]: crossAxisCoord\n };\n }\n };\n};\n\n/**\n * Provides data that allows you to change the size of the floating element —\n * for instance, prevent it from overflowing the clipping boundary or match the\n * width of the reference element.\n * @see https://floating-ui.com/docs/size\n */\nconst size = function (options) {\n if (options === void 0) {\n options = {};\n }\n return {\n name: 'size',\n options,\n async fn(state) {\n var _state$middlewareData, _state$middlewareData2;\n const {\n placement,\n rects,\n platform,\n elements\n } = state;\n const {\n apply = () => {},\n ...detectOverflowOptions\n } = evaluate(options, state);\n const overflow = await platform.detectOverflow(state, detectOverflowOptions);\n const side = getSide(placement);\n const alignment = getAlignment(placement);\n const isYAxis = getSideAxis(placement) === 'y';\n const {\n width,\n height\n } = rects.floating;\n let heightSide;\n let widthSide;\n if (side === 'top' || side === 'bottom') {\n heightSide = side;\n widthSide = alignment === ((await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating))) ? 'start' : 'end') ? 'left' : 'right';\n } else {\n widthSide = side;\n heightSide = alignment === 'end' ? 'top' : 'bottom';\n }\n const maximumClippingHeight = height - overflow.top - overflow.bottom;\n const maximumClippingWidth = width - overflow.left - overflow.right;\n const overflowAvailableHeight = min(height - overflow[heightSide], maximumClippingHeight);\n const overflowAvailableWidth = min(width - overflow[widthSide], maximumClippingWidth);\n const noShift = !state.middlewareData.shift;\n let availableHeight = overflowAvailableHeight;\n let availableWidth = overflowAvailableWidth;\n if ((_state$middlewareData = state.middlewareData.shift) != null && _state$middlewareData.enabled.x) {\n availableWidth = maximumClippingWidth;\n }\n if ((_state$middlewareData2 = state.middlewareData.shift) != null && _state$middlewareData2.enabled.y) {\n availableHeight = maximumClippingHeight;\n }\n if (noShift && !alignment) {\n const xMin = max(overflow.left, 0);\n const xMax = max(overflow.right, 0);\n const yMin = max(overflow.top, 0);\n const yMax = max(overflow.bottom, 0);\n if (isYAxis) {\n availableWidth = width - 2 * (xMin !== 0 || xMax !== 0 ? xMin + xMax : max(overflow.left, overflow.right));\n } else {\n availableHeight = height - 2 * (yMin !== 0 || yMax !== 0 ? yMin + yMax : max(overflow.top, overflow.bottom));\n }\n }\n await apply({\n ...state,\n availableWidth,\n availableHeight\n });\n const nextDimensions = await platform.getDimensions(elements.floating);\n if (width !== nextDimensions.width || height !== nextDimensions.height) {\n return {\n reset: {\n rects: true\n }\n };\n }\n return {};\n }\n };\n};\n\nexport { arrow, autoPlacement, computePosition, detectOverflow, flip, hide, inline, limitShift, offset, shift, size };\n","import { rectToClientRect, arrow as arrow$1, autoPlacement as autoPlacement$1, detectOverflow as detectOverflow$1, flip as flip$1, hide as hide$1, inline as inline$1, limitShift as limitShift$1, offset as offset$1, shift as shift$1, size as size$1, computePosition as computePosition$1 } from '@floating-ui/core';\nimport { round, createCoords, max, min, floor } from '@floating-ui/utils';\nimport { getComputedStyle as getComputedStyle$1, isHTMLElement, isElement, getWindow, isWebKit, getFrameElement, getNodeScroll, getDocumentElement, isTopLayer, getNodeName, isOverflowElement, getOverflowAncestors, getParentNode, isLastTraversableNode, isContainingBlock, isTableElement, getContainingBlock } from '@floating-ui/utils/dom';\nexport { getOverflowAncestors } from '@floating-ui/utils/dom';\n\nfunction getCssDimensions(element) {\n const css = getComputedStyle$1(element);\n // In testing environments, the `width` and `height` properties are empty\n // strings for SVG elements, returning NaN. Fallback to `0` in this case.\n let width = parseFloat(css.width) || 0;\n let height = parseFloat(css.height) || 0;\n const hasOffset = isHTMLElement(element);\n const offsetWidth = hasOffset ? element.offsetWidth : width;\n const offsetHeight = hasOffset ? element.offsetHeight : height;\n const shouldFallback = round(width) !== offsetWidth || round(height) !== offsetHeight;\n if (shouldFallback) {\n width = offsetWidth;\n height = offsetHeight;\n }\n return {\n width,\n height,\n $: shouldFallback\n };\n}\n\nfunction unwrapElement(element) {\n return !isElement(element) ? element.contextElement : element;\n}\n\nfunction getScale(element) {\n const domElement = unwrapElement(element);\n if (!isHTMLElement(domElement)) {\n return createCoords(1);\n }\n const rect = domElement.getBoundingClientRect();\n const {\n width,\n height,\n $\n } = getCssDimensions(domElement);\n let x = ($ ? round(rect.width) : rect.width) / width;\n let y = ($ ? round(rect.height) : rect.height) / height;\n\n // 0, NaN, or Infinity should always fallback to 1.\n\n if (!x || !Number.isFinite(x)) {\n x = 1;\n }\n if (!y || !Number.isFinite(y)) {\n y = 1;\n }\n return {\n x,\n y\n };\n}\n\nconst noOffsets = /*#__PURE__*/createCoords(0);\nfunction getVisualOffsets(element) {\n const win = getWindow(element);\n if (!isWebKit() || !win.visualViewport) {\n return noOffsets;\n }\n return {\n x: win.visualViewport.offsetLeft,\n y: win.visualViewport.offsetTop\n };\n}\nfunction shouldAddVisualOffsets(element, isFixed, floatingOffsetParent) {\n if (isFixed === void 0) {\n isFixed = false;\n }\n if (!floatingOffsetParent || isFixed && floatingOffsetParent !== getWindow(element)) {\n return false;\n }\n return isFixed;\n}\n\nfunction getBoundingClientRect(element, includeScale, isFixedStrategy, offsetParent) {\n if (includeScale === void 0) {\n includeScale = false;\n }\n if (isFixedStrategy === void 0) {\n isFixedStrategy = false;\n }\n const clientRect = element.getBoundingClientRect();\n const domElement = unwrapElement(element);\n let scale = createCoords(1);\n if (includeScale) {\n if (offsetParent) {\n if (isElement(offsetParent)) {\n scale = getScale(offsetParent);\n }\n } else {\n scale = getScale(element);\n }\n }\n const visualOffsets = shouldAddVisualOffsets(domElement, isFixedStrategy, offsetParent) ? getVisualOffsets(domElement) : createCoords(0);\n let x = (clientRect.left + visualOffsets.x) / scale.x;\n let y = (clientRect.top + visualOffsets.y) / scale.y;\n let width = clientRect.width / scale.x;\n let height = clientRect.height / scale.y;\n if (domElement) {\n const win = getWindow(domElement);\n const offsetWin = offsetParent && isElement(offsetParent) ? getWindow(offsetParent) : offsetParent;\n let currentWin = win;\n let currentIFrame = getFrameElement(currentWin);\n while (currentIFrame && offsetParent && offsetWin !== currentWin) {\n const iframeScale = getScale(currentIFrame);\n const iframeRect = currentIFrame.getBoundingClientRect();\n const css = getComputedStyle$1(currentIFrame);\n const left = iframeRect.left + (currentIFrame.clientLeft + parseFloat(css.paddingLeft)) * iframeScale.x;\n const top = iframeRect.top + (currentIFrame.clientTop + parseFloat(css.paddingTop)) * iframeScale.y;\n x *= iframeScale.x;\n y *= iframeScale.y;\n width *= iframeScale.x;\n height *= iframeScale.y;\n x += left;\n y += top;\n currentWin = getWindow(currentIFrame);\n currentIFrame = getFrameElement(currentWin);\n }\n }\n return rectToClientRect({\n width,\n height,\n x,\n y\n });\n}\n\n// If <html> has a CSS width greater than the viewport, then this will be\n// incorrect for RTL.\nfunction getWindowScrollBarX(element, rect) {\n const leftScroll = getNodeScroll(element).scrollLeft;\n if (!rect) {\n return getBoundingClientRect(getDocumentElement(element)).left + leftScroll;\n }\n return rect.left + leftScroll;\n}\n\nfunction getHTMLOffset(documentElement, scroll) {\n const htmlRect = documentElement.getBoundingClientRect();\n const x = htmlRect.left + scroll.scrollLeft - getWindowScrollBarX(documentElement, htmlRect);\n const y = htmlRect.top + scroll.scrollTop;\n return {\n x,\n y\n };\n}\n\nfunction convertOffsetParentRelativeRectToViewportRelativeRect(_ref) {\n let {\n elements,\n rect,\n offsetParent,\n strategy\n } = _ref;\n const isFixed = strategy === 'fixed';\n const documentElement = getDocumentElement(offsetParent);\n const topLayer = elements ? isTopLayer(elements.floating) : false;\n if (offsetParent === documentElement || topLayer && isFixed) {\n return rect;\n }\n let scroll = {\n scrollLeft: 0,\n scrollTop: 0\n };\n let scale = createCoords(1);\n const offsets = createCoords(0);\n const isOffsetParentAnElement = isHTMLElement(offsetParent);\n if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {\n if (getNodeName(offsetParent) !== 'body' || isOverflowElement(documentElement)) {\n scroll = getNodeScroll(offsetParent);\n }\n if (isHTMLElement(offsetParent)) {\n const offsetRect = getBoundingClientRect(offsetParent);\n scale = getScale(offsetParent);\n offsets.x = offsetRect.x + offsetParent.clientLeft;\n offsets.y = offsetRect.y + offsetParent.clientTop;\n }\n }\n const htmlOffset = documentElement && !isOffsetParentAnElement && !isFixed ? getHTMLOffset(documentElement, scroll) : createCoords(0);\n return {\n width: rect.width * scale.x,\n height: rect.height * scale.y,\n x: rect.x * scale.x - scroll.scrollLeft * scale.x + offsets.x + htmlOffset.x,\n y: rect.y * scale.y - scroll.scrollTop * scale.y + offsets.y + htmlOffset.y\n };\n}\n\nfunction getClientRects(element) {\n return Array.from(element.getClientRects());\n}\n\n// Gets the entire size of the scrollable document area, even extending outside\n// of the `<html>` and `<body>` rect bounds if horizontally scrollable.\nfunction getDocumentRect(element) {\n const html = getDocumentElement(element);\n const scroll = getNodeScroll(element);\n const body = element.ownerDocument.body;\n const width = max(html.scrollWidth, html.clientWidth, body.scrollWidth, body.clientWidth);\n const height = max(html.scrollHeight, html.clientHeight, body.scrollHeight, body.clientHeight);\n let x = -scroll.scrollLeft + getWindowScrollBarX(element);\n const y = -scroll.scrollTop;\n if (getComputedStyle$1(body).direction === 'rtl') {\n x += max(html.clientWidth, body.clientWidth) - width;\n }\n return {\n width,\n height,\n x,\n y\n };\n}\n\n// Safety check: ensure the scrollbar space is reasonable in case this\n// calculation is affected by unusual styles.\n// Most scrollbars leave 15-18px of space.\nconst SCROLLBAR_MAX = 25;\nfunction getViewportRect(element, strategy) {\n const win = getWindow(element);\n const html = getDocumentElement(element);\n const visualViewport = win.visualViewport;\n let width = html.clientWidth;\n let height = html.clientHeight;\n let x = 0;\n let y = 0;\n if (visualViewport) {\n width = visualViewport.width;\n height = visualViewport.height;\n const visualViewportBased = isWebKit();\n if (!visualViewportBased || visualViewportBased && strategy === 'fixed') {\n x = visualViewport.offsetLeft;\n y = visualViewport.offsetTop;\n }\n }\n const windowScrollbarX = getWindowScrollBarX(html);\n // <html> `overflow: hidden` + `scrollbar-gutter: stable` reduces the\n // visual width of the <html> but this is not considered in the size\n // of `html.clientWidth`.\n if (windowScrollbarX <= 0) {\n const doc = html.ownerDocument;\n const body = doc.body;\n const bodyStyles = getComputedStyle(body);\n const bodyMarginInline = doc.compatMode === 'CSS1Compat' ? parseFloat(bodyStyles.marginLeft) + parseFloat(bodyStyles.marginRight) || 0 : 0;\n const clippingStableScrollbarWidth = Math.abs(html.clientWidth - body.clientWidth - bodyMarginInline);\n if (clippingStableScrollbarWidth <= SCROLLBAR_MAX) {\n width -= clippingStableScrollbarWidth;\n }\n } else if (windowScrollbarX <= SCROLLBAR_MAX) {\n // If the <body> scrollbar is on the left, the width needs to be extended\n // by the scrollbar amount so there isn't extra space on the right.\n width += windowScrollbarX;\n }\n return {\n width,\n height,\n x,\n y\n };\n}\n\nconst absoluteOrFixed = /*#__PURE__*/new Set(['absolute', 'fixed']);\n// Returns the inner client rect, subtracting scrollbars if present.\nfunction getInnerBoundingClientRect(element, strategy) {\n const clientRect = getBoundingClientRect(element, true, strategy === 'fixed');\n const top = clientRect.top + element.clientTop;\n const left = clientRect.left + element.clientLeft;\n const scale = isHTMLElement(element) ? getScale(element) : createCoords(1);\n const width = element.clientWidth * scale.x;\n const height = element.clientHeight * scale.y;\n const x = left * scale.x;\n const y = top * scale.y;\n return {\n width,\n height,\n x,\n y\n };\n}\nfunction getClientRectFromClippingAncestor(element, clippingAncestor, strategy) {\n let rect;\n if (clippingAncestor === 'viewport') {\n rect = getViewportRect(element, strategy);\n } else if (clippingAncestor === 'document') {\n rect = getDocumentRect(getDocumentElement(element));\n } else if (isElement(clippingAncestor)) {\n rect = getInnerBoundingClientRect(clippingAncestor, strategy);\n } else {\n const visualOffsets = getVisualOffsets(element);\n rect = {\n x: clippingAncestor.x - visualOffsets.x,\n y: clippingAncestor.y - visualOffsets.y,\n width: clippingAncestor.width,\n height: clippingAncestor.height\n };\n }\n return rectToClientRect(rect);\n}\nfunction hasFixedPositionAncestor(element, stopNode) {\n const parentNode = getParentNode(element);\n if (parentNode === stopNode || !isElement(parentNode) || isLastTraversableNode(parentNode)) {\n return false;\n }\n return getComputedStyle$1(parentNode).position === 'fixed' || hasFixedPositionAncestor(parentNode, stopNode);\n}\n\n// A \"clipping ancestor\" is an `overflow` element with the characteristic of\n// clipping (or hiding) child elements. This returns all clipping ancestors\n// of the given element up the tree.\nfunction getClippingElementAncestors(element, cache) {\n const cachedResult = cache.get(element);\n if (cachedResult) {\n return cachedResult;\n }\n let result = getOverflowAncestors(element, [], false).filter(el => isElement(el) && getNodeName(el) !== 'body');\n let currentContainingBlockComputedStyle = null;\n const elementIsFixed = getComputedStyle$1(element).position === 'fixed';\n let currentNode = elementIsFixed ? getParentNode(element) : element;\n\n // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block\n while (isElement(currentNode) && !isLastTraversableNode(currentNode)) {\n const computedStyle = getComputedStyle$1(currentNode);\n const currentNodeIsContaining = isContainingBlock(currentNode);\n if (!currentNodeIsContaining && computedStyle.position === 'fixed') {\n currentContainingBlockComputedStyle = null;\n }\n const shouldDropCurrentNode = elementIsFixed ? !currentNodeIsContaining && !currentContainingBlockComputedStyle : !currentNodeIsContaining && computedStyle.position === 'static' && !!currentContainingBlockComputedStyle && absoluteOrFixed.has(currentContainingBlockComputedStyle.position) || isOverflowElement(currentNode) && !currentNodeIsContaining && hasFixedPositionAncestor(element, currentNode);\n if (shouldDropCurrentNode) {\n // Drop non-containing blocks.\n result = result.filter(ancestor => ancestor !== currentNode);\n } else {\n // Record last containing block for next iteration.\n currentContainingBlockComputedStyle = computedStyle;\n }\n currentNode = getParentNode(currentNode);\n }\n cache.set(element, result);\n return result;\n}\n\n// Gets the maximum area that the element is visible in due to any number of\n// clipping ancestors.\nfunction getClippingRect(_ref) {\n let {\n element,\n boundary,\n rootBoundary,\n strategy\n } = _ref;\n const elementClippingAncestors = boundary === 'clippingAncestors' ? isTopLayer(element) ? [] : getClippingElementAncestors(element, this._c) : [].concat(boundary);\n const clippingAncestors = [...elementClippingAncestors, rootBoundary];\n const firstClippingAncestor = clippingAncestors[0];\n const clippingRect = clippingAncestors.reduce((accRect, clippingAncestor) => {\n const rect = getClientRectFromClippingAncestor(element, clippingAncestor, strategy);\n accRect.top = max(rect.top, accRect.top);\n accRect.right = min(rect.right, accRect.right);\n accRect.bottom = min(rect.bottom, accRect.bottom);\n accRect.left = max(rect.left, accRect.left);\n return accRect;\n }, getClientRectFromClippingAncestor(element, firstClippingAncestor, strategy));\n return {\n width: clippingRect.right - clippingRect.left,\n height: clippingRect.bottom - clippingRect.top,\n x: clippingRect.left,\n y: clippingRect.top\n };\n}\n\nfunction getDimensions(element) {\n const {\n width,\n height\n } = getCssDimensions(element);\n return {\n width,\n height\n };\n}\n\nfunction getRectRelativeToOffsetParent(element, offsetParent, strategy) {\n const isOffsetParentAnElement = isHTMLElement(offsetParent);\n const documentElement = getDocumentElement(offsetParent);\n const isFixed = strategy === 'fixed';\n const rect = getBoundingClientRect(element, true, isFixed, offsetParent);\n let scroll = {\n scrollLeft: 0,\n scrollTop: 0\n };\n const offsets = createCoords(0);\n\n // If the <body> scrollbar appears on the left (e.g. RTL systems). Use\n // Firefox with layout.scrollbar.side = 3 in about:config to test this.\n function setLeftRTLScrollbarOffset() {\n offsets.x = getWindowScrollBarX(documentElement);\n }\n if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {\n if (getNodeName(offsetParent) !== 'body' || isOverflowElement(documentElement)) {\n scroll = getNodeScroll(offsetParent);\n }\n if (isOffsetParentAnElement) {\n const offsetRect = getBoundingClientRect(offsetParent, true, isFixed, offsetParent);\n offsets.x = offsetRect.x + offsetParent.clientLeft;\n offsets.y = offsetRect.y + offsetParent.clientTop;\n } else if (documentElement) {\n setLeftRTLScrollbarOffset();\n }\n }\n if (isFixed && !isOffsetParentAnElement && documentElement) {\n setLeftRTLScrollbarOffset();\n }\n const htmlOffset = documentElement && !isOffsetParentAnElement && !isFixed ? getHTMLOffset(documentElement, scroll) : createCoords(0);\n const x = rect.left + scroll.scrollLeft - offsets.x - htmlOffset.x;\n const y = rect.top + scroll.scrollTop - offsets.y - htmlOffset.y;\n return {\n x,\n y,\n width: rect.width,\n height: rect.height\n };\n}\n\nfunction isStaticPositioned(element) {\n return getComputedStyle$1(element).position === 'static';\n}\n\nfunction getTrueOffsetParent(element, polyfill) {\n if (!isHTMLElement(element) || getComputedStyle$1(element).position === 'fixed') {\n return null;\n }\n if (polyfill) {\n return polyfill(element);\n }\n let rawOffsetParent = element.offsetParent;\n\n // Firefox returns the <html> element as the offsetParent if it's non-static,\n // while Chrome and Safari return the <body> element. The <body> element must\n // be used to perform the correct calculations even if the <html> element is\n // non-static.\n if (getDocumentElement(element) === rawOffsetParent) {\n rawOffsetParent = rawOffsetParent.ownerDocument.body;\n }\n return rawOffsetParent;\n}\n\n// Gets the closest ancestor positioned element. Handles some edge cases,\n// such as table ancestors and cross browser bugs.\nfunction getOffsetParent(element, polyfill) {\n const win = getWindow(element);\n if (isTopLayer(element)) {\n return win;\n }\n if (!isHTMLElement(element)) {\n let svgOffsetParent = getParentNode(element);\n while (svgOffsetParent && !isLastTraversableNode(svgOffsetParent)) {\n if (isElement(svgOffsetParent) && !isStaticPositioned(svgOffsetParent)) {\n return svgOffsetParent;\n }\n svgOffsetParent = getParentNode(svgOffsetParent);\n }\n return win;\n }\n let offsetParent = getTrueOffsetParent(element, polyfill);\n while (offsetParent && isTableElement(offsetParent) && isStaticPositioned(offsetParent)) {\n offsetParent = getTrueOffsetParent(offsetParent, polyfill);\n }\n if (offsetParent && isLastTraversableNode(offsetParent) && isStaticPositioned(offsetParent) && !isContainingBlock(offsetParent)) {\n return win;\n }\n return offsetParent || getContainingBlock(element) || win;\n}\n\nconst getElementRects = async function (data) {\n const getOffsetParentFn = this.getOffsetParent || getOffsetParent;\n const getDimensionsFn = this.getDimensions;\n const floatingDimensions = await getDimensionsFn(data.floating);\n return {\n reference: getRectRelativeToOffsetParent(data.reference, await getOffsetParentFn(data.floating), data.strategy),\n floating: {\n x: 0,\n y: 0,\n width: floatingDimensions.width,\n height: floatingDimensions.height\n }\n };\n};\n\nfunction isRTL(element) {\n return getComputedStyle$1(element).direction === 'rtl';\n}\n\nconst platform = {\n convertOffsetParentRelativeRectToViewportRelativeRect,\n getDocumentElement,\n getClippingRect,\n getOffsetParent,\n getElementRects,\n getClientRects,\n getDimensions,\n getScale,\n isElement,\n isRTL\n};\n\nfunction rectsAreEqual(a, b) {\n return a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height;\n}\n\n// https://samthor.au/2021/observing-dom/\nfunction observeMove(element, onMove) {\n let io = null;\n let timeoutId;\n const root = getDocumentElement(element);\n function cleanup() {\n var _io;\n clearTimeout(timeoutId);\n (_io = io) == null || _io.disconnect();\n io = null;\n }\n function refresh(skip, threshold) {\n if (skip === void 0) {\n skip = false;\n }\n if (threshold === void 0) {\n threshold = 1;\n }\n cleanup();\n const elementRectForRootMargin = element.getBoundingClientRect();\n const {\n left,\n top,\n width,\n height\n } = elementRectForRootMargin;\n if (!skip) {\n onMove();\n }\n if (!width || !height) {\n return;\n }\n const insetTop = floor(top);\n const insetRight = floor(root.clientWidth - (left + width));\n const insetBottom = floor(root.clientHeight - (top + height));\n const insetLeft = floor(left);\n const rootMargin = -insetTop + \"px \" + -insetRight + \"px \" + -insetBottom + \"px \" + -insetLeft + \"px\";\n const options = {\n rootMargin,\n threshold: max(0, min(1, threshold)) || 1\n };\n let isFirstUpdate = true;\n function handleObserve(entries) {\n const ratio = entries[0].intersectionRatio;\n if (ratio !== threshold) {\n if (!isFirstUpdate) {\n return refresh();\n }\n if (!ratio) {\n // If the reference is clipped, the ratio is 0. Throttle the refresh\n // to prevent an infinite loop of updates.\n timeoutId = setTimeout(() => {\n refresh(false, 1e-7);\n }, 1000);\n } else {\n refresh(false, ratio);\n }\n }\n if (ratio === 1 && !rectsAreEqual(elementRectForRootMargin, element.getBoundingClientRect())) {\n // It's possible that even though the ratio is reported as 1, the\n // element is not actually fully within the IntersectionObserver's root\n // area anymore. This can happen under performance constraints. This may\n // be a bug in the browser's IntersectionObserver implementation. To\n // work around this, we compare the element's bounding rect now with\n // what it was at the time we created the IntersectionObserver. If they\n // are not equal then the element moved, so we refresh.\n refresh();\n }\n isFirstUpdate = false;\n }\n\n // Older browsers don't support a `document` as the root and will throw an\n // error.\n try {\n io = new IntersectionObserver(handleObserve, {\n ...options,\n // Handle <iframe>s\n root: root.ownerDocument\n });\n } catch (_e) {\n io = new IntersectionObserver(handleObserve, options);\n }\n io.observe(element);\n }\n refresh(true);\n return cleanup;\n}\n\n/**\n * Automatically updates the position of the floating element when necessary.\n * Should only be called when the floating element is mounted on the DOM or\n * visible on the screen.\n * @returns cleanup function that should be invoked when the floating element is\n * removed from the DOM or hidden from the screen.\n * @see https://floating-ui.com/docs/autoUpdate\n */\nfunction autoUpdate(reference, floating, update, options) {\n if (options === void 0) {\n options = {};\n }\n const {\n ancestorScroll = true,\n ancestorResize = true,\n elementResize = typeof ResizeObserver === 'function',\n layoutShift = typeof IntersectionObserver === 'function',\n animationFrame = false\n } = options;\n const referenceEl = unwrapElement(reference);\n const ancestors = ancestorScroll || ancestorResize ? [...(referenceEl ? getOverflowAncestors(referenceEl) : []), ...getOverflowAncestors(floating)] : [];\n ancestors.forEach(ancestor => {\n ancestorScroll && ancestor.addEventListener('scroll', update, {\n passive: true\n });\n ancestorResize && ancestor.addEventListener('resize', update);\n });\n const cleanupIo = referenceEl && layoutShift ? observeMove(referenceEl, update) : null;\n let reobserveFrame = -1;\n let resizeObserver = null;\n if (elementResize) {\n resizeObserver = new ResizeObserver(_ref => {\n let [firstEntry] = _ref;\n if (firstEntry && firstEntry.target === referenceEl && resizeObserver) {\n // Prevent update loops when using the `size` middleware.\n // https://github.com/floating-ui/floating-ui/issues/1740\n resizeObserver.unobserve(floating);\n cancelAnimationFrame(reobserveFrame);\n reobserveFrame = requestAnimationFrame(() => {\n var _resizeObserver;\n (_resizeObserver = resizeObserver) == null || _resizeObserver.observe(floating);\n });\n }\n update();\n });\n if (referenceEl && !animationFrame) {\n resizeObserver.observe(referenceEl);\n }\n resizeObserver.observe(floating);\n }\n let frameId;\n let prevRefRect = animationFrame ? getBoundingClientRect(reference) : null;\n if (animationFrame) {\n frameLoop();\n }\n function frameLoop() {\n const nextRefRect = getBoundingClientRect(reference);\n if (prevRefRect && !rectsAreEqual(prevRefRect, nextRefRect)) {\n update();\n }\n prevRefRect = nextRefRect;\n frameId = requestAnimationFrame(frameLoop);\n }\n update();\n return () => {\n var _resizeObserver2;\n ancestors.forEach(ancestor => {\n ancestorScroll && ancestor.removeEventListener('scroll', update);\n ancestorResize && ancestor.removeEventListener('resize', update);\n });\n cleanupIo == null || cleanupIo();\n (_resizeObserver2 = resizeObserver) == null || _resizeObserver2.disconnect();\n resizeObserver = null;\n if (animationFrame) {\n cancelAnimationFrame(frameId);\n }\n };\n}\n\n/**\n * Resolves with an object of overflow side offsets that determine how much the\n * element is overflowing a given clipping boundary on each side.\n * - positive = overflowing the boundary by that number of pixels\n * - negative = how many pixels left before it will overflow\n * - 0 = lies flush with the boundary\n * @see https://floating-ui.com/docs/detectOverflow\n */\nconst detectOverflow = detectOverflow$1;\n\n/**\n * Modifies the placement by translating the floating element along the\n * specified axes.\n * A number (shorthand for `mainAxis` or distance), or an axes configuration\n * object may be passed.\n * @see https://floating-ui.com/docs/offset\n */\nconst offset = offset$1;\n\n/**\n * Optimizes the visibility of the floating element by choosing the placement\n * that has the most space available automatically, without needing to specify a\n * preferred placement. Alternative to `flip`.\n * @see https://floating-ui.com/docs/autoPlacement\n */\nconst autoPlacement = autoPlacement$1;\n\n/**\n * Optimizes the visibility of the floating element by shifting it in order to\n * keep it in view when it will overflow the clipping boundary.\n * @see https://floating-ui.com/docs/shift\n */\nconst shift = shift$1;\n\n/**\n * Optimizes the visibility of the floating element by flipping the `placement`\n * in order to keep it in view when the preferred placement(s) will overflow the\n * clipping boundary. Alternative to `autoPlacement`.\n * @see https://floating-ui.com/docs/flip\n */\nconst flip = flip$1;\n\n/**\n * Provides data that allows you to change the size of the floating element —\n * for instance, prevent it from overflowing the clipping boundary or match the\n * width of the reference element.\n * @see https://floating-ui.com/docs/size\n */\nconst size = size$1;\n\n/**\n * Provides data to hide the floating element in applicable situations, such as\n * when it is not in the same clipping context as the reference element.\n * @see https://floating-ui.com/docs/hide\n */\nconst hide = hide$1;\n\n/**\n * Provides data to position an inner element of the floating element so that it\n * appears centered to the reference element.\n * @see https://floating-ui.com/docs/arrow\n */\nconst arrow = arrow$1;\n\n/**\n * Provides improved positioning for inline reference elements that can span\n * over multiple lines, such as hyperlinks or range selections.\n * @see https://floating-ui.com/docs/inline\n */\nconst inline = inline$1;\n\n/**\n * Built-in `limiter` that will stop `shift()` at a certain point.\n */\nconst limitShift = limitShift$1;\n\n/**\n * Computes the `x` and `y` coordinates that will place the floating element\n * next to a given reference element.\n */\nconst computePosition = (reference, floating, options) => {\n // This caches the expensive `getClippingElementAncestors` function so that\n // multiple lifecycle resets re-use the same result. It only lives for a\n // single call. If other functions become expensive, we can add them as well.\n const cache = new Map();\n const mergedOptions = {\n platform,\n ...options\n };\n const platformWithCache = {\n ...mergedOptions.platform,\n _c: cache\n };\n return computePosition$1(reference, floating, {\n ...mergedOptions,\n platform: platformWithCache\n });\n};\n\nexport { arrow, autoPlacement, autoUpdate, computePosition, detectOverflow, flip, hide, inline, limitShift, offset, platform, shift, size };\n","import { computePosition, arrow as arrow$2, autoPlacement as autoPlacement$1, flip as flip$1, hide as hide$1, inline as inline$1, limitShift as limitShift$1, offset as offset$1, shift as shift$1, size as size$1 } from '@floating-ui/dom';\nexport { autoUpdate, computePosition, detectOverflow, getOverflowAncestors, platform } from '@floating-ui/dom';\nimport * as React from 'react';\nimport { useLayoutEffect } from 'react';\nimport * as ReactDOM from 'react-dom';\n\nvar isClient = typeof document !== 'undefined';\n\nvar noop = function noop() {};\nvar index = isClient ? useLayoutEffect : noop;\n\n// Fork of `fast-deep-equal` that only does the comparisons we need and compares\n// functions\nfunction deepEqual(a, b) {\n if (a === b) {\n return true;\n }\n if (typeof a !== typeof b) {\n return false;\n }\n if (typeof a === 'function' && a.toString() === b.toString()) {\n return true;\n }\n let length;\n let i;\n let keys;\n if (a && b && typeof a === 'object') {\n if (Array.isArray(a)) {\n length = a.length;\n if (length !== b.length) return false;\n for (i = length; i-- !== 0;) {\n if (!deepEqual(a[i], b[i])) {\n return false;\n }\n }\n return true;\n }\n keys = Object.keys(a);\n length = keys.length;\n if (length !== Object.keys(b).length) {\n return false;\n }\n for (i = length; i-- !== 0;) {\n if (!{}.hasOwnProperty.call(b, keys[i])) {\n return false;\n }\n }\n for (i = length; i-- !== 0;) {\n const key = keys[i];\n if (key === '_owner' && a.$$typeof) {\n continue;\n }\n if (!deepEqual(a[key], b[key])) {\n return false;\n }\n }\n return true;\n }\n return a !== a && b !== b;\n}\n\nfunction getDPR(element) {\n if (typeof window === 'undefined') {\n return 1;\n }\n const win = element.ownerDocument.defaultView || window;\n return win.devicePixelRatio || 1;\n}\n\nfunction roundByDPR(element, value) {\n const dpr = getDPR(element);\n return Math.round(value * dpr) / dpr;\n}\n\nfunction useLatestRef(value) {\n const ref = React.useRef(value);\n index(() => {\n ref.current = value;\n });\n return ref;\n}\n\n/**\n * Provides data to position a floating element.\n * @see https://floating-ui.com/docs/useFloating\n */\nfunction useFloating(options) {\n if (options === void 0) {\n options = {};\n }\n const {\n placement = 'bottom',\n strategy = 'absolute',\n middleware = [],\n platform,\n elements: {\n reference: externalReference,\n floating: externalFloating\n } = {},\n transform = true,\n whileElementsMounted,\n open\n } = options;\n const [data, setData] = React.useState({\n x: 0,\n y: 0,\n strategy,\n placement,\n middlewareData: {},\n isPositioned: false\n });\n const [latestMiddleware, setLatestMiddleware] = React.useState(middleware);\n if (!deepEqual(latestMiddleware, middleware)) {\n setLatestMiddleware(middleware);\n }\n const [_reference, _setReference] = React.useState(null);\n const [_floating, _setFloating] = React.useState(null);\n const setReference = React.useCallback(node => {\n if (node !== referenceRef.current) {\n referenceRef.current = node;\n _setReference(node);\n }\n }, []);\n const setFloating = React.useCallback(node => {\n if (node !== floatingRef.current) {\n floatingRef.current = node;\n _setFloating(node);\n }\n }, []);\n const referenceEl = externalReference || _reference;\n const floatingEl = externalFloating || _floating;\n const referenceRef = React.useRef(null);\n const floatingRef = React.useRef(null);\n const dataRef = React.useRef(data);\n const hasWhileElementsMounted = whileElementsMounted != null;\n const whileElementsMountedRef = useLatestRef(whileElementsMounted);\n const platformRef = useLatestRef(platform);\n const openRef = useLatestRef(open);\n const update = React.useCallback(() => {\n if (!referenceRef.current || !floatingRef.current) {\n return;\n }\n const config = {\n placement,\n strategy,\n middleware: latestMiddleware\n };\n if (platformRef.current) {\n config.platform = platformRef.current;\n }\n computePosition(referenceRef.current, floatingRef.current, config).then(data => {\n const fullData = {\n ...data,\n // The floating element's position may be recomputed while it's closed\n // but still mounted (such as when transitioning out). To ensure\n // `isPositioned` will be `false` initially on the next open, avoid\n // setting it to `true` when `open === false` (must be specified).\n isPositioned: openRef.current !== false\n };\n if (isMountedRef.current && !deepEqual(dataRef.current, fullData)) {\n dataRef.current = fullData;\n ReactDOM.flushSync(() => {\n setData(fullData);\n });\n }\n });\n }, [latestMiddleware, placement, strategy, platformRef, openRef]);\n index(() => {\n if (open === false && dataRef.current.isPositioned) {\n dataRef.current.isPositioned = false;\n setData(data => ({\n ...data,\n isPositioned: false\n }));\n }\n }, [open]);\n const isMountedRef = React.useRef(false);\n index(() => {\n isMountedRef.current = true;\n return () => {\n isMountedRef.current = false;\n };\n }, []);\n index(() => {\n if (referenceEl) referenceRef.current = referenceEl;\n if (floatingEl) floatingRef.current = floatingEl;\n if (referenceEl && floatingEl) {\n if (whileElementsMountedRef.current) {\n return whileElementsMountedRef.current(referenceEl, floatingEl, update);\n }\n update();\n }\n }, [referenceEl, floatingEl, update, whileElementsMountedRef, hasWhileElementsMounted]);\n const refs = React.useMemo(() => ({\n reference: referenceRef,\n floating: floatingRef,\n setReference,\n setFloating\n }), [setReference, setFloating]);\n const elements = React.useMemo(() => ({\n reference: referenceEl,\n floating: floatingEl\n }), [referenceEl, floatingEl]);\n const floatingStyles = React.useMemo(() => {\n const initialStyles = {\n position: strategy,\n left: 0,\n top: 0\n };\n if (!elements.floating) {\n return initialStyles;\n }\n const x = roundByDPR(elements.floating, data.x);\n const y = roundByDPR(elements.floating, data.y);\n if (transform) {\n return {\n ...initialStyles,\n transform: \"translate(\" + x + \"px, \" + y + \"px)\",\n ...(getDPR(elements.floating) >= 1.5 && {\n willChange: 'transform'\n })\n };\n }\n return {\n position: strategy,\n left: x,\n top: y\n };\n }, [strategy, transform, elements.floating, data.x, data.y]);\n return React.useMemo(() => ({\n ...data,\n update,\n refs,\n elements,\n floatingStyles\n }), [data, update, refs, elements, floatingStyles]);\n}\n\n/**\n * Provides data to position an inner element of the floating element so that it\n * appears centered to the reference element.\n * This wraps the core `arrow` middleware to allow React refs as the element.\n * @see https://floating-ui.com/docs/arrow\n */\nconst arrow$1 = options => {\n function isRef(value) {\n return {}.hasOwnProperty.call(value, 'current');\n }\n return {\n name: 'arrow',\n options,\n fn(state) {\n const {\n element,\n padding\n } = typeof options === 'function' ? options(state) : options;\n if (element && isRef(element)) {\n if (element.current != null) {\n return arrow$2({\n element: element.current,\n padding\n }).fn(state);\n }\n return {};\n }\n if (element) {\n return arrow$2({\n element,\n padding\n }).fn(state);\n }\n return {};\n }\n };\n};\n\n/**\n * Modifies the placement by translating the floating element along the\n * specified axes.\n * A number (shorthand for `mainAxis` or distance), or an axes configuration\n * object may be passed.\n * @see https://floating-ui.com/docs/offset\n */\nconst offset = (options, deps) => ({\n ...offset$1(options),\n options: [options, deps]\n});\n\n/**\n * Optimizes the visibility of the floating element by shifting it in order to\n * keep it in view when it will overflow the clipping boundary.\n * @see https://floating-ui.com/docs/shift\n */\nconst shift = (options, deps) => ({\n ...shift$1(options),\n options: [options, deps]\n});\n\n/**\n * Built-in `limiter` that will stop `shift()` at a certain point.\n */\nconst limitShift = (options, deps) => ({\n ...limitShift$1(options),\n options: [options, deps]\n});\n\n/**\n * Optimizes the visibility of the floating element by flipping the `placement`\n * in order to keep it in view when the preferred placement(s) will overflow the\n * clipping boundary. Alternative to `autoPlacement`.\n * @see https://floating-ui.com/docs/flip\n */\nconst flip = (options, deps) => ({\n ...flip$1(options),\n options: [options, deps]\n});\n\n/**\n * Provides data that allows you to change the size of the floating element —\n * for instance, prevent it from overflowing the clipping boundary or match the\n * width of the reference element.\n * @see https://floating-ui.com/docs/size\n */\nconst size = (options, deps) => ({\n ...size$1(options),\n options: [options, deps]\n});\n\n/**\n * Optimizes the visibility of the floating element by choosing the placement\n * that has the most space available automatically, without needing to specify a\n * preferred placement. Alternative to `flip`.\n * @see https://floating-ui.com/docs/autoPlacement\n */\nconst autoPlacement = (options, deps) => ({\n ...autoPlacement$1(options),\n options: [options, deps]\n});\n\n/**\n * Provides data to hide the floating element in applicable situations, such as\n * when it is not in the same clipping context as the reference element.\n * @see https://floating-ui.com/docs/hide\n */\nconst hide = (options, deps) => ({\n ...hide$1(options),\n options: [options, deps]\n});\n\n/**\n * Provides improved positioning for inline reference elements that can span\n * over multiple lines, such as hyperlinks or range selections.\n * @see https://floating-ui.com/docs/inline\n */\nconst inline = (options, deps) => ({\n ...inline$1(options),\n options: [options, deps]\n});\n\n/**\n * Provides data to position an inner element of the floating element so that it\n * appears centered to the reference element.\n * This wraps the core `arrow` middleware to allow React refs as the element.\n * @see https://floating-ui.com/docs/arrow\n */\nconst arrow = (options, deps) => ({\n ...arrow$1(options),\n options: [options, deps]\n});\n\nexport { arrow, autoPlacement, flip, hide, inline, limitShift, offset, shift, size, useFloating };\n","import * as React from 'react';\nimport { useModernLayoutEffect, useEffectEvent, getMinListIndex, getMaxListIndex, createGridCellMap, isListIndexDisabled, getGridNavigatedIndex, getGridCellIndexOfCorner, getGridCellIndices, findNonDisabledListIndex, isIndexOutOfListBounds, useLatestRef, getDocument as getDocument$1, isMouseLikePointerType, contains as contains$1, isSafari, enableFocusInside, isOutsideEvent, getPreviousTabbable, getNextTabbable, disableFocusInside, isTypeableCombobox, getFloatingFocusElement, getTabbableOptions, getNodeAncestors, activeElement, getNodeChildren as getNodeChildren$1, stopEvent, getTarget as getTarget$1, isVirtualClick, isVirtualPointerEvent, getPlatform, isTypeableElement, isReactEvent, isRootElement, isEventTargetWithin, matchesFocusVisible, isMac, getDeepestNode, getUserAgent } from '@floating-ui/react/utils';\nimport { jsx, jsxs, Fragment } from 'react/jsx-runtime';\nimport { getComputedStyle, isElement, isShadowRoot, getNodeName, isNode, isHTMLElement, getWindow, isLastTraversableNode, getParentNode, isWebKit } from '@floating-ui/utils/dom';\nimport { tabbable, isTabbable, focusable } from 'tabbable';\nimport * as ReactDOM from 'react-dom';\nimport { getOverflowAncestors, useFloating as useFloating$1, offset } from '@floating-ui/react-dom';\nexport { arrow, autoPlacement, autoUpdate, computePosition, detectOverflow, flip, getOverflowAncestors, hide, inline, limitShift, offset, platform, shift, size } from '@floating-ui/react-dom';\nimport { evaluate, max, round, min } from '@floating-ui/utils';\n\n/**\n * Merges an array of refs into a single memoized callback ref or `null`.\n * @see https://floating-ui.com/docs/react-utils#usemergerefs\n */\nfunction useMergeRefs(refs) {\n const cleanupRef = React.useRef(undefined);\n const refEffect = React.useCallback(instance => {\n const cleanups = refs.map(ref => {\n if (ref == null) {\n return;\n }\n if (typeof ref === 'function') {\n const refCallback = ref;\n const refCleanup = refCallback(instance);\n return typeof refCleanup === 'function' ? refCleanup : () => {\n refCallback(null);\n };\n }\n ref.current = instance;\n return () => {\n ref.current = null;\n };\n });\n return () => {\n cleanups.forEach(refCleanup => refCleanup == null ? void 0 : refCleanup());\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, refs);\n return React.useMemo(() => {\n if (refs.every(ref => ref == null)) {\n return null;\n }\n return value => {\n if (cleanupRef.current) {\n cleanupRef.current();\n cleanupRef.current = undefined;\n }\n if (value != null) {\n cleanupRef.current = refEffect(value);\n }\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, refs);\n}\n\nfunction sortByDocumentPosition(a, b) {\n const position = a.compareDocumentPosition(b);\n if (position & Node.DOCUMENT_POSITION_FOLLOWING || position & Node.DOCUMENT_POSITION_CONTAINED_BY) {\n return -1;\n }\n if (position & Node.DOCUMENT_POSITION_PRECEDING || position & Node.DOCUMENT_POSITION_CONTAINS) {\n return 1;\n }\n return 0;\n}\nconst FloatingListContext = /*#__PURE__*/React.createContext({\n register: () => {},\n unregister: () => {},\n map: /*#__PURE__*/new Map(),\n elementsRef: {\n current: []\n }\n});\n/**\n * Provides context for a list of items within the floating element.\n * @see https://floating-ui.com/docs/FloatingList\n */\nfunction FloatingList(props) {\n const {\n children,\n elementsRef,\n labelsRef\n } = props;\n const [nodes, setNodes] = React.useState(() => new Set());\n const register = React.useCallback(node => {\n setNodes(prevSet => new Set(prevSet).add(node));\n }, []);\n const unregister = React.useCallback(node => {\n setNodes(prevSet => {\n const set = new Set(prevSet);\n set.delete(node);\n return set;\n });\n }, []);\n const map = React.useMemo(() => {\n const newMap = new Map();\n const sortedNodes = Array.from(nodes.keys()).sort(sortByDocumentPosition);\n sortedNodes.forEach((node, index) => {\n newMap.set(node, index);\n });\n return newMap;\n }, [nodes]);\n return /*#__PURE__*/jsx(FloatingListContext.Provider, {\n value: React.useMemo(() => ({\n register,\n unregister,\n map,\n elementsRef,\n labelsRef\n }), [register, unregister, map, elementsRef, labelsRef]),\n children: children\n });\n}\n/**\n * Used to register a list item and its index (DOM position) in the\n * `FloatingList`.\n * @see https://floating-ui.com/docs/FloatingList#uselistitem\n */\nfunction useListItem(props) {\n if (props === void 0) {\n props = {};\n }\n const {\n label\n } = props;\n const {\n register,\n unregister,\n map,\n elementsRef,\n labelsRef\n } = React.useContext(FloatingListContext);\n const [index, setIndex] = React.useState(null);\n const componentRef = React.useRef(null);\n const ref = React.useCallback(node => {\n componentRef.current = node;\n if (index !== null) {\n elementsRef.current[index] = node;\n if (labelsRef) {\n var _node$textContent;\n const isLabelDefined = label !== undefined;\n labelsRef.current[index] = isLabelDefined ? label : (_node$textContent = node == null ? void 0 : node.textContent) != null ? _node$textContent : null;\n }\n }\n }, [index, elementsRef, labelsRef, label]);\n useModernLayoutEffect(() => {\n const node = componentRef.current;\n if (node) {\n register(node);\n return () => {\n unregister(node);\n };\n }\n }, [register, unregister]);\n useModernLayoutEffect(() => {\n const index = componentRef.current ? map.get(componentRef.current) : null;\n if (index != null) {\n setIndex(index);\n }\n }, [map]);\n return React.useMemo(() => ({\n ref,\n index: index == null ? -1 : index\n }), [index, ref]);\n}\n\nconst FOCUSABLE_ATTRIBUTE = 'data-floating-ui-focusable';\nconst ACTIVE_KEY = 'active';\nconst SELECTED_KEY = 'selected';\nconst ARROW_LEFT = 'ArrowLeft';\nconst ARROW_RIGHT = 'ArrowRight';\nconst ARROW_UP = 'ArrowUp';\nconst ARROW_DOWN = 'ArrowDown';\n\nfunction renderJsx(render, computedProps) {\n if (typeof render === 'function') {\n return render(computedProps);\n }\n if (render) {\n return /*#__PURE__*/React.cloneElement(render, computedProps);\n }\n return /*#__PURE__*/jsx(\"div\", {\n ...computedProps\n });\n}\nconst CompositeContext = /*#__PURE__*/React.createContext({\n activeIndex: 0,\n onNavigate: () => {}\n});\nconst horizontalKeys = [ARROW_LEFT, ARROW_RIGHT];\nconst verticalKeys = [ARROW_UP, ARROW_DOWN];\nconst allKeys = [...horizontalKeys, ...verticalKeys];\n\n/**\n * Creates a single tab stop whose items are navigated by arrow keys, which\n * provides list navigation outside of floating element contexts.\n *\n * This is useful to enable navigation of a list of items that aren’t part of a\n * floating element. A menubar is an example of a composite, with each reference\n * element being an item.\n * @see https://floating-ui.com/docs/Composite\n */\nconst Composite = /*#__PURE__*/React.forwardRef(function Composite(props, forwardedRef) {\n const {\n render,\n orientation = 'both',\n loop = true,\n rtl = false,\n cols = 1,\n disabledIndices,\n activeIndex: externalActiveIndex,\n onNavigate: externalSetActiveIndex,\n itemSizes,\n dense = false,\n ...domProps\n } = props;\n const [internalActiveIndex, internalSetActiveIndex] = React.useState(0);\n const activeIndex = externalActiveIndex != null ? externalActiveIndex : internalActiveIndex;\n const onNavigate = useEffectEvent(externalSetActiveIndex != null ? externalSetActiveIndex : internalSetActiveIndex);\n const elementsRef = React.useRef([]);\n const renderElementProps = render && typeof render !== 'function' ? render.props : {};\n const contextValue = React.useMemo(() => ({\n activeIndex,\n onNavigate\n }), [activeIndex, onNavigate]);\n const isGrid = cols > 1;\n function handleKeyDown(event) {\n if (!allKeys.includes(event.key)) return;\n let nextIndex = activeIndex;\n const minIndex = getMinListIndex(elementsRef, disabledIndices);\n const maxIndex = getMaxListIndex(elementsRef, disabledIndices);\n const horizontalEndKey = rtl ? ARROW_LEFT : ARROW_RIGHT;\n const horizontalStartKey = rtl ? ARROW_RIGHT : ARROW_LEFT;\n if (isGrid) {\n const sizes = itemSizes || Array.from({\n length: elementsRef.current.length\n }, () => ({\n width: 1,\n height: 1\n }));\n // To calculate movements on the grid, we use hypothetical cell indices\n // as if every item was 1x1, then convert back to real indices.\n const cellMap = createGridCellMap(sizes, cols, dense);\n const minGridIndex = cellMap.findIndex(index => index != null && !isListIndexDisabled(elementsRef, index, disabledIndices));\n // last enabled index\n const maxGridIndex = cellMap.reduce((foundIndex, index, cellIndex) => index != null && !isListIndexDisabled(elementsRef, index, disabledIndices) ? cellIndex : foundIndex, -1);\n const maybeNextIndex = cellMap[getGridNavigatedIndex({\n current: cellMap.map(itemIndex => itemIndex ? elementsRef.current[itemIndex] : null)\n }, {\n event,\n orientation,\n loop,\n rtl,\n cols,\n // treat undefined (empty grid spaces) as disabled indices so we\n // don't end up in them\n disabledIndices: getGridCellIndices([...((typeof disabledIndices !== 'function' ? disabledIndices : null) || elementsRef.current.map((_, index) => isListIndexDisabled(elementsRef, index, disabledIndices) ? index : undefined)), undefined], cellMap),\n minIndex: minGridIndex,\n maxIndex: maxGridIndex,\n prevIndex: getGridCellIndexOfCorner(activeIndex > maxIndex ? minIndex : activeIndex, sizes, cellMap, cols,\n // use a corner matching the edge closest to the direction we're\n // moving in so we don't end up in the same item. Prefer\n // top/left over bottom/right.\n event.key === ARROW_DOWN ? 'bl' : event.key === horizontalEndKey ? 'tr' : 'tl')\n })];\n if (maybeNextIndex != null) {\n nextIndex = maybeNextIndex;\n }\n }\n const toEndKeys = {\n horizontal: [horizontalEndKey],\n vertical: [ARROW_DOWN],\n both: [horizontalEndKey, ARROW_DOWN]\n }[orientation];\n const toStartKeys = {\n horizontal: [horizontalStartKey],\n vertical: [ARROW_UP],\n both: [horizontalStartKey, ARROW_UP]\n }[orientation];\n const preventedKeys = isGrid ? allKeys : {\n horizontal: horizontalKeys,\n vertical: verticalKeys,\n both: allKeys\n }[orientation];\n if (nextIndex === activeIndex && [...toEndKeys, ...toStartKeys].includes(event.key)) {\n if (loop && nextIndex === maxIndex && toEndKeys.includes(event.key)) {\n nextIndex = minIndex;\n } else if (loop && nextIndex === minIndex && toStartKeys.includes(event.key)) {\n nextIndex = maxIndex;\n } else {\n nextIndex = findNonDisabledListIndex(elementsRef, {\n startingIndex: nextIndex,\n decrement: toStartKeys.includes(event.key),\n disabledIndices\n });\n }\n }\n if (nextIndex !== activeIndex && !isIndexOutOfListBounds(elementsRef, nextIndex)) {\n var _elementsRef$current$;\n event.stopPropagation();\n if (preventedKeys.includes(event.key)) {\n event.preventDefault();\n }\n onNavigate(nextIndex);\n (_elementsRef$current$ = elementsRef.current[nextIndex]) == null || _elementsRef$current$.focus();\n }\n }\n const computedProps = {\n ...domProps,\n ...renderElementProps,\n ref: forwardedRef,\n 'aria-orientation': orientation === 'both' ? undefined : orientation,\n onKeyDown(e) {\n domProps.onKeyDown == null || domProps.onKeyDown(e);\n renderElementProps.onKeyDown == null || renderElementProps.onKeyDown(e);\n handleKeyDown(e);\n }\n };\n return /*#__PURE__*/jsx(CompositeContext.Provider, {\n value: contextValue,\n children: /*#__PURE__*/jsx(FloatingList, {\n elementsRef: elementsRef,\n children: renderJsx(render, computedProps)\n })\n });\n});\n/**\n * @see https://floating-ui.com/docs/Composite\n */\nconst CompositeItem = /*#__PURE__*/React.forwardRef(function CompositeItem(props, forwardedRef) {\n const {\n render,\n ...domProps\n } = props;\n const renderElementProps = render && typeof render !== 'function' ? render.props : {};\n const {\n activeIndex,\n onNavigate\n } = React.useContext(CompositeContext);\n const {\n ref,\n index\n } = useListItem();\n const mergedRef = useMergeRefs([ref, forwardedRef, renderElementProps.ref]);\n const isActive = activeIndex === index;\n const computedProps = {\n ...domProps,\n ...renderElementProps,\n ref: mergedRef,\n tabIndex: isActive ? 0 : -1,\n 'data-active': isActive ? '' : undefined,\n onFocus(e) {\n domProps.onFocus == null || domProps.onFocus(e);\n renderElementProps.onFocus == null || renderElementProps.onFocus(e);\n onNavigate(index);\n }\n };\n return renderJsx(render, computedProps);\n});\n\n// https://github.com/mui/material-ui/issues/41190#issuecomment-2040873379\nconst SafeReact = {\n ...React\n};\n\nlet serverHandoffComplete = false;\nlet count = 0;\nconst genId = () => // Ensure the id is unique with multiple independent versions of Floating UI\n// on <React 18\n\"floating-ui-\" + Math.random().toString(36).slice(2, 6) + count++;\nfunction useFloatingId() {\n const [id, setId] = React.useState(() => serverHandoffComplete ? genId() : undefined);\n useModernLayoutEffect(() => {\n if (id == null) {\n setId(genId());\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n React.useEffect(() => {\n serverHandoffComplete = true;\n }, []);\n return id;\n}\nconst useReactId = SafeReact.useId;\n\n/**\n * Uses React 18's built-in `useId()` when available, or falls back to a\n * slightly less performant (requiring a double render) implementation for\n * earlier React versions.\n * @see https://floating-ui.com/docs/react-utils#useid\n */\nconst useId = useReactId || useFloatingId;\n\nlet devMessageSet;\nif (process.env.NODE_ENV !== \"production\") {\n devMessageSet = /*#__PURE__*/new Set();\n}\nfunction warn() {\n var _devMessageSet;\n for (var _len = arguments.length, messages = new Array(_len), _key = 0; _key < _len; _key++) {\n messages[_key] = arguments[_key];\n }\n const message = \"Floating UI: \" + messages.join(' ');\n if (!((_devMessageSet = devMessageSet) != null && _devMessageSet.has(message))) {\n var _devMessageSet2;\n (_devMessageSet2 = devMessageSet) == null || _devMessageSet2.add(message);\n console.warn(message);\n }\n}\nfunction error() {\n var _devMessageSet3;\n for (var _len2 = arguments.length, messages = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n messages[_key2] = arguments[_key2];\n }\n const message = \"Floating UI: \" + messages.join(' ');\n if (!((_devMessageSet3 = devMessageSet) != null && _devMessageSet3.has(message))) {\n var _devMessageSet4;\n (_devMessageSet4 = devMessageSet) == null || _devMessageSet4.add(message);\n console.error(message);\n }\n}\n\n/**\n * Renders a pointing arrow triangle.\n * @see https://floating-ui.com/docs/FloatingArrow\n */\nconst FloatingArrow = /*#__PURE__*/React.forwardRef(function FloatingArrow(props, ref) {\n const {\n context: {\n placement,\n elements: {\n floating\n },\n middlewareData: {\n arrow,\n shift\n }\n },\n width = 14,\n height = 7,\n tipRadius = 0,\n strokeWidth = 0,\n staticOffset,\n stroke,\n d,\n style: {\n transform,\n ...restStyle\n } = {},\n ...rest\n } = props;\n if (process.env.NODE_ENV !== \"production\") {\n if (!ref) {\n warn('The `ref` prop is required for `FloatingArrow`.');\n }\n }\n const clipPathId = useId();\n const [isRTL, setIsRTL] = React.useState(false);\n\n // https://github.com/floating-ui/floating-ui/issues/2932\n useModernLayoutEffect(() => {\n if (!floating) return;\n const isRTL = getComputedStyle(floating).direction === 'rtl';\n if (isRTL) {\n setIsRTL(true);\n }\n }, [floating]);\n if (!floating) {\n return null;\n }\n const [side, alignment] = placement.split('-');\n const isVerticalSide = side === 'top' || side === 'bottom';\n let computedStaticOffset = staticOffset;\n if (isVerticalSide && shift != null && shift.x || !isVerticalSide && shift != null && shift.y) {\n computedStaticOffset = null;\n }\n\n // Strokes must be double the border width, this ensures the stroke's width\n // works as you'd expect.\n const computedStrokeWidth = strokeWidth * 2;\n const halfStrokeWidth = computedStrokeWidth / 2;\n const svgX = width / 2 * (tipRadius / -8 + 1);\n const svgY = height / 2 * tipRadius / 4;\n const isCustomShape = !!d;\n const yOffsetProp = computedStaticOffset && alignment === 'end' ? 'bottom' : 'top';\n let xOffsetProp = computedStaticOffset && alignment === 'end' ? 'right' : 'left';\n if (computedStaticOffset && isRTL) {\n xOffsetProp = alignment === 'end' ? 'left' : 'right';\n }\n const arrowX = (arrow == null ? void 0 : arrow.x) != null ? computedStaticOffset || arrow.x : '';\n const arrowY = (arrow == null ? void 0 : arrow.y) != null ? computedStaticOffset || arrow.y : '';\n const dValue = d || 'M0,0' + (\" H\" + width) + (\" L\" + (width - svgX) + \",\" + (height - svgY)) + (\" Q\" + width / 2 + \",\" + height + \" \" + svgX + \",\" + (height - svgY)) + ' Z';\n const rotation = {\n top: isCustomShape ? 'rotate(180deg)' : '',\n left: isCustomShape ? 'rotate(90deg)' : 'rotate(-90deg)',\n bottom: isCustomShape ? '' : 'rotate(180deg)',\n right: isCustomShape ? 'rotate(-90deg)' : 'rotate(90deg)'\n }[side];\n return /*#__PURE__*/jsxs(\"svg\", {\n ...rest,\n \"aria-hidden\": true,\n ref: ref,\n width: isCustomShape ? width : width + computedStrokeWidth,\n height: width,\n viewBox: \"0 0 \" + width + \" \" + (height > width ? height : width),\n style: {\n position: 'absolute',\n pointerEvents: 'none',\n [xOffsetProp]: arrowX,\n [yOffsetProp]: arrowY,\n [side]: isVerticalSide || isCustomShape ? '100%' : \"calc(100% - \" + computedStrokeWidth / 2 + \"px)\",\n transform: [rotation, transform].filter(t => !!t).join(' '),\n ...restStyle\n },\n children: [computedStrokeWidth > 0 && /*#__PURE__*/jsx(\"path\", {\n clipPath: \"url(#\" + clipPathId + \")\",\n fill: \"none\",\n stroke: stroke\n // Account for the stroke on the fill path rendered below.\n ,\n strokeWidth: computedStrokeWidth + (d ? 0 : 1),\n d: dValue\n }), /*#__PURE__*/jsx(\"path\", {\n stroke: computedStrokeWidth && !d ? rest.fill : 'none',\n d: dValue\n }), /*#__PURE__*/jsx(\"clipPath\", {\n id: clipPathId,\n children: /*#__PURE__*/jsx(\"rect\", {\n x: -halfStrokeWidth,\n y: halfStrokeWidth * (isCustomShape ? -1 : 1),\n width: width + computedStrokeWidth,\n height: width\n })\n })]\n });\n});\n\nfunction createEventEmitter() {\n const map = new Map();\n return {\n emit(event, data) {\n var _map$get;\n (_map$get = map.get(event)) == null || _map$get.forEach(listener => listener(data));\n },\n on(event, listener) {\n if (!map.has(event)) {\n map.set(event, new Set());\n }\n map.get(event).add(listener);\n },\n off(event, listener) {\n var _map$get2;\n (_map$get2 = map.get(event)) == null || _map$get2.delete(listener);\n }\n };\n}\n\nconst FloatingNodeContext = /*#__PURE__*/React.createContext(null);\nconst FloatingTreeContext = /*#__PURE__*/React.createContext(null);\n\n/**\n * Returns the parent node id for nested floating elements, if available.\n * Returns `null` for top-level floating elements.\n */\nconst useFloatingParentNodeId = () => {\n var _React$useContext;\n return ((_React$useContext = React.useContext(FloatingNodeContext)) == null ? void 0 : _React$useContext.id) || null;\n};\n\n/**\n * Returns the nearest floating tree context, if available.\n */\nconst useFloatingTree = () => React.useContext(FloatingTreeContext);\n\n/**\n * Registers a node into the `FloatingTree`, returning its id.\n * @see https://floating-ui.com/docs/FloatingTree\n */\nfunction useFloatingNodeId(customParentId) {\n const id = useId();\n const tree = useFloatingTree();\n const reactParentId = useFloatingParentNodeId();\n const parentId = customParentId || reactParentId;\n useModernLayoutEffect(() => {\n if (!id) return;\n const node = {\n id,\n parentId\n };\n tree == null || tree.addNode(node);\n return () => {\n tree == null || tree.removeNode(node);\n };\n }, [tree, id, parentId]);\n return id;\n}\n/**\n * Provides parent node context for nested floating elements.\n * @see https://floating-ui.com/docs/FloatingTree\n */\nfunction FloatingNode(props) {\n const {\n children,\n id\n } = props;\n const parentId = useFloatingParentNodeId();\n return /*#__PURE__*/jsx(FloatingNodeContext.Provider, {\n value: React.useMemo(() => ({\n id,\n parentId\n }), [id, parentId]),\n children: children\n });\n}\n/**\n * Provides context for nested floating elements when they are not children of\n * each other on the DOM.\n * This is not necessary in all cases, except when there must be explicit communication between parent and child floating elements. It is necessary for:\n * - The `bubbles` option in the `useDismiss()` Hook\n * - Nested virtual list navigation\n * - Nested floating elements that each open on hover\n * - Custom communication between parent and child floating elements\n * @see https://floating-ui.com/docs/FloatingTree\n */\nfunction FloatingTree(props) {\n const {\n children\n } = props;\n const nodesRef = React.useRef([]);\n const addNode = React.useCallback(node => {\n nodesRef.current = [...nodesRef.current, node];\n }, []);\n const removeNode = React.useCallback(node => {\n nodesRef.current = nodesRef.current.filter(n => n !== node);\n }, []);\n const [events] = React.useState(() => createEventEmitter());\n return /*#__PURE__*/jsx(FloatingTreeContext.Provider, {\n value: React.useMemo(() => ({\n nodesRef,\n addNode,\n removeNode,\n events\n }), [addNode, removeNode, events]),\n children: children\n });\n}\n\nfunction createAttribute(name) {\n return \"data-floating-ui-\" + name;\n}\n\nfunction clearTimeoutIfSet(timeoutRef) {\n if (timeoutRef.current !== -1) {\n clearTimeout(timeoutRef.current);\n timeoutRef.current = -1;\n }\n}\n\nconst safePolygonIdentifier = /*#__PURE__*/createAttribute('safe-polygon');\nfunction getDelay(value, prop, pointerType) {\n if (pointerType && !isMouseLikePointerType(pointerType)) {\n return 0;\n }\n if (typeof value === 'number') {\n return value;\n }\n if (typeof value === 'function') {\n const result = value();\n if (typeof result === 'number') {\n return result;\n }\n return result == null ? void 0 : result[prop];\n }\n return value == null ? void 0 : value[prop];\n}\nfunction getRestMs(value) {\n if (typeof value === 'function') {\n return value();\n }\n return value;\n}\n/**\n * Opens the floating element while hovering over the reference element, like\n * CSS `:hover`.\n * @see https://floating-ui.com/docs/useHover\n */\nfunction useHover(context, props) {\n if (props === void 0) {\n props = {};\n }\n const {\n open,\n onOpenChange,\n dataRef,\n events,\n elements\n } = context;\n const {\n enabled = true,\n delay = 0,\n handleClose = null,\n mouseOnly = false,\n restMs = 0,\n move = true\n } = props;\n const tree = useFloatingTree();\n const parentId = useFloatingParentNodeId();\n const handleCloseRef = useLatestRef(handleClose);\n const delayRef = useLatestRef(delay);\n const openRef = useLatestRef(open);\n const restMsRef = useLatestRef(restMs);\n const pointerTypeRef = React.useRef();\n const timeoutRef = React.useRef(-1);\n const handlerRef = React.useRef();\n const restTimeoutRef = React.useRef(-1);\n const blockMouseMoveRef = React.useRef(true);\n const performedPointerEventsMutationRef = React.useRef(false);\n const unbindMouseMoveRef = React.useRef(() => {});\n const restTimeoutPendingRef = React.useRef(false);\n const isHoverOpen = useEffectEvent(() => {\n var _dataRef$current$open;\n const type = (_dataRef$current$open = dataRef.current.openEvent) == null ? void 0 : _dataRef$current$open.type;\n return (type == null ? void 0 : type.includes('mouse')) && type !== 'mousedown';\n });\n\n // When closing before opening, clear the delay timeouts to cancel it\n // from showing.\n React.useEffect(() => {\n if (!enabled) return;\n function onOpenChange(_ref) {\n let {\n open\n } = _ref;\n if (!open) {\n clearTimeoutIfSet(timeoutRef);\n clearTimeoutIfSet(restTimeoutRef);\n blockMouseMoveRef.current = true;\n restTimeoutPendingRef.current = false;\n }\n }\n events.on('openchange', onOpenChange);\n return () => {\n events.off('openchange', onOpenChange);\n };\n }, [enabled, events]);\n React.useEffect(() => {\n if (!enabled) return;\n if (!handleCloseRef.current) return;\n if (!open) return;\n function onLeave(event) {\n if (isHoverOpen()) {\n onOpenChange(false, event, 'hover');\n }\n }\n const html = getDocument$1(elements.floating).documentElement;\n html.addEventListener('mouseleave', onLeave);\n return () => {\n html.removeEventListener('mouseleave', onLeave);\n };\n }, [elements.floating, open, onOpenChange, enabled, handleCloseRef, isHoverOpen]);\n const closeWithDelay = React.useCallback(function (event, runElseBranch, reason) {\n if (runElseBranch === void 0) {\n runElseBranch = true;\n }\n if (reason === void 0) {\n reason = 'hover';\n }\n const closeDelay = getDelay(delayRef.current, 'close', pointerTypeRef.current);\n if (closeDelay && !handlerRef.current) {\n clearTimeoutIfSet(timeoutRef);\n timeoutRef.current = window.setTimeout(() => onOpenChange(false, event, reason), closeDelay);\n } else if (runElseBranch) {\n clearTimeoutIfSet(timeoutRef);\n onOpenChange(false, event, reason);\n }\n }, [delayRef, onOpenChange]);\n const cleanupMouseMoveHandler = useEffectEvent(() => {\n unbindMouseMoveRef.current();\n handlerRef.current = undefined;\n });\n const clearPointerEvents = useEffectEvent(() => {\n if (performedPointerEventsMutationRef.current) {\n const body = getDocument$1(elements.floating).body;\n body.style.pointerEvents = '';\n body.removeAttribute(safePolygonIdentifier);\n performedPointerEventsMutationRef.current = false;\n }\n });\n const isClickLikeOpenEvent = useEffectEvent(() => {\n return dataRef.current.openEvent ? ['click', 'mousedown'].includes(dataRef.current.openEvent.type) : false;\n });\n\n // Registering the mouse events on the reference directly to bypass React's\n // delegation system. If the cursor was on a disabled element and then entered\n // the reference (no gap), `mouseenter` doesn't fire in the delegation system.\n React.useEffect(() => {\n if (!enabled) return;\n function onReferenceMouseEnter(event) {\n clearTimeoutIfSet(timeoutRef);\n blockMouseMoveRef.current = false;\n if (mouseOnly && !isMouseLikePointerType(pointerTypeRef.current) || getRestMs(restMsRef.current) > 0 && !getDelay(delayRef.current, 'open')) {\n return;\n }\n const openDelay = getDelay(delayRef.current, 'open', pointerTypeRef.current);\n if (openDelay) {\n timeoutRef.current = window.setTimeout(() => {\n if (!openRef.current) {\n onOpenChange(true, event, 'hover');\n }\n }, openDelay);\n } else if (!open) {\n onOpenChange(true, event, 'hover');\n }\n }\n function onReferenceMouseLeave(event) {\n if (isClickLikeOpenEvent()) {\n clearPointerEvents();\n return;\n }\n unbindMouseMoveRef.current();\n const doc = getDocument$1(elements.floating);\n clearTimeoutIfSet(restTimeoutRef);\n restTimeoutPendingRef.current = false;\n if (handleCloseRef.current && dataRef.current.floatingContext) {\n // Prevent clearing `onScrollMouseLeave` timeout.\n if (!open) {\n clearTimeoutIfSet(timeoutRef);\n }\n handlerRef.current = handleCloseRef.current({\n ...dataRef.current.floatingContext,\n tree,\n x: event.clientX,\n y: event.clientY,\n onClose() {\n clearPointerEvents();\n cleanupMouseMoveHandler();\n if (!isClickLikeOpenEvent()) {\n closeWithDelay(event, true, 'safe-polygon');\n }\n }\n });\n const handler = handlerRef.current;\n doc.addEventListener('mousemove', handler);\n unbindMouseMoveRef.current = () => {\n doc.removeEventListener('mousemove', handler);\n };\n return;\n }\n\n // Allow interactivity without `safePolygon` on touch devices. With a\n // pointer, a short close delay is an alternative, so it should work\n // consistently.\n const shouldClose = pointerTypeRef.current === 'touch' ? !contains$1(elements.floating, event.relatedTarget) : true;\n if (shouldClose) {\n closeWithDelay(event);\n }\n }\n\n // Ensure the floating element closes after scrolling even if the pointer\n // did not move.\n // https://github.com/floating-ui/floating-ui/discussions/1692\n function onScrollMouseLeave(event) {\n if (isClickLikeOpenEvent()) return;\n if (!dataRef.current.floatingContext) return;\n handleCloseRef.current == null || handleCloseRef.current({\n ...dataRef.current.floatingContext,\n tree,\n x: event.clientX,\n y: event.clientY,\n onClose() {\n clearPointerEvents();\n cleanupMouseMoveHandler();\n if (!isClickLikeOpenEvent()) {\n closeWithDelay(event);\n }\n }\n })(event);\n }\n function onFloatingMouseEnter() {\n clearTimeoutIfSet(timeoutRef);\n }\n function onFloatingMouseLeave(event) {\n if (!isClickLikeOpenEvent()) {\n closeWithDelay(event, false);\n }\n }\n if (isElement(elements.domReference)) {\n const reference = elements.domReference;\n const floating = elements.floating;\n if (open) {\n reference.addEventListener('mouseleave', onScrollMouseLeave);\n }\n if (move) {\n reference.addEventListener('mousemove', onReferenceMouseEnter, {\n once: true\n });\n }\n reference.addEventListener('mouseenter', onReferenceMouseEnter);\n reference.addEventListener('mouseleave', onReferenceMouseLeave);\n if (floating) {\n floating.addEventListener('mouseleave', onScrollMouseLeave);\n floating.addEventListener('mouseenter', onFloatingMouseEnter);\n floating.addEventListener('mouseleave', onFloatingMouseLeave);\n }\n return () => {\n if (open) {\n reference.removeEventListener('mouseleave', onScrollMouseLeave);\n }\n if (move) {\n reference.removeEventListener('mousemove', onReferenceMouseEnter);\n }\n reference.removeEventListener('mouseenter', onReferenceMouseEnter);\n reference.removeEventListener('mouseleave', onReferenceMouseLeave);\n if (floating) {\n floating.removeEventListener('mouseleave', onScrollMouseLeave);\n floating.removeEventListener('mouseenter', onFloatingMouseEnter);\n floating.removeEventListener('mouseleave', onFloatingMouseLeave);\n }\n };\n }\n }, [elements, enabled, context, mouseOnly, move, closeWithDelay, cleanupMouseMoveHandler, clearPointerEvents, onOpenChange, open, openRef, tree, delayRef, handleCloseRef, dataRef, isClickLikeOpenEvent, restMsRef]);\n\n // Block pointer-events of every element other than the reference and floating\n // while the floating element is open and has a `handleClose` handler. Also\n // handles nested floating elements.\n // https://github.com/floating-ui/floating-ui/issues/1722\n useModernLayoutEffect(() => {\n var _handleCloseRef$curre;\n if (!enabled) return;\n if (open && (_handleCloseRef$curre = handleCloseRef.current) != null && (_handleCloseRef$curre = _handleCloseRef$curre.__options) != null && _handleCloseRef$curre.blockPointerEvents && isHoverOpen()) {\n performedPointerEventsMutationRef.current = true;\n const floatingEl = elements.floating;\n if (isElement(elements.domReference) && floatingEl) {\n var _tree$nodesRef$curren;\n const body = getDocument$1(elements.floating).body;\n body.setAttribute(safePolygonIdentifier, '');\n const ref = elements.domReference;\n const parentFloating = tree == null || (_tree$nodesRef$curren = tree.nodesRef.current.find(node => node.id === parentId)) == null || (_tree$nodesRef$curren = _tree$nodesRef$curren.context) == null ? void 0 : _tree$nodesRef$curren.elements.floating;\n if (parentFloating) {\n parentFloating.style.pointerEvents = '';\n }\n body.style.pointerEvents = 'none';\n ref.style.pointerEvents = 'auto';\n floatingEl.style.pointerEvents = 'auto';\n return () => {\n body.style.pointerEvents = '';\n ref.style.pointerEvents = '';\n floatingEl.style.pointerEvents = '';\n };\n }\n }\n }, [enabled, open, parentId, elements, tree, handleCloseRef, isHoverOpen]);\n useModernLayoutEffect(() => {\n if (!open) {\n pointerTypeRef.current = undefined;\n restTimeoutPendingRef.current = false;\n cleanupMouseMoveHandler();\n clearPointerEvents();\n }\n }, [open, cleanupMouseMoveHandler, clearPointerEvents]);\n React.useEffect(() => {\n return () => {\n cleanupMouseMoveHandler();\n clearTimeoutIfSet(timeoutRef);\n clearTimeoutIfSet(restTimeoutRef);\n clearPointerEvents();\n };\n }, [enabled, elements.domReference, cleanupMouseMoveHandler, clearPointerEvents]);\n const reference = React.useMemo(() => {\n function setPointerRef(event) {\n pointerTypeRef.current = event.pointerType;\n }\n return {\n onPointerDown: setPointerRef,\n onPointerEnter: setPointerRef,\n onMouseMove(event) {\n const {\n nativeEvent\n } = event;\n function handleMouseMove() {\n if (!blockMouseMoveRef.current && !openRef.current) {\n onOpenChange(true, nativeEvent, 'hover');\n }\n }\n if (mouseOnly && !isMouseLikePointerType(pointerTypeRef.current)) {\n return;\n }\n if (open || getRestMs(restMsRef.current) === 0) {\n return;\n }\n\n // Ignore insignificant movements to account for tremors.\n if (restTimeoutPendingRef.current && event.movementX ** 2 + event.movementY ** 2 < 2) {\n return;\n }\n clearTimeoutIfSet(restTimeoutRef);\n if (pointerTypeRef.current === 'touch') {\n handleMouseMove();\n } else {\n restTimeoutPendingRef.current = true;\n restTimeoutRef.current = window.setTimeout(handleMouseMove, getRestMs(restMsRef.current));\n }\n }\n };\n }, [mouseOnly, onOpenChange, open, openRef, restMsRef]);\n return React.useMemo(() => enabled ? {\n reference\n } : {}, [enabled, reference]);\n}\n\nconst NOOP = () => {};\nconst FloatingDelayGroupContext = /*#__PURE__*/React.createContext({\n delay: 0,\n initialDelay: 0,\n timeoutMs: 0,\n currentId: null,\n setCurrentId: NOOP,\n setState: NOOP,\n isInstantPhase: false\n});\n\n/**\n * @deprecated\n * Use the return value of `useDelayGroup()` instead.\n */\nconst useDelayGroupContext = () => React.useContext(FloatingDelayGroupContext);\n/**\n * Provides context for a group of floating elements that should share a\n * `delay`.\n * @see https://floating-ui.com/docs/FloatingDelayGroup\n */\nfunction FloatingDelayGroup(props) {\n const {\n children,\n delay,\n timeoutMs = 0\n } = props;\n const [state, setState] = React.useReducer((prev, next) => ({\n ...prev,\n ...next\n }), {\n delay,\n timeoutMs,\n initialDelay: delay,\n currentId: null,\n isInstantPhase: false\n });\n const initialCurrentIdRef = React.useRef(null);\n const setCurrentId = React.useCallback(currentId => {\n setState({\n currentId\n });\n }, []);\n useModernLayoutEffect(() => {\n if (state.currentId) {\n if (initialCurrentIdRef.current === null) {\n initialCurrentIdRef.current = state.currentId;\n } else if (!state.isInstantPhase) {\n setState({\n isInstantPhase: true\n });\n }\n } else {\n if (state.isInstantPhase) {\n setState({\n isInstantPhase: false\n });\n }\n initialCurrentIdRef.current = null;\n }\n }, [state.currentId, state.isInstantPhase]);\n return /*#__PURE__*/jsx(FloatingDelayGroupContext.Provider, {\n value: React.useMemo(() => ({\n ...state,\n setState,\n setCurrentId\n }), [state, setCurrentId]),\n children: children\n });\n}\n/**\n * Enables grouping when called inside a component that's a child of a\n * `FloatingDelayGroup`.\n * @see https://floating-ui.com/docs/FloatingDelayGroup\n */\nfunction useDelayGroup(context, options) {\n if (options === void 0) {\n options = {};\n }\n const {\n open,\n onOpenChange,\n floatingId\n } = context;\n const {\n id: optionId,\n enabled = true\n } = options;\n const id = optionId != null ? optionId : floatingId;\n const groupContext = useDelayGroupContext();\n const {\n currentId,\n setCurrentId,\n initialDelay,\n setState,\n timeoutMs\n } = groupContext;\n useModernLayoutEffect(() => {\n if (!enabled) return;\n if (!currentId) return;\n setState({\n delay: {\n open: 1,\n close: getDelay(initialDelay, 'close')\n }\n });\n if (currentId !== id) {\n onOpenChange(false);\n }\n }, [enabled, id, onOpenChange, setState, currentId, initialDelay]);\n useModernLayoutEffect(() => {\n function unset() {\n onOpenChange(false);\n setState({\n delay: initialDelay,\n currentId: null\n });\n }\n if (!enabled) return;\n if (!currentId) return;\n if (!open && currentId === id) {\n if (timeoutMs) {\n const timeout = window.setTimeout(unset, timeoutMs);\n return () => {\n clearTimeout(timeout);\n };\n }\n unset();\n }\n }, [enabled, open, setState, currentId, id, onOpenChange, initialDelay, timeoutMs]);\n useModernLayoutEffect(() => {\n if (!enabled) return;\n if (setCurrentId === NOOP || !open) return;\n setCurrentId(id);\n }, [enabled, open, setCurrentId, id]);\n return groupContext;\n}\n\nconst NextFloatingDelayGroupContext = /*#__PURE__*/React.createContext({\n hasProvider: false,\n timeoutMs: 0,\n delayRef: {\n current: 0\n },\n initialDelayRef: {\n current: 0\n },\n timeoutIdRef: {\n current: -1\n },\n currentIdRef: {\n current: null\n },\n currentContextRef: {\n current: null\n }\n});\n/**\n * Experimental next version of `FloatingDelayGroup` to become the default\n * in the future. This component is not yet stable.\n * Provides context for a group of floating elements that should share a\n * `delay`. Unlike `FloatingDelayGroup`, `useNextDelayGroup` with this\n * component does not cause a re-render of unrelated consumers of the\n * context when the delay changes.\n * @see https://floating-ui.com/docs/FloatingDelayGroup\n */\nfunction NextFloatingDelayGroup(props) {\n const {\n children,\n delay,\n timeoutMs = 0\n } = props;\n const delayRef = React.useRef(delay);\n const initialDelayRef = React.useRef(delay);\n const currentIdRef = React.useRef(null);\n const currentContextRef = React.useRef(null);\n const timeoutIdRef = React.useRef(-1);\n return /*#__PURE__*/jsx(NextFloatingDelayGroupContext.Provider, {\n value: React.useMemo(() => ({\n hasProvider: true,\n delayRef,\n initialDelayRef,\n currentIdRef,\n timeoutMs,\n currentContextRef,\n timeoutIdRef\n }), [timeoutMs]),\n children: children\n });\n}\n/**\n * Enables grouping when called inside a component that's a child of a\n * `NextFloatingDelayGroup`.\n * @see https://floating-ui.com/docs/FloatingDelayGroup\n */\nfunction useNextDelayGroup(context, options) {\n if (options === void 0) {\n options = {};\n }\n const {\n open,\n onOpenChange,\n floatingId\n } = context;\n const {\n enabled = true\n } = options;\n const groupContext = React.useContext(NextFloatingDelayGroupContext);\n const {\n currentIdRef,\n delayRef,\n timeoutMs,\n initialDelayRef,\n currentContextRef,\n hasProvider,\n timeoutIdRef\n } = groupContext;\n const [isInstantPhase, setIsInstantPhase] = React.useState(false);\n useModernLayoutEffect(() => {\n function unset() {\n var _currentContextRef$cu;\n setIsInstantPhase(false);\n (_currentContextRef$cu = currentContextRef.current) == null || _currentContextRef$cu.setIsInstantPhase(false);\n currentIdRef.current = null;\n currentContextRef.current = null;\n delayRef.current = initialDelayRef.current;\n }\n if (!enabled) return;\n if (!currentIdRef.current) return;\n if (!open && currentIdRef.current === floatingId) {\n setIsInstantPhase(false);\n if (timeoutMs) {\n timeoutIdRef.current = window.setTimeout(unset, timeoutMs);\n return () => {\n clearTimeout(timeoutIdRef.current);\n };\n }\n unset();\n }\n }, [enabled, open, floatingId, currentIdRef, delayRef, timeoutMs, initialDelayRef, currentContextRef, timeoutIdRef]);\n useModernLayoutEffect(() => {\n if (!enabled) return;\n if (!open) return;\n const prevContext = currentContextRef.current;\n const prevId = currentIdRef.current;\n currentContextRef.current = {\n onOpenChange,\n setIsInstantPhase\n };\n currentIdRef.current = floatingId;\n delayRef.current = {\n open: 0,\n close: getDelay(initialDelayRef.current, 'close')\n };\n if (prevId !== null && prevId !== floatingId) {\n clearTimeoutIfSet(timeoutIdRef);\n setIsInstantPhase(true);\n prevContext == null || prevContext.setIsInstantPhase(true);\n prevContext == null || prevContext.onOpenChange(false);\n } else {\n setIsInstantPhase(false);\n prevContext == null || prevContext.setIsInstantPhase(false);\n }\n }, [enabled, open, floatingId, onOpenChange, currentIdRef, delayRef, timeoutMs, initialDelayRef, currentContextRef, timeoutIdRef]);\n useModernLayoutEffect(() => {\n return () => {\n currentContextRef.current = null;\n };\n }, [currentContextRef]);\n return React.useMemo(() => ({\n hasProvider,\n delayRef,\n isInstantPhase\n }), [hasProvider, delayRef, isInstantPhase]);\n}\n\nlet rafId = 0;\nfunction enqueueFocus(el, options) {\n if (options === void 0) {\n options = {};\n }\n const {\n preventScroll = false,\n cancelPrevious = true,\n sync = false\n } = options;\n cancelPrevious && cancelAnimationFrame(rafId);\n const exec = () => el == null ? void 0 : el.focus({\n preventScroll\n });\n if (sync) {\n exec();\n } else {\n rafId = requestAnimationFrame(exec);\n }\n}\n\nfunction contains(parent, child) {\n if (!parent || !child) {\n return false;\n }\n const rootNode = child.getRootNode == null ? void 0 : child.getRootNode();\n\n // First, attempt with faster native method\n if (parent.contains(child)) {\n return true;\n }\n\n // then fallback to custom implementation with Shadow DOM support\n if (rootNode && isShadowRoot(rootNode)) {\n let next = child;\n while (next) {\n if (parent === next) {\n return true;\n }\n // @ts-ignore\n next = next.parentNode || next.host;\n }\n }\n\n // Give up, the result is false\n return false;\n}\nfunction getTarget(event) {\n if ('composedPath' in event) {\n return event.composedPath()[0];\n }\n\n // TS thinks `event` is of type never as it assumes all browsers support\n // `composedPath()`, but browsers without shadow DOM don't.\n return event.target;\n}\nfunction getDocument(node) {\n return (node == null ? void 0 : node.ownerDocument) || document;\n}\n\n// Modified to add conditional `aria-hidden` support:\n// https://github.com/theKashey/aria-hidden/blob/9220c8f4a4fd35f63bee5510a9f41a37264382d4/src/index.ts\nconst counters = {\n inert: /*#__PURE__*/new WeakMap(),\n 'aria-hidden': /*#__PURE__*/new WeakMap(),\n none: /*#__PURE__*/new WeakMap()\n};\nfunction getCounterMap(control) {\n if (control === 'inert') return counters.inert;\n if (control === 'aria-hidden') return counters['aria-hidden'];\n return counters.none;\n}\nlet uncontrolledElementsSet = /*#__PURE__*/new WeakSet();\nlet markerMap = {};\nlet lockCount$1 = 0;\nconst supportsInert = () => typeof HTMLElement !== 'undefined' && 'inert' in HTMLElement.prototype;\nconst unwrapHost = node => node && (node.host || unwrapHost(node.parentNode));\nconst correctElements = (parent, targets) => targets.map(target => {\n if (parent.contains(target)) {\n return target;\n }\n const correctedTarget = unwrapHost(target);\n if (parent.contains(correctedTarget)) {\n return correctedTarget;\n }\n return null;\n}).filter(x => x != null);\nfunction applyAttributeToOthers(uncorrectedAvoidElements, body, ariaHidden, inert) {\n const markerName = 'data-floating-ui-inert';\n const controlAttribute = inert ? 'inert' : ariaHidden ? 'aria-hidden' : null;\n const avoidElements = correctElements(body, uncorrectedAvoidElements);\n const elementsToKeep = new Set();\n const elementsToStop = new Set(avoidElements);\n const hiddenElements = [];\n if (!markerMap[markerName]) {\n markerMap[markerName] = new WeakMap();\n }\n const markerCounter = markerMap[markerName];\n avoidElements.forEach(keep);\n deep(body);\n elementsToKeep.clear();\n function keep(el) {\n if (!el || elementsToKeep.has(el)) {\n return;\n }\n elementsToKeep.add(el);\n el.parentNode && keep(el.parentNode);\n }\n function deep(parent) {\n if (!parent || elementsToStop.has(parent)) {\n return;\n }\n [].forEach.call(parent.children, node => {\n if (getNodeName(node) === 'script') return;\n if (elementsToKeep.has(node)) {\n deep(node);\n } else {\n const attr = controlAttribute ? node.getAttribute(controlAttribute) : null;\n const alreadyHidden = attr !== null && attr !== 'false';\n const counterMap = getCounterMap(controlAttribute);\n const counterValue = (counterMap.get(node) || 0) + 1;\n const markerValue = (markerCounter.get(node) || 0) + 1;\n counterMap.set(node, counterValue);\n markerCounter.set(node, markerValue);\n hiddenElements.push(node);\n if (counterValue === 1 && alreadyHidden) {\n uncontrolledElementsSet.add(node);\n }\n if (markerValue === 1) {\n node.setAttribute(markerName, '');\n }\n if (!alreadyHidden && controlAttribute) {\n node.setAttribute(controlAttribute, controlAttribute === 'inert' ? '' : 'true');\n }\n }\n });\n }\n lockCount$1++;\n return () => {\n hiddenElements.forEach(element => {\n const counterMap = getCounterMap(controlAttribute);\n const currentCounterValue = counterMap.get(element) || 0;\n const counterValue = currentCounterValue - 1;\n const markerValue = (markerCounter.get(element) || 0) - 1;\n counterMap.set(element, counterValue);\n markerCounter.set(element, markerValue);\n if (!counterValue) {\n if (!uncontrolledElementsSet.has(element) && controlAttribute) {\n element.removeAttribute(controlAttribute);\n }\n uncontrolledElementsSet.delete(element);\n }\n if (!markerValue) {\n element.removeAttribute(markerName);\n }\n });\n lockCount$1--;\n if (!lockCount$1) {\n counters.inert = new WeakMap();\n counters['aria-hidden'] = new WeakMap();\n counters.none = new WeakMap();\n uncontrolledElementsSet = new WeakSet();\n markerMap = {};\n }\n };\n}\nfunction markOthers(avoidElements, ariaHidden, inert) {\n if (ariaHidden === void 0) {\n ariaHidden = false;\n }\n if (inert === void 0) {\n inert = false;\n }\n const body = getDocument(avoidElements[0]).body;\n return applyAttributeToOthers(avoidElements.concat(Array.from(body.querySelectorAll('[aria-live],[role=\"status\"],output'))), body, ariaHidden, inert);\n}\n\nconst HIDDEN_STYLES = {\n border: 0,\n clip: 'rect(0 0 0 0)',\n height: '1px',\n margin: '-1px',\n overflow: 'hidden',\n padding: 0,\n position: 'fixed',\n whiteSpace: 'nowrap',\n width: '1px',\n top: 0,\n left: 0\n};\nconst FocusGuard = /*#__PURE__*/React.forwardRef(function FocusGuard(props, ref) {\n const [role, setRole] = React.useState();\n useModernLayoutEffect(() => {\n if (isSafari()) {\n // Unlike other screen readers such as NVDA and JAWS, the virtual cursor\n // on VoiceOver does trigger the onFocus event, so we can use the focus\n // trap element. On Safari, only buttons trigger the onFocus event.\n // NB: \"group\" role in the Sandbox no longer appears to work, must be a\n // button role.\n setRole('button');\n }\n }, []);\n const restProps = {\n ref,\n tabIndex: 0,\n // Role is only for VoiceOver\n role,\n 'aria-hidden': role ? undefined : true,\n [createAttribute('focus-guard')]: '',\n style: HIDDEN_STYLES\n };\n return /*#__PURE__*/jsx(\"span\", {\n ...props,\n ...restProps\n });\n});\n\nconst HIDDEN_OWNER_STYLES = {\n clipPath: 'inset(50%)',\n position: 'fixed',\n top: 0,\n left: 0\n};\nconst PortalContext = /*#__PURE__*/React.createContext(null);\nconst attr = /*#__PURE__*/createAttribute('portal');\n/**\n * @see https://floating-ui.com/docs/FloatingPortal#usefloatingportalnode\n */\nfunction useFloatingPortalNode(props) {\n if (props === void 0) {\n props = {};\n }\n const {\n id,\n root\n } = props;\n const uniqueId = useId();\n const portalContext = usePortalContext();\n const [portalNode, setPortalNode] = React.useState(null);\n const portalNodeRef = React.useRef(null);\n useModernLayoutEffect(() => {\n return () => {\n portalNode == null || portalNode.remove();\n // Allow the subsequent layout effects to create a new node on updates.\n // The portal node will still be cleaned up on unmount.\n // https://github.com/floating-ui/floating-ui/issues/2454\n queueMicrotask(() => {\n portalNodeRef.current = null;\n });\n };\n }, [portalNode]);\n useModernLayoutEffect(() => {\n // Wait for the uniqueId to be generated before creating the portal node in\n // React <18 (using `useFloatingId` instead of the native `useId`).\n // https://github.com/floating-ui/floating-ui/issues/2778\n if (!uniqueId) return;\n if (portalNodeRef.current) return;\n const existingIdRoot = id ? document.getElementById(id) : null;\n if (!existingIdRoot) return;\n const subRoot = document.createElement('div');\n subRoot.id = uniqueId;\n subRoot.setAttribute(attr, '');\n existingIdRoot.appendChild(subRoot);\n portalNodeRef.current = subRoot;\n setPortalNode(subRoot);\n }, [id, uniqueId]);\n useModernLayoutEffect(() => {\n // Wait for the root to exist before creating the portal node. The root must\n // be stored in state, not a ref, for this to work reactively.\n if (root === null) return;\n if (!uniqueId) return;\n if (portalNodeRef.current) return;\n let container = root || (portalContext == null ? void 0 : portalContext.portalNode);\n if (container && !isNode(container)) container = container.current;\n container = container || document.body;\n let idWrapper = null;\n if (id) {\n idWrapper = document.createElement('div');\n idWrapper.id = id;\n container.appendChild(idWrapper);\n }\n const subRoot = document.createElement('div');\n subRoot.id = uniqueId;\n subRoot.setAttribute(attr, '');\n container = idWrapper || container;\n container.appendChild(subRoot);\n portalNodeRef.current = subRoot;\n setPortalNode(subRoot);\n }, [id, root, uniqueId, portalContext]);\n return portalNode;\n}\n/**\n * Portals the floating element into a given container element — by default,\n * outside of the app root and into the body.\n * This is necessary to ensure the floating element can appear outside any\n * potential parent containers that cause clipping (such as `overflow: hidden`),\n * while retaining its location in the React tree.\n * @see https://floating-ui.com/docs/FloatingPortal\n */\nfunction FloatingPortal(props) {\n const {\n children,\n id,\n root,\n preserveTabOrder = true\n } = props;\n const portalNode = useFloatingPortalNode({\n id,\n root\n });\n const [focusManagerState, setFocusManagerState] = React.useState(null);\n const beforeOutsideRef = React.useRef(null);\n const afterOutsideRef = React.useRef(null);\n const beforeInsideRef = React.useRef(null);\n const afterInsideRef = React.useRef(null);\n const modal = focusManagerState == null ? void 0 : focusManagerState.modal;\n const open = focusManagerState == null ? void 0 : focusManagerState.open;\n const shouldRenderGuards =\n // The FocusManager and therefore floating element are currently open/\n // rendered.\n !!focusManagerState &&\n // Guards are only for non-modal focus management.\n !focusManagerState.modal &&\n // Don't render if unmount is transitioning.\n focusManagerState.open && preserveTabOrder && !!(root || portalNode);\n\n // https://codesandbox.io/s/tabbable-portal-f4tng?file=/src/TabbablePortal.tsx\n React.useEffect(() => {\n if (!portalNode || !preserveTabOrder || modal) {\n return;\n }\n\n // Make sure elements inside the portal element are tabbable only when the\n // portal has already been focused, either by tabbing into a focus trap\n // element outside or using the mouse.\n function onFocus(event) {\n if (portalNode && isOutsideEvent(event)) {\n const focusing = event.type === 'focusin';\n const manageFocus = focusing ? enableFocusInside : disableFocusInside;\n manageFocus(portalNode);\n }\n }\n // Listen to the event on the capture phase so they run before the focus\n // trap elements onFocus prop is called.\n portalNode.addEventListener('focusin', onFocus, true);\n portalNode.addEventListener('focusout', onFocus, true);\n return () => {\n portalNode.removeEventListener('focusin', onFocus, true);\n portalNode.removeEventListener('focusout', onFocus, true);\n };\n }, [portalNode, preserveTabOrder, modal]);\n React.useEffect(() => {\n if (!portalNode) return;\n if (open) return;\n enableFocusInside(portalNode);\n }, [open, portalNode]);\n return /*#__PURE__*/jsxs(PortalContext.Provider, {\n value: React.useMemo(() => ({\n preserveTabOrder,\n beforeOutsideRef,\n afterOutsideRef,\n beforeInsideRef,\n afterInsideRef,\n portalNode,\n setFocusManagerState\n }), [preserveTabOrder, portalNode]),\n children: [shouldRenderGuards && portalNode && /*#__PURE__*/jsx(FocusGuard, {\n \"data-type\": \"outside\",\n ref: beforeOutsideRef,\n onFocus: event => {\n if (isOutsideEvent(event, portalNode)) {\n var _beforeInsideRef$curr;\n (_beforeInsideRef$curr = beforeInsideRef.current) == null || _beforeInsideRef$curr.focus();\n } else {\n const domReference = focusManagerState ? focusManagerState.domReference : null;\n const prevTabbable = getPreviousTabbable(domReference);\n prevTabbable == null || prevTabbable.focus();\n }\n }\n }), shouldRenderGuards && portalNode && /*#__PURE__*/jsx(\"span\", {\n \"aria-owns\": portalNode.id,\n style: HIDDEN_OWNER_STYLES\n }), portalNode && /*#__PURE__*/ReactDOM.createPortal(children, portalNode), shouldRenderGuards && portalNode && /*#__PURE__*/jsx(FocusGuard, {\n \"data-type\": \"outside\",\n ref: afterOutsideRef,\n onFocus: event => {\n if (isOutsideEvent(event, portalNode)) {\n var _afterInsideRef$curre;\n (_afterInsideRef$curre = afterInsideRef.current) == null || _afterInsideRef$curre.focus();\n } else {\n const domReference = focusManagerState ? focusManagerState.domReference : null;\n const nextTabbable = getNextTabbable(domReference);\n nextTabbable == null || nextTabbable.focus();\n (focusManagerState == null ? void 0 : focusManagerState.closeOnFocusOut) && (focusManagerState == null ? void 0 : focusManagerState.onOpenChange(false, event.nativeEvent, 'focus-out'));\n }\n }\n })]\n });\n}\nconst usePortalContext = () => React.useContext(PortalContext);\n\nfunction useLiteMergeRefs(refs) {\n return React.useMemo(() => {\n return value => {\n refs.forEach(ref => {\n if (ref) {\n ref.current = value;\n }\n });\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, refs);\n}\n\nconst LIST_LIMIT = 20;\nlet previouslyFocusedElements = [];\nfunction clearDisconnectedPreviouslyFocusedElements() {\n previouslyFocusedElements = previouslyFocusedElements.filter(elementRef => {\n var _elementRef$deref;\n return (_elementRef$deref = elementRef.deref()) == null ? void 0 : _elementRef$deref.isConnected;\n });\n}\nfunction addPreviouslyFocusedElement(element) {\n clearDisconnectedPreviouslyFocusedElements();\n if (element && getNodeName(element) !== 'body') {\n previouslyFocusedElements.push(new WeakRef(element));\n if (previouslyFocusedElements.length > LIST_LIMIT) {\n previouslyFocusedElements = previouslyFocusedElements.slice(-20);\n }\n }\n}\nfunction getPreviouslyFocusedElement() {\n clearDisconnectedPreviouslyFocusedElements();\n const elementRef = previouslyFocusedElements[previouslyFocusedElements.length - 1];\n return elementRef == null ? void 0 : elementRef.deref();\n}\nfunction getFirstTabbableElement(container) {\n const tabbableOptions = getTabbableOptions();\n if (isTabbable(container, tabbableOptions)) {\n return container;\n }\n return tabbable(container, tabbableOptions)[0] || container;\n}\nfunction handleTabIndex(floatingFocusElement, orderRef) {\n var _floatingFocusElement;\n if (!orderRef.current.includes('floating') && !((_floatingFocusElement = floatingFocusElement.getAttribute('role')) != null && _floatingFocusElement.includes('dialog'))) {\n return;\n }\n const options = getTabbableOptions();\n const focusableElements = focusable(floatingFocusElement, options);\n const tabbableContent = focusableElements.filter(element => {\n const dataTabIndex = element.getAttribute('data-tabindex') || '';\n return isTabbable(element, options) || element.hasAttribute('data-tabindex') && !dataTabIndex.startsWith('-');\n });\n const tabIndex = floatingFocusElement.getAttribute('tabindex');\n if (orderRef.current.includes('floating') || tabbableContent.length === 0) {\n if (tabIndex !== '0') {\n floatingFocusElement.setAttribute('tabindex', '0');\n }\n } else if (tabIndex !== '-1' || floatingFocusElement.hasAttribute('data-tabindex') && floatingFocusElement.getAttribute('data-tabindex') !== '-1') {\n floatingFocusElement.setAttribute('tabindex', '-1');\n floatingFocusElement.setAttribute('data-tabindex', '-1');\n }\n}\nconst VisuallyHiddenDismiss = /*#__PURE__*/React.forwardRef(function VisuallyHiddenDismiss(props, ref) {\n return /*#__PURE__*/jsx(\"button\", {\n ...props,\n type: \"button\",\n ref: ref,\n tabIndex: -1,\n style: HIDDEN_STYLES\n });\n});\n/**\n * Provides focus management for the floating element.\n * @see https://floating-ui.com/docs/FloatingFocusManager\n */\nfunction FloatingFocusManager(props) {\n const {\n context,\n children,\n disabled = false,\n order = ['content'],\n guards: _guards = true,\n initialFocus = 0,\n returnFocus = true,\n restoreFocus = false,\n modal = true,\n visuallyHiddenDismiss = false,\n closeOnFocusOut = true,\n outsideElementsInert = false,\n getInsideElements: _getInsideElements = () => []\n } = props;\n const {\n open,\n onOpenChange,\n events,\n dataRef,\n elements: {\n domReference,\n floating\n }\n } = context;\n const getNodeId = useEffectEvent(() => {\n var _dataRef$current$floa;\n return (_dataRef$current$floa = dataRef.current.floatingContext) == null ? void 0 : _dataRef$current$floa.nodeId;\n });\n const getInsideElements = useEffectEvent(_getInsideElements);\n const ignoreInitialFocus = typeof initialFocus === 'number' && initialFocus < 0;\n // If the reference is a combobox and is typeable (e.g. input/textarea),\n // there are different focus semantics. The guards should not be rendered, but\n // aria-hidden should be applied to all nodes still. Further, the visually\n // hidden dismiss button should only appear at the end of the list, not the\n // start.\n const isUntrappedTypeableCombobox = isTypeableCombobox(domReference) && ignoreInitialFocus;\n\n // Force the guards to be rendered if the `inert` attribute is not supported.\n const inertSupported = supportsInert();\n const guards = inertSupported ? _guards : true;\n const useInert = !guards || inertSupported && outsideElementsInert;\n const orderRef = useLatestRef(order);\n const initialFocusRef = useLatestRef(initialFocus);\n const returnFocusRef = useLatestRef(returnFocus);\n const tree = useFloatingTree();\n const portalContext = usePortalContext();\n const startDismissButtonRef = React.useRef(null);\n const endDismissButtonRef = React.useRef(null);\n const preventReturnFocusRef = React.useRef(false);\n const isPointerDownRef = React.useRef(false);\n const tabbableIndexRef = React.useRef(-1);\n const blurTimeoutRef = React.useRef(-1);\n const isInsidePortal = portalContext != null;\n const floatingFocusElement = getFloatingFocusElement(floating);\n const getTabbableContent = useEffectEvent(function (container) {\n if (container === void 0) {\n container = floatingFocusElement;\n }\n return container ? tabbable(container, getTabbableOptions()) : [];\n });\n const getTabbableElements = useEffectEvent(container => {\n const content = getTabbableContent(container);\n return orderRef.current.map(type => {\n if (domReference && type === 'reference') {\n return domReference;\n }\n if (floatingFocusElement && type === 'floating') {\n return floatingFocusElement;\n }\n return content;\n }).filter(Boolean).flat();\n });\n React.useEffect(() => {\n if (disabled) return;\n if (!modal) return;\n function onKeyDown(event) {\n if (event.key === 'Tab') {\n // The focus guards have nothing to focus, so we need to stop the event.\n if (contains$1(floatingFocusElement, activeElement(getDocument$1(floatingFocusElement))) && getTabbableContent().length === 0 && !isUntrappedTypeableCombobox) {\n stopEvent(event);\n }\n const els = getTabbableElements();\n const target = getTarget$1(event);\n if (orderRef.current[0] === 'reference' && target === domReference) {\n stopEvent(event);\n if (event.shiftKey) {\n enqueueFocus(els[els.length - 1]);\n } else {\n enqueueFocus(els[1]);\n }\n }\n if (orderRef.current[1] === 'floating' && target === floatingFocusElement && event.shiftKey) {\n stopEvent(event);\n enqueueFocus(els[0]);\n }\n }\n }\n const doc = getDocument$1(floatingFocusElement);\n doc.addEventListener('keydown', onKeyDown);\n return () => {\n doc.removeEventListener('keydown', onKeyDown);\n };\n }, [disabled, domReference, floatingFocusElement, modal, orderRef, isUntrappedTypeableCombobox, getTabbableContent, getTabbableElements]);\n React.useEffect(() => {\n if (disabled) return;\n if (!floating) return;\n function handleFocusIn(event) {\n const target = getTarget$1(event);\n const tabbableContent = getTabbableContent();\n const tabbableIndex = tabbableContent.indexOf(target);\n if (tabbableIndex !== -1) {\n tabbableIndexRef.current = tabbableIndex;\n }\n }\n floating.addEventListener('focusin', handleFocusIn);\n return () => {\n floating.removeEventListener('focusin', handleFocusIn);\n };\n }, [disabled, floating, getTabbableContent]);\n React.useEffect(() => {\n if (disabled) return;\n if (!closeOnFocusOut) return;\n\n // In Safari, buttons lose focus when pressing them.\n function handlePointerDown() {\n isPointerDownRef.current = true;\n setTimeout(() => {\n isPointerDownRef.current = false;\n });\n }\n function handleFocusOutside(event) {\n const relatedTarget = event.relatedTarget;\n const currentTarget = event.currentTarget;\n const target = getTarget$1(event);\n queueMicrotask(() => {\n const nodeId = getNodeId();\n const movedToUnrelatedNode = !(contains$1(domReference, relatedTarget) || contains$1(floating, relatedTarget) || contains$1(relatedTarget, floating) || contains$1(portalContext == null ? void 0 : portalContext.portalNode, relatedTarget) || relatedTarget != null && relatedTarget.hasAttribute(createAttribute('focus-guard')) || tree && (getNodeChildren$1(tree.nodesRef.current, nodeId).find(node => {\n var _node$context, _node$context2;\n return contains$1((_node$context = node.context) == null ? void 0 : _node$context.elements.floating, relatedTarget) || contains$1((_node$context2 = node.context) == null ? void 0 : _node$context2.elements.domReference, relatedTarget);\n }) || getNodeAncestors(tree.nodesRef.current, nodeId).find(node => {\n var _node$context3, _node$context4, _node$context5;\n return [(_node$context3 = node.context) == null ? void 0 : _node$context3.elements.floating, getFloatingFocusElement((_node$context4 = node.context) == null ? void 0 : _node$context4.elements.floating)].includes(relatedTarget) || ((_node$context5 = node.context) == null ? void 0 : _node$context5.elements.domReference) === relatedTarget;\n })));\n if (currentTarget === domReference && floatingFocusElement) {\n handleTabIndex(floatingFocusElement, orderRef);\n }\n\n // Restore focus to the previous tabbable element index to prevent\n // focus from being lost outside the floating tree.\n if (restoreFocus && currentTarget !== domReference && !(target != null && target.isConnected) && activeElement(getDocument$1(floatingFocusElement)) === getDocument$1(floatingFocusElement).body) {\n // Let `FloatingPortal` effect knows that focus is still inside the\n // floating tree.\n if (isHTMLElement(floatingFocusElement)) {\n floatingFocusElement.focus();\n }\n const prevTabbableIndex = tabbableIndexRef.current;\n const tabbableContent = getTabbableContent();\n const nodeToFocus = tabbableContent[prevTabbableIndex] || tabbableContent[tabbableContent.length - 1] || floatingFocusElement;\n if (isHTMLElement(nodeToFocus)) {\n nodeToFocus.focus();\n }\n }\n\n // https://github.com/floating-ui/floating-ui/issues/3060\n if (dataRef.current.insideReactTree) {\n dataRef.current.insideReactTree = false;\n return;\n }\n\n // Focus did not move inside the floating tree, and there are no tabbable\n // portal guards to handle closing.\n if ((isUntrappedTypeableCombobox ? true : !modal) && relatedTarget && movedToUnrelatedNode && !isPointerDownRef.current &&\n // Fix React 18 Strict Mode returnFocus due to double rendering.\n relatedTarget !== getPreviouslyFocusedElement()) {\n preventReturnFocusRef.current = true;\n onOpenChange(false, event, 'focus-out');\n }\n });\n }\n const shouldHandleBlurCapture = Boolean(!tree && portalContext);\n function markInsideReactTree() {\n clearTimeoutIfSet(blurTimeoutRef);\n dataRef.current.insideReactTree = true;\n blurTimeoutRef.current = window.setTimeout(() => {\n dataRef.current.insideReactTree = false;\n });\n }\n if (floating && isHTMLElement(domReference)) {\n domReference.addEventListener('focusout', handleFocusOutside);\n domReference.addEventListener('pointerdown', handlePointerDown);\n floating.addEventListener('focusout', handleFocusOutside);\n if (shouldHandleBlurCapture) {\n floating.addEventListener('focusout', markInsideReactTree, true);\n }\n return () => {\n domReference.removeEventListener('focusout', handleFocusOutside);\n domReference.removeEventListener('pointerdown', handlePointerDown);\n floating.removeEventListener('focusout', handleFocusOutside);\n if (shouldHandleBlurCapture) {\n floating.removeEventListener('focusout', markInsideReactTree, true);\n }\n };\n }\n }, [disabled, domReference, floating, floatingFocusElement, modal, tree, portalContext, onOpenChange, closeOnFocusOut, restoreFocus, getTabbableContent, isUntrappedTypeableCombobox, getNodeId, orderRef, dataRef]);\n const beforeGuardRef = React.useRef(null);\n const afterGuardRef = React.useRef(null);\n const mergedBeforeGuardRef = useLiteMergeRefs([beforeGuardRef, portalContext == null ? void 0 : portalContext.beforeInsideRef]);\n const mergedAfterGuardRef = useLiteMergeRefs([afterGuardRef, portalContext == null ? void 0 : portalContext.afterInsideRef]);\n React.useEffect(() => {\n var _portalContext$portal, _ancestors$find;\n if (disabled) return;\n if (!floating) return;\n\n // Don't hide portals nested within the parent portal.\n const portalNodes = Array.from((portalContext == null || (_portalContext$portal = portalContext.portalNode) == null ? void 0 : _portalContext$portal.querySelectorAll(\"[\" + createAttribute('portal') + \"]\")) || []);\n const ancestors = tree ? getNodeAncestors(tree.nodesRef.current, getNodeId()) : [];\n const rootAncestorComboboxDomReference = (_ancestors$find = ancestors.find(node => {\n var _node$context6;\n return isTypeableCombobox(((_node$context6 = node.context) == null ? void 0 : _node$context6.elements.domReference) || null);\n })) == null || (_ancestors$find = _ancestors$find.context) == null ? void 0 : _ancestors$find.elements.domReference;\n const insideElements = [floating, rootAncestorComboboxDomReference, ...portalNodes, ...getInsideElements(), startDismissButtonRef.current, endDismissButtonRef.current, beforeGuardRef.current, afterGuardRef.current, portalContext == null ? void 0 : portalContext.beforeOutsideRef.current, portalContext == null ? void 0 : portalContext.afterOutsideRef.current, orderRef.current.includes('reference') || isUntrappedTypeableCombobox ? domReference : null].filter(x => x != null);\n const cleanup = modal || isUntrappedTypeableCombobox ? markOthers(insideElements, !useInert, useInert) : markOthers(insideElements);\n return () => {\n cleanup();\n };\n }, [disabled, domReference, floating, modal, orderRef, portalContext, isUntrappedTypeableCombobox, guards, useInert, tree, getNodeId, getInsideElements]);\n useModernLayoutEffect(() => {\n if (disabled || !isHTMLElement(floatingFocusElement)) return;\n const doc = getDocument$1(floatingFocusElement);\n const previouslyFocusedElement = activeElement(doc);\n\n // Wait for any layout effect state setters to execute to set `tabIndex`.\n queueMicrotask(() => {\n const focusableElements = getTabbableElements(floatingFocusElement);\n const initialFocusValue = initialFocusRef.current;\n const elToFocus = (typeof initialFocusValue === 'number' ? focusableElements[initialFocusValue] : initialFocusValue.current) || floatingFocusElement;\n const focusAlreadyInsideFloatingEl = contains$1(floatingFocusElement, previouslyFocusedElement);\n if (!ignoreInitialFocus && !focusAlreadyInsideFloatingEl && open) {\n enqueueFocus(elToFocus, {\n preventScroll: elToFocus === floatingFocusElement\n });\n }\n });\n }, [disabled, open, floatingFocusElement, ignoreInitialFocus, getTabbableElements, initialFocusRef]);\n useModernLayoutEffect(() => {\n if (disabled || !floatingFocusElement) return;\n const doc = getDocument$1(floatingFocusElement);\n const previouslyFocusedElement = activeElement(doc);\n addPreviouslyFocusedElement(previouslyFocusedElement);\n\n // Dismissing via outside press should always ignore `returnFocus` to\n // prevent unwanted scrolling.\n function onOpenChange(_ref) {\n let {\n reason,\n event,\n nested\n } = _ref;\n if (['hover', 'safe-polygon'].includes(reason) && event.type === 'mouseleave') {\n preventReturnFocusRef.current = true;\n }\n if (reason !== 'outside-press') return;\n if (nested) {\n preventReturnFocusRef.current = false;\n } else if (isVirtualClick(event) || isVirtualPointerEvent(event)) {\n preventReturnFocusRef.current = false;\n } else {\n let isPreventScrollSupported = false;\n document.createElement('div').focus({\n get preventScroll() {\n isPreventScrollSupported = true;\n return false;\n }\n });\n if (isPreventScrollSupported) {\n preventReturnFocusRef.current = false;\n } else {\n preventReturnFocusRef.current = true;\n }\n }\n }\n events.on('openchange', onOpenChange);\n const fallbackEl = doc.createElement('span');\n fallbackEl.setAttribute('tabindex', '-1');\n fallbackEl.setAttribute('aria-hidden', 'true');\n Object.assign(fallbackEl.style, HIDDEN_STYLES);\n if (isInsidePortal && domReference) {\n domReference.insertAdjacentElement('afterend', fallbackEl);\n }\n function getReturnElement() {\n if (typeof returnFocusRef.current === 'boolean') {\n const el = domReference || getPreviouslyFocusedElement();\n return el && el.isConnected ? el : fallbackEl;\n }\n return returnFocusRef.current.current || fallbackEl;\n }\n return () => {\n events.off('openchange', onOpenChange);\n const activeEl = activeElement(doc);\n const isFocusInsideFloatingTree = contains$1(floating, activeEl) || tree && getNodeChildren$1(tree.nodesRef.current, getNodeId(), false).some(node => {\n var _node$context7;\n return contains$1((_node$context7 = node.context) == null ? void 0 : _node$context7.elements.floating, activeEl);\n });\n const returnElement = getReturnElement();\n queueMicrotask(() => {\n // This is `returnElement`, if it's tabbable, or its first tabbable child.\n const tabbableReturnElement = getFirstTabbableElement(returnElement);\n if (\n // eslint-disable-next-line react-hooks/exhaustive-deps\n returnFocusRef.current && !preventReturnFocusRef.current && isHTMLElement(tabbableReturnElement) && (\n // If the focus moved somewhere else after mount, avoid returning focus\n // since it likely entered a different element which should be\n // respected: https://github.com/floating-ui/floating-ui/issues/2607\n tabbableReturnElement !== activeEl && activeEl !== doc.body ? isFocusInsideFloatingTree : true)) {\n tabbableReturnElement.focus({\n preventScroll: true\n });\n }\n fallbackEl.remove();\n });\n };\n }, [disabled, floating, floatingFocusElement, returnFocusRef, dataRef, events, tree, isInsidePortal, domReference, getNodeId]);\n React.useEffect(() => {\n // The `returnFocus` cleanup behavior is inside a microtask; ensure we\n // wait for it to complete before resetting the flag.\n queueMicrotask(() => {\n preventReturnFocusRef.current = false;\n });\n return () => {\n queueMicrotask(clearDisconnectedPreviouslyFocusedElements);\n };\n }, [disabled]);\n\n // Synchronize the `context` & `modal` value to the FloatingPortal context.\n // It will decide whether or not it needs to render its own guards.\n useModernLayoutEffect(() => {\n if (disabled) return;\n if (!portalContext) return;\n portalContext.setFocusManagerState({\n modal,\n closeOnFocusOut,\n open,\n onOpenChange,\n domReference\n });\n return () => {\n portalContext.setFocusManagerState(null);\n };\n }, [disabled, portalContext, modal, open, onOpenChange, closeOnFocusOut, domReference]);\n useModernLayoutEffect(() => {\n if (disabled) return;\n if (!floatingFocusElement) return;\n handleTabIndex(floatingFocusElement, orderRef);\n }, [disabled, floatingFocusElement, orderRef]);\n function renderDismissButton(location) {\n if (disabled || !visuallyHiddenDismiss || !modal) {\n return null;\n }\n return /*#__PURE__*/jsx(VisuallyHiddenDismiss, {\n ref: location === 'start' ? startDismissButtonRef : endDismissButtonRef,\n onClick: event => onOpenChange(false, event.nativeEvent),\n children: typeof visuallyHiddenDismiss === 'string' ? visuallyHiddenDismiss : 'Dismiss'\n });\n }\n const shouldRenderGuards = !disabled && guards && (modal ? !isUntrappedTypeableCombobox : true) && (isInsidePortal || modal);\n return /*#__PURE__*/jsxs(Fragment, {\n children: [shouldRenderGuards && /*#__PURE__*/jsx(FocusGuard, {\n \"data-type\": \"inside\",\n ref: mergedBeforeGuardRef,\n onFocus: event => {\n if (modal) {\n const els = getTabbableElements();\n enqueueFocus(order[0] === 'reference' ? els[0] : els[els.length - 1]);\n } else if (portalContext != null && portalContext.preserveTabOrder && portalContext.portalNode) {\n preventReturnFocusRef.current = false;\n if (isOutsideEvent(event, portalContext.portalNode)) {\n const nextTabbable = getNextTabbable(domReference);\n nextTabbable == null || nextTabbable.focus();\n } else {\n var _portalContext$before;\n (_portalContext$before = portalContext.beforeOutsideRef.current) == null || _portalContext$before.focus();\n }\n }\n }\n }), !isUntrappedTypeableCombobox && renderDismissButton('start'), children, renderDismissButton('end'), shouldRenderGuards && /*#__PURE__*/jsx(FocusGuard, {\n \"data-type\": \"inside\",\n ref: mergedAfterGuardRef,\n onFocus: event => {\n if (modal) {\n enqueueFocus(getTabbableElements()[0]);\n } else if (portalContext != null && portalContext.preserveTabOrder && portalContext.portalNode) {\n if (closeOnFocusOut) {\n preventReturnFocusRef.current = true;\n }\n if (isOutsideEvent(event, portalContext.portalNode)) {\n const prevTabbable = getPreviousTabbable(domReference);\n prevTabbable == null || prevTabbable.focus();\n } else {\n var _portalContext$afterO;\n (_portalContext$afterO = portalContext.afterOutsideRef.current) == null || _portalContext$afterO.focus();\n }\n }\n }\n })]\n });\n}\n\nlet lockCount = 0;\nconst scrollbarProperty = '--floating-ui-scrollbar-width';\nfunction enableScrollLock() {\n const platform = getPlatform();\n const isIOS = /iP(hone|ad|od)|iOS/.test(platform) ||\n // iPads can claim to be MacIntel\n platform === 'MacIntel' && navigator.maxTouchPoints > 1;\n const bodyStyle = document.body.style;\n // RTL <body> scrollbar\n const scrollbarX = Math.round(document.documentElement.getBoundingClientRect().left) + document.documentElement.scrollLeft;\n const paddingProp = scrollbarX ? 'paddingLeft' : 'paddingRight';\n const scrollbarWidth = window.innerWidth - document.documentElement.clientWidth;\n const scrollX = bodyStyle.left ? parseFloat(bodyStyle.left) : window.scrollX;\n const scrollY = bodyStyle.top ? parseFloat(bodyStyle.top) : window.scrollY;\n bodyStyle.overflow = 'hidden';\n bodyStyle.setProperty(scrollbarProperty, scrollbarWidth + \"px\");\n if (scrollbarWidth) {\n bodyStyle[paddingProp] = scrollbarWidth + \"px\";\n }\n\n // Only iOS doesn't respect `overflow: hidden` on document.body, and this\n // technique has fewer side effects.\n if (isIOS) {\n var _window$visualViewpor, _window$visualViewpor2;\n // iOS 12 does not support `visualViewport`.\n const offsetLeft = ((_window$visualViewpor = window.visualViewport) == null ? void 0 : _window$visualViewpor.offsetLeft) || 0;\n const offsetTop = ((_window$visualViewpor2 = window.visualViewport) == null ? void 0 : _window$visualViewpor2.offsetTop) || 0;\n Object.assign(bodyStyle, {\n position: 'fixed',\n top: -(scrollY - Math.floor(offsetTop)) + \"px\",\n left: -(scrollX - Math.floor(offsetLeft)) + \"px\",\n right: '0'\n });\n }\n return () => {\n Object.assign(bodyStyle, {\n overflow: '',\n [paddingProp]: ''\n });\n bodyStyle.removeProperty(scrollbarProperty);\n if (isIOS) {\n Object.assign(bodyStyle, {\n position: '',\n top: '',\n left: '',\n right: ''\n });\n window.scrollTo(scrollX, scrollY);\n }\n };\n}\nlet cleanup = () => {};\n\n/**\n * Provides base styling for a fixed overlay element to dim content or block\n * pointer events behind a floating element.\n * It's a regular `<div>`, so it can be styled via any CSS solution you prefer.\n * @see https://floating-ui.com/docs/FloatingOverlay\n */\nconst FloatingOverlay = /*#__PURE__*/React.forwardRef(function FloatingOverlay(props, ref) {\n const {\n lockScroll = false,\n ...rest\n } = props;\n useModernLayoutEffect(() => {\n if (!lockScroll) return;\n lockCount++;\n if (lockCount === 1) {\n cleanup = enableScrollLock();\n }\n return () => {\n lockCount--;\n if (lockCount === 0) {\n cleanup();\n }\n };\n }, [lockScroll]);\n return /*#__PURE__*/jsx(\"div\", {\n ref: ref,\n ...rest,\n style: {\n position: 'fixed',\n overflow: 'auto',\n top: 0,\n right: 0,\n bottom: 0,\n left: 0,\n ...rest.style\n }\n });\n});\n\nfunction isButtonTarget(event) {\n return isHTMLElement(event.target) && event.target.tagName === 'BUTTON';\n}\nfunction isAnchorTarget(event) {\n return isHTMLElement(event.target) && event.target.tagName === 'A';\n}\nfunction isSpaceIgnored(element) {\n return isTypeableElement(element);\n}\n/**\n * Opens or closes the floating element when clicking the reference element.\n * @see https://floating-ui.com/docs/useClick\n */\nfunction useClick(context, props) {\n if (props === void 0) {\n props = {};\n }\n const {\n open,\n onOpenChange,\n dataRef,\n elements: {\n domReference\n }\n } = context;\n const {\n enabled = true,\n event: eventOption = 'click',\n toggle = true,\n ignoreMouse = false,\n keyboardHandlers = true,\n stickIfOpen = true\n } = props;\n const pointerTypeRef = React.useRef();\n const didKeyDownRef = React.useRef(false);\n const reference = React.useMemo(() => ({\n onPointerDown(event) {\n pointerTypeRef.current = event.pointerType;\n },\n onMouseDown(event) {\n const pointerType = pointerTypeRef.current;\n\n // Ignore all buttons except for the \"main\" button.\n // https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button\n if (event.button !== 0) return;\n if (eventOption === 'click') return;\n if (isMouseLikePointerType(pointerType, true) && ignoreMouse) return;\n if (open && toggle && (dataRef.current.openEvent && stickIfOpen ? dataRef.current.openEvent.type === 'mousedown' : true)) {\n onOpenChange(false, event.nativeEvent, 'click');\n } else {\n // Prevent stealing focus from the floating element\n event.preventDefault();\n onOpenChange(true, event.nativeEvent, 'click');\n }\n },\n onClick(event) {\n const pointerType = pointerTypeRef.current;\n if (eventOption === 'mousedown' && pointerTypeRef.current) {\n pointerTypeRef.current = undefined;\n return;\n }\n if (isMouseLikePointerType(pointerType, true) && ignoreMouse) return;\n if (open && toggle && (dataRef.current.openEvent && stickIfOpen ? dataRef.current.openEvent.type === 'click' : true)) {\n onOpenChange(false, event.nativeEvent, 'click');\n } else {\n onOpenChange(true, event.nativeEvent, 'click');\n }\n },\n onKeyDown(event) {\n pointerTypeRef.current = undefined;\n if (event.defaultPrevented || !keyboardHandlers || isButtonTarget(event)) {\n return;\n }\n if (event.key === ' ' && !isSpaceIgnored(domReference)) {\n // Prevent scrolling\n event.preventDefault();\n didKeyDownRef.current = true;\n }\n if (isAnchorTarget(event)) {\n return;\n }\n if (event.key === 'Enter') {\n if (open && toggle) {\n onOpenChange(false, event.nativeEvent, 'click');\n } else {\n onOpenChange(true, event.nativeEvent, 'click');\n }\n }\n },\n onKeyUp(event) {\n if (event.defaultPrevented || !keyboardHandlers || isButtonTarget(event) || isSpaceIgnored(domReference)) {\n return;\n }\n if (event.key === ' ' && didKeyDownRef.current) {\n didKeyDownRef.current = false;\n if (open && toggle) {\n onOpenChange(false, event.nativeEvent, 'click');\n } else {\n onOpenChange(true, event.nativeEvent, 'click');\n }\n }\n }\n }), [dataRef, domReference, eventOption, ignoreMouse, keyboardHandlers, onOpenChange, open, stickIfOpen, toggle]);\n return React.useMemo(() => enabled ? {\n reference\n } : {}, [enabled, reference]);\n}\n\nfunction createVirtualElement(domElement, data) {\n let offsetX = null;\n let offsetY = null;\n let isAutoUpdateEvent = false;\n return {\n contextElement: domElement || undefined,\n getBoundingClientRect() {\n var _data$dataRef$current;\n const domRect = (domElement == null ? void 0 : domElement.getBoundingClientRect()) || {\n width: 0,\n height: 0,\n x: 0,\n y: 0\n };\n const isXAxis = data.axis === 'x' || data.axis === 'both';\n const isYAxis = data.axis === 'y' || data.axis === 'both';\n const canTrackCursorOnAutoUpdate = ['mouseenter', 'mousemove'].includes(((_data$dataRef$current = data.dataRef.current.openEvent) == null ? void 0 : _data$dataRef$current.type) || '') && data.pointerType !== 'touch';\n let width = domRect.width;\n let height = domRect.height;\n let x = domRect.x;\n let y = domRect.y;\n if (offsetX == null && data.x && isXAxis) {\n offsetX = domRect.x - data.x;\n }\n if (offsetY == null && data.y && isYAxis) {\n offsetY = domRect.y - data.y;\n }\n x -= offsetX || 0;\n y -= offsetY || 0;\n width = 0;\n height = 0;\n if (!isAutoUpdateEvent || canTrackCursorOnAutoUpdate) {\n width = data.axis === 'y' ? domRect.width : 0;\n height = data.axis === 'x' ? domRect.height : 0;\n x = isXAxis && data.x != null ? data.x : x;\n y = isYAxis && data.y != null ? data.y : y;\n } else if (isAutoUpdateEvent && !canTrackCursorOnAutoUpdate) {\n height = data.axis === 'x' ? domRect.height : height;\n width = data.axis === 'y' ? domRect.width : width;\n }\n isAutoUpdateEvent = true;\n return {\n width,\n height,\n x,\n y,\n top: y,\n right: x + width,\n bottom: y + height,\n left: x\n };\n }\n };\n}\nfunction isMouseBasedEvent(event) {\n return event != null && event.clientX != null;\n}\n/**\n * Positions the floating element relative to a client point (in the viewport),\n * such as the mouse position. By default, it follows the mouse cursor.\n * @see https://floating-ui.com/docs/useClientPoint\n */\nfunction useClientPoint(context, props) {\n if (props === void 0) {\n props = {};\n }\n const {\n open,\n dataRef,\n elements: {\n floating,\n domReference\n },\n refs\n } = context;\n const {\n enabled = true,\n axis = 'both',\n x = null,\n y = null\n } = props;\n const initialRef = React.useRef(false);\n const cleanupListenerRef = React.useRef(null);\n const [pointerType, setPointerType] = React.useState();\n const [reactive, setReactive] = React.useState([]);\n const setReference = useEffectEvent((x, y) => {\n if (initialRef.current) return;\n\n // Prevent setting if the open event was not a mouse-like one\n // (e.g. focus to open, then hover over the reference element).\n // Only apply if the event exists.\n if (dataRef.current.openEvent && !isMouseBasedEvent(dataRef.current.openEvent)) {\n return;\n }\n refs.setPositionReference(createVirtualElement(domReference, {\n x,\n y,\n axis,\n dataRef,\n pointerType\n }));\n });\n const handleReferenceEnterOrMove = useEffectEvent(event => {\n if (x != null || y != null) return;\n if (!open) {\n setReference(event.clientX, event.clientY);\n } else if (!cleanupListenerRef.current) {\n // If there's no cleanup, there's no listener, but we want to ensure\n // we add the listener if the cursor landed on the floating element and\n // then back on the reference (i.e. it's interactive).\n setReactive([]);\n }\n });\n\n // If the pointer is a mouse-like pointer, we want to continue following the\n // mouse even if the floating element is transitioning out. On touch\n // devices, this is undesirable because the floating element will move to\n // the dismissal touch point.\n const openCheck = isMouseLikePointerType(pointerType) ? floating : open;\n const addListener = React.useCallback(() => {\n // Explicitly specified `x`/`y` coordinates shouldn't add a listener.\n if (!openCheck || !enabled || x != null || y != null) return;\n const win = getWindow(floating);\n function handleMouseMove(event) {\n const target = getTarget$1(event);\n if (!contains$1(floating, target)) {\n setReference(event.clientX, event.clientY);\n } else {\n win.removeEventListener('mousemove', handleMouseMove);\n cleanupListenerRef.current = null;\n }\n }\n if (!dataRef.current.openEvent || isMouseBasedEvent(dataRef.current.openEvent)) {\n win.addEventListener('mousemove', handleMouseMove);\n const cleanup = () => {\n win.removeEventListener('mousemove', handleMouseMove);\n cleanupListenerRef.current = null;\n };\n cleanupListenerRef.current = cleanup;\n return cleanup;\n }\n refs.setPositionReference(domReference);\n }, [openCheck, enabled, x, y, floating, dataRef, refs, domReference, setReference]);\n React.useEffect(() => {\n return addListener();\n }, [addListener, reactive]);\n React.useEffect(() => {\n if (enabled && !floating) {\n initialRef.current = false;\n }\n }, [enabled, floating]);\n React.useEffect(() => {\n if (!enabled && open) {\n initialRef.current = true;\n }\n }, [enabled, open]);\n useModernLayoutEffect(() => {\n if (enabled && (x != null || y != null)) {\n initialRef.current = false;\n setReference(x, y);\n }\n }, [enabled, x, y, setReference]);\n const reference = React.useMemo(() => {\n function setPointerTypeRef(_ref) {\n let {\n pointerType\n } = _ref;\n setPointerType(pointerType);\n }\n return {\n onPointerDown: setPointerTypeRef,\n onPointerEnter: setPointerTypeRef,\n onMouseMove: handleReferenceEnterOrMove,\n onMouseEnter: handleReferenceEnterOrMove\n };\n }, [handleReferenceEnterOrMove]);\n return React.useMemo(() => enabled ? {\n reference\n } : {}, [enabled, reference]);\n}\n\nconst bubbleHandlerKeys = {\n pointerdown: 'onPointerDown',\n mousedown: 'onMouseDown',\n click: 'onClick'\n};\nconst captureHandlerKeys = {\n pointerdown: 'onPointerDownCapture',\n mousedown: 'onMouseDownCapture',\n click: 'onClickCapture'\n};\nconst normalizeProp = normalizable => {\n var _normalizable$escapeK, _normalizable$outside;\n return {\n escapeKey: typeof normalizable === 'boolean' ? normalizable : (_normalizable$escapeK = normalizable == null ? void 0 : normalizable.escapeKey) != null ? _normalizable$escapeK : false,\n outsidePress: typeof normalizable === 'boolean' ? normalizable : (_normalizable$outside = normalizable == null ? void 0 : normalizable.outsidePress) != null ? _normalizable$outside : true\n };\n};\n/**\n * Closes the floating element when a dismissal is requested — by default, when\n * the user presses the `escape` key or outside of the floating element.\n * @see https://floating-ui.com/docs/useDismiss\n */\nfunction useDismiss(context, props) {\n if (props === void 0) {\n props = {};\n }\n const {\n open,\n onOpenChange,\n elements,\n dataRef\n } = context;\n const {\n enabled = true,\n escapeKey = true,\n outsidePress: unstable_outsidePress = true,\n outsidePressEvent = 'pointerdown',\n referencePress = false,\n referencePressEvent = 'pointerdown',\n ancestorScroll = false,\n bubbles,\n capture\n } = props;\n const tree = useFloatingTree();\n const outsidePressFn = useEffectEvent(typeof unstable_outsidePress === 'function' ? unstable_outsidePress : () => false);\n const outsidePress = typeof unstable_outsidePress === 'function' ? outsidePressFn : unstable_outsidePress;\n const endedOrStartedInsideRef = React.useRef(false);\n const {\n escapeKey: escapeKeyBubbles,\n outsidePress: outsidePressBubbles\n } = normalizeProp(bubbles);\n const {\n escapeKey: escapeKeyCapture,\n outsidePress: outsidePressCapture\n } = normalizeProp(capture);\n const isComposingRef = React.useRef(false);\n const closeOnEscapeKeyDown = useEffectEvent(event => {\n var _dataRef$current$floa;\n if (!open || !enabled || !escapeKey || event.key !== 'Escape') {\n return;\n }\n\n // Wait until IME is settled. Pressing `Escape` while composing should\n // close the compose menu, but not the floating element.\n if (isComposingRef.current) {\n return;\n }\n const nodeId = (_dataRef$current$floa = dataRef.current.floatingContext) == null ? void 0 : _dataRef$current$floa.nodeId;\n const children = tree ? getNodeChildren$1(tree.nodesRef.current, nodeId) : [];\n if (!escapeKeyBubbles) {\n event.stopPropagation();\n if (children.length > 0) {\n let shouldDismiss = true;\n children.forEach(child => {\n var _child$context;\n if ((_child$context = child.context) != null && _child$context.open && !child.context.dataRef.current.__escapeKeyBubbles) {\n shouldDismiss = false;\n return;\n }\n });\n if (!shouldDismiss) {\n return;\n }\n }\n }\n onOpenChange(false, isReactEvent(event) ? event.nativeEvent : event, 'escape-key');\n });\n const closeOnEscapeKeyDownCapture = useEffectEvent(event => {\n var _getTarget2;\n const callback = () => {\n var _getTarget;\n closeOnEscapeKeyDown(event);\n (_getTarget = getTarget$1(event)) == null || _getTarget.removeEventListener('keydown', callback);\n };\n (_getTarget2 = getTarget$1(event)) == null || _getTarget2.addEventListener('keydown', callback);\n });\n const closeOnPressOutside = useEffectEvent(event => {\n var _dataRef$current$floa2;\n // Given developers can stop the propagation of the synthetic event,\n // we can only be confident with a positive value.\n const insideReactTree = dataRef.current.insideReactTree;\n dataRef.current.insideReactTree = false;\n\n // When click outside is lazy (`click` event), handle dragging.\n // Don't close if:\n // - The click started inside the floating element.\n // - The click ended inside the floating element.\n const endedOrStartedInside = endedOrStartedInsideRef.current;\n endedOrStartedInsideRef.current = false;\n if (outsidePressEvent === 'click' && endedOrStartedInside) {\n return;\n }\n if (insideReactTree) {\n return;\n }\n if (typeof outsidePress === 'function' && !outsidePress(event)) {\n return;\n }\n const target = getTarget$1(event);\n const inertSelector = \"[\" + createAttribute('inert') + \"]\";\n const markers = getDocument$1(elements.floating).querySelectorAll(inertSelector);\n let targetRootAncestor = isElement(target) ? target : null;\n while (targetRootAncestor && !isLastTraversableNode(targetRootAncestor)) {\n const nextParent = getParentNode(targetRootAncestor);\n if (isLastTraversableNode(nextParent) || !isElement(nextParent)) {\n break;\n }\n targetRootAncestor = nextParent;\n }\n\n // Check if the click occurred on a third-party element injected after the\n // floating element rendered.\n if (markers.length && isElement(target) && !isRootElement(target) &&\n // Clicked on a direct ancestor (e.g. FloatingOverlay).\n !contains$1(target, elements.floating) &&\n // If the target root element contains none of the markers, then the\n // element was injected after the floating element rendered.\n Array.from(markers).every(marker => !contains$1(targetRootAncestor, marker))) {\n return;\n }\n\n // Check if the click occurred on the scrollbar\n if (isHTMLElement(target) && floating) {\n const lastTraversableNode = isLastTraversableNode(target);\n const style = getComputedStyle(target);\n const scrollRe = /auto|scroll/;\n const isScrollableX = lastTraversableNode || scrollRe.test(style.overflowX);\n const isScrollableY = lastTraversableNode || scrollRe.test(style.overflowY);\n const canScrollX = isScrollableX && target.clientWidth > 0 && target.scrollWidth > target.clientWidth;\n const canScrollY = isScrollableY && target.clientHeight > 0 && target.scrollHeight > target.clientHeight;\n const isRTL = style.direction === 'rtl';\n\n // Check click position relative to scrollbar.\n // In some browsers it is possible to change the <body> (or window)\n // scrollbar to the left side, but is very rare and is difficult to\n // check for. Plus, for modal dialogs with backdrops, it is more\n // important that the backdrop is checked but not so much the window.\n const pressedVerticalScrollbar = canScrollY && (isRTL ? event.offsetX <= target.offsetWidth - target.clientWidth : event.offsetX > target.clientWidth);\n const pressedHorizontalScrollbar = canScrollX && event.offsetY > target.clientHeight;\n if (pressedVerticalScrollbar || pressedHorizontalScrollbar) {\n return;\n }\n }\n const nodeId = (_dataRef$current$floa2 = dataRef.current.floatingContext) == null ? void 0 : _dataRef$current$floa2.nodeId;\n const targetIsInsideChildren = tree && getNodeChildren$1(tree.nodesRef.current, nodeId).some(node => {\n var _node$context;\n return isEventTargetWithin(event, (_node$context = node.context) == null ? void 0 : _node$context.elements.floating);\n });\n if (isEventTargetWithin(event, elements.floating) || isEventTargetWithin(event, elements.domReference) || targetIsInsideChildren) {\n return;\n }\n const children = tree ? getNodeChildren$1(tree.nodesRef.current, nodeId) : [];\n if (children.length > 0) {\n let shouldDismiss = true;\n children.forEach(child => {\n var _child$context2;\n if ((_child$context2 = child.context) != null && _child$context2.open && !child.context.dataRef.current.__outsidePressBubbles) {\n shouldDismiss = false;\n return;\n }\n });\n if (!shouldDismiss) {\n return;\n }\n }\n onOpenChange(false, event, 'outside-press');\n });\n const closeOnPressOutsideCapture = useEffectEvent(event => {\n var _getTarget4;\n const callback = () => {\n var _getTarget3;\n closeOnPressOutside(event);\n (_getTarget3 = getTarget$1(event)) == null || _getTarget3.removeEventListener(outsidePressEvent, callback);\n };\n (_getTarget4 = getTarget$1(event)) == null || _getTarget4.addEventListener(outsidePressEvent, callback);\n });\n React.useEffect(() => {\n if (!open || !enabled) {\n return;\n }\n dataRef.current.__escapeKeyBubbles = escapeKeyBubbles;\n dataRef.current.__outsidePressBubbles = outsidePressBubbles;\n let compositionTimeout = -1;\n function onScroll(event) {\n onOpenChange(false, event, 'ancestor-scroll');\n }\n function handleCompositionStart() {\n window.clearTimeout(compositionTimeout);\n isComposingRef.current = true;\n }\n function handleCompositionEnd() {\n // Safari fires `compositionend` before `keydown`, so we need to wait\n // until the next tick to set `isComposing` to `false`.\n // https://bugs.webkit.org/show_bug.cgi?id=165004\n compositionTimeout = window.setTimeout(() => {\n isComposingRef.current = false;\n },\n // 0ms or 1ms don't work in Safari. 5ms appears to consistently work.\n // Only apply to WebKit for the test to remain 0ms.\n isWebKit() ? 5 : 0);\n }\n const doc = getDocument$1(elements.floating);\n if (escapeKey) {\n doc.addEventListener('keydown', escapeKeyCapture ? closeOnEscapeKeyDownCapture : closeOnEscapeKeyDown, escapeKeyCapture);\n doc.addEventListener('compositionstart', handleCompositionStart);\n doc.addEventListener('compositionend', handleCompositionEnd);\n }\n outsidePress && doc.addEventListener(outsidePressEvent, outsidePressCapture ? closeOnPressOutsideCapture : closeOnPressOutside, outsidePressCapture);\n let ancestors = [];\n if (ancestorScroll) {\n if (isElement(elements.domReference)) {\n ancestors = getOverflowAncestors(elements.domReference);\n }\n if (isElement(elements.floating)) {\n ancestors = ancestors.concat(getOverflowAncestors(elements.floating));\n }\n if (!isElement(elements.reference) && elements.reference && elements.reference.contextElement) {\n ancestors = ancestors.concat(getOverflowAncestors(elements.reference.contextElement));\n }\n }\n\n // Ignore the visual viewport for scrolling dismissal (allow pinch-zoom)\n ancestors = ancestors.filter(ancestor => {\n var _doc$defaultView;\n return ancestor !== ((_doc$defaultView = doc.defaultView) == null ? void 0 : _doc$defaultView.visualViewport);\n });\n ancestors.forEach(ancestor => {\n ancestor.addEventListener('scroll', onScroll, {\n passive: true\n });\n });\n return () => {\n if (escapeKey) {\n doc.removeEventListener('keydown', escapeKeyCapture ? closeOnEscapeKeyDownCapture : closeOnEscapeKeyDown, escapeKeyCapture);\n doc.removeEventListener('compositionstart', handleCompositionStart);\n doc.removeEventListener('compositionend', handleCompositionEnd);\n }\n outsidePress && doc.removeEventListener(outsidePressEvent, outsidePressCapture ? closeOnPressOutsideCapture : closeOnPressOutside, outsidePressCapture);\n ancestors.forEach(ancestor => {\n ancestor.removeEventListener('scroll', onScroll);\n });\n window.clearTimeout(compositionTimeout);\n };\n }, [dataRef, elements, escapeKey, outsidePress, outsidePressEvent, open, onOpenChange, ancestorScroll, enabled, escapeKeyBubbles, outsidePressBubbles, closeOnEscapeKeyDown, escapeKeyCapture, closeOnEscapeKeyDownCapture, closeOnPressOutside, outsidePressCapture, closeOnPressOutsideCapture]);\n React.useEffect(() => {\n dataRef.current.insideReactTree = false;\n }, [dataRef, outsidePress, outsidePressEvent]);\n const reference = React.useMemo(() => ({\n onKeyDown: closeOnEscapeKeyDown,\n ...(referencePress && {\n [bubbleHandlerKeys[referencePressEvent]]: event => {\n onOpenChange(false, event.nativeEvent, 'reference-press');\n },\n ...(referencePressEvent !== 'click' && {\n onClick(event) {\n onOpenChange(false, event.nativeEvent, 'reference-press');\n }\n })\n })\n }), [closeOnEscapeKeyDown, onOpenChange, referencePress, referencePressEvent]);\n const floating = React.useMemo(() => ({\n onKeyDown: closeOnEscapeKeyDown,\n onMouseDown() {\n endedOrStartedInsideRef.current = true;\n },\n onMouseUp() {\n endedOrStartedInsideRef.current = true;\n },\n [captureHandlerKeys[outsidePressEvent]]: () => {\n dataRef.current.insideReactTree = true;\n }\n }), [closeOnEscapeKeyDown, outsidePressEvent, dataRef]);\n return React.useMemo(() => enabled ? {\n reference,\n floating\n } : {}, [enabled, reference, floating]);\n}\n\nfunction useFloatingRootContext(options) {\n const {\n open = false,\n onOpenChange: onOpenChangeProp,\n elements: elementsProp\n } = options;\n const floatingId = useId();\n const dataRef = React.useRef({});\n const [events] = React.useState(() => createEventEmitter());\n const nested = useFloatingParentNodeId() != null;\n if (process.env.NODE_ENV !== \"production\") {\n const optionDomReference = elementsProp.reference;\n if (optionDomReference && !isElement(optionDomReference)) {\n error('Cannot pass a virtual element to the `elements.reference` option,', 'as it must be a real DOM element. Use `refs.setPositionReference()`', 'instead.');\n }\n }\n const [positionReference, setPositionReference] = React.useState(elementsProp.reference);\n const onOpenChange = useEffectEvent((open, event, reason) => {\n dataRef.current.openEvent = open ? event : undefined;\n events.emit('openchange', {\n open,\n event,\n reason,\n nested\n });\n onOpenChangeProp == null || onOpenChangeProp(open, event, reason);\n });\n const refs = React.useMemo(() => ({\n setPositionReference\n }), []);\n const elements = React.useMemo(() => ({\n reference: positionReference || elementsProp.reference || null,\n floating: elementsProp.floating || null,\n domReference: elementsProp.reference\n }), [positionReference, elementsProp.reference, elementsProp.floating]);\n return React.useMemo(() => ({\n dataRef,\n open,\n onOpenChange,\n elements,\n events,\n floatingId,\n refs\n }), [open, onOpenChange, elements, events, floatingId, refs]);\n}\n\n/**\n * Provides data to position a floating element and context to add interactions.\n * @see https://floating-ui.com/docs/useFloating\n */\nfunction useFloating(options) {\n if (options === void 0) {\n options = {};\n }\n const {\n nodeId\n } = options;\n const internalRootContext = useFloatingRootContext({\n ...options,\n elements: {\n reference: null,\n floating: null,\n ...options.elements\n }\n });\n const rootContext = options.rootContext || internalRootContext;\n const computedElements = rootContext.elements;\n const [_domReference, setDomReference] = React.useState(null);\n const [positionReference, _setPositionReference] = React.useState(null);\n const optionDomReference = computedElements == null ? void 0 : computedElements.domReference;\n const domReference = optionDomReference || _domReference;\n const domReferenceRef = React.useRef(null);\n const tree = useFloatingTree();\n useModernLayoutEffect(() => {\n if (domReference) {\n domReferenceRef.current = domReference;\n }\n }, [domReference]);\n const position = useFloating$1({\n ...options,\n elements: {\n ...computedElements,\n ...(positionReference && {\n reference: positionReference\n })\n }\n });\n const setPositionReference = React.useCallback(node => {\n const computedPositionReference = isElement(node) ? {\n getBoundingClientRect: () => node.getBoundingClientRect(),\n getClientRects: () => node.getClientRects(),\n contextElement: node\n } : node;\n // Store the positionReference in state if the DOM reference is specified externally via the\n // `elements.reference` option. This ensures that it won't be overridden on future renders.\n _setPositionReference(computedPositionReference);\n position.refs.setReference(computedPositionReference);\n }, [position.refs]);\n const setReference = React.useCallback(node => {\n if (isElement(node) || node === null) {\n domReferenceRef.current = node;\n setDomReference(node);\n }\n\n // Backwards-compatibility for passing a virtual element to `reference`\n // after it has set the DOM reference.\n if (isElement(position.refs.reference.current) || position.refs.reference.current === null ||\n // Don't allow setting virtual elements using the old technique back to\n // `null` to support `positionReference` + an unstable `reference`\n // callback ref.\n node !== null && !isElement(node)) {\n position.refs.setReference(node);\n }\n }, [position.refs]);\n const refs = React.useMemo(() => ({\n ...position.refs,\n setReference,\n setPositionReference,\n domReference: domReferenceRef\n }), [position.refs, setReference, setPositionReference]);\n const elements = React.useMemo(() => ({\n ...position.elements,\n domReference: domReference\n }), [position.elements, domReference]);\n const context = React.useMemo(() => ({\n ...position,\n ...rootContext,\n refs,\n elements,\n nodeId\n }), [position, refs, elements, nodeId, rootContext]);\n useModernLayoutEffect(() => {\n rootContext.dataRef.current.floatingContext = context;\n const node = tree == null ? void 0 : tree.nodesRef.current.find(node => node.id === nodeId);\n if (node) {\n node.context = context;\n }\n });\n return React.useMemo(() => ({\n ...position,\n context,\n refs,\n elements\n }), [position, refs, elements, context]);\n}\n\nfunction isMacSafari() {\n return isMac() && isSafari();\n}\n/**\n * Opens the floating element while the reference element has focus, like CSS\n * `:focus`.\n * @see https://floating-ui.com/docs/useFocus\n */\nfunction useFocus(context, props) {\n if (props === void 0) {\n props = {};\n }\n const {\n open,\n onOpenChange,\n events,\n dataRef,\n elements\n } = context;\n const {\n enabled = true,\n visibleOnly = true\n } = props;\n const blockFocusRef = React.useRef(false);\n const timeoutRef = React.useRef(-1);\n const keyboardModalityRef = React.useRef(true);\n React.useEffect(() => {\n if (!enabled) return;\n const win = getWindow(elements.domReference);\n\n // If the reference was focused and the user left the tab/window, and the\n // floating element was not open, the focus should be blocked when they\n // return to the tab/window.\n function onBlur() {\n if (!open && isHTMLElement(elements.domReference) && elements.domReference === activeElement(getDocument$1(elements.domReference))) {\n blockFocusRef.current = true;\n }\n }\n function onKeyDown() {\n keyboardModalityRef.current = true;\n }\n function onPointerDown() {\n keyboardModalityRef.current = false;\n }\n win.addEventListener('blur', onBlur);\n if (isMacSafari()) {\n win.addEventListener('keydown', onKeyDown, true);\n win.addEventListener('pointerdown', onPointerDown, true);\n }\n return () => {\n win.removeEventListener('blur', onBlur);\n if (isMacSafari()) {\n win.removeEventListener('keydown', onKeyDown, true);\n win.removeEventListener('pointerdown', onPointerDown, true);\n }\n };\n }, [elements.domReference, open, enabled]);\n React.useEffect(() => {\n if (!enabled) return;\n function onOpenChange(_ref) {\n let {\n reason\n } = _ref;\n if (reason === 'reference-press' || reason === 'escape-key') {\n blockFocusRef.current = true;\n }\n }\n events.on('openchange', onOpenChange);\n return () => {\n events.off('openchange', onOpenChange);\n };\n }, [events, enabled]);\n React.useEffect(() => {\n return () => {\n clearTimeoutIfSet(timeoutRef);\n };\n }, []);\n const reference = React.useMemo(() => ({\n onMouseLeave() {\n blockFocusRef.current = false;\n },\n onFocus(event) {\n if (blockFocusRef.current) return;\n const target = getTarget$1(event.nativeEvent);\n if (visibleOnly && isElement(target)) {\n // Safari fails to match `:focus-visible` if focus was initially\n // outside the document.\n if (isMacSafari() && !event.relatedTarget) {\n if (!keyboardModalityRef.current && !isTypeableElement(target)) {\n return;\n }\n } else if (!matchesFocusVisible(target)) {\n return;\n }\n }\n onOpenChange(true, event.nativeEvent, 'focus');\n },\n onBlur(event) {\n blockFocusRef.current = false;\n const relatedTarget = event.relatedTarget;\n const nativeEvent = event.nativeEvent;\n\n // Hit the non-modal focus management portal guard. Focus will be\n // moved into the floating element immediately after.\n const movedToFocusGuard = isElement(relatedTarget) && relatedTarget.hasAttribute(createAttribute('focus-guard')) && relatedTarget.getAttribute('data-type') === 'outside';\n\n // Wait for the window blur listener to fire.\n timeoutRef.current = window.setTimeout(() => {\n var _dataRef$current$floa;\n const activeEl = activeElement(elements.domReference ? elements.domReference.ownerDocument : document);\n\n // Focus left the page, keep it open.\n if (!relatedTarget && activeEl === elements.domReference) return;\n\n // When focusing the reference element (e.g. regular click), then\n // clicking into the floating element, prevent it from hiding.\n // Note: it must be focusable, e.g. `tabindex=\"-1\"`.\n // We can not rely on relatedTarget to point to the correct element\n // as it will only point to the shadow host of the newly focused element\n // and not the element that actually has received focus if it is located\n // inside a shadow root.\n if (contains$1((_dataRef$current$floa = dataRef.current.floatingContext) == null ? void 0 : _dataRef$current$floa.refs.floating.current, activeEl) || contains$1(elements.domReference, activeEl) || movedToFocusGuard) {\n return;\n }\n onOpenChange(false, nativeEvent, 'focus');\n });\n }\n }), [dataRef, elements.domReference, onOpenChange, visibleOnly]);\n return React.useMemo(() => enabled ? {\n reference\n } : {}, [enabled, reference]);\n}\n\nfunction mergeProps(userProps, propsList, elementKey) {\n const map = new Map();\n const isItem = elementKey === 'item';\n let domUserProps = userProps;\n if (isItem && userProps) {\n const {\n [ACTIVE_KEY]: _,\n [SELECTED_KEY]: __,\n ...validProps\n } = userProps;\n domUserProps = validProps;\n }\n return {\n ...(elementKey === 'floating' && {\n tabIndex: -1,\n [FOCUSABLE_ATTRIBUTE]: ''\n }),\n ...domUserProps,\n ...propsList.map(value => {\n const propsOrGetProps = value ? value[elementKey] : null;\n if (typeof propsOrGetProps === 'function') {\n return userProps ? propsOrGetProps(userProps) : null;\n }\n return propsOrGetProps;\n }).concat(userProps).reduce((acc, props) => {\n if (!props) {\n return acc;\n }\n Object.entries(props).forEach(_ref => {\n let [key, value] = _ref;\n if (isItem && [ACTIVE_KEY, SELECTED_KEY].includes(key)) {\n return;\n }\n if (key.indexOf('on') === 0) {\n if (!map.has(key)) {\n map.set(key, []);\n }\n if (typeof value === 'function') {\n var _map$get;\n (_map$get = map.get(key)) == null || _map$get.push(value);\n acc[key] = function () {\n var _map$get2;\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n return (_map$get2 = map.get(key)) == null ? void 0 : _map$get2.map(fn => fn(...args)).find(val => val !== undefined);\n };\n }\n } else {\n acc[key] = value;\n }\n });\n return acc;\n }, {})\n };\n}\n/**\n * Merges an array of interaction hooks' props into prop getters, allowing\n * event handler functions to be composed together without overwriting one\n * another.\n * @see https://floating-ui.com/docs/useInteractions\n */\nfunction useInteractions(propsList) {\n if (propsList === void 0) {\n propsList = [];\n }\n const referenceDeps = propsList.map(key => key == null ? void 0 : key.reference);\n const floatingDeps = propsList.map(key => key == null ? void 0 : key.floating);\n const itemDeps = propsList.map(key => key == null ? void 0 : key.item);\n const getReferenceProps = React.useCallback(userProps => mergeProps(userProps, propsList, 'reference'),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n referenceDeps);\n const getFloatingProps = React.useCallback(userProps => mergeProps(userProps, propsList, 'floating'),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n floatingDeps);\n const getItemProps = React.useCallback(userProps => mergeProps(userProps, propsList, 'item'),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n itemDeps);\n return React.useMemo(() => ({\n getReferenceProps,\n getFloatingProps,\n getItemProps\n }), [getReferenceProps, getFloatingProps, getItemProps]);\n}\n\nconst ESCAPE = 'Escape';\nfunction doSwitch(orientation, vertical, horizontal) {\n switch (orientation) {\n case 'vertical':\n return vertical;\n case 'horizontal':\n return horizontal;\n default:\n return vertical || horizontal;\n }\n}\nfunction isMainOrientationKey(key, orientation) {\n const vertical = key === ARROW_UP || key === ARROW_DOWN;\n const horizontal = key === ARROW_LEFT || key === ARROW_RIGHT;\n return doSwitch(orientation, vertical, horizontal);\n}\nfunction isMainOrientationToEndKey(key, orientation, rtl) {\n const vertical = key === ARROW_DOWN;\n const horizontal = rtl ? key === ARROW_LEFT : key === ARROW_RIGHT;\n return doSwitch(orientation, vertical, horizontal) || key === 'Enter' || key === ' ' || key === '';\n}\nfunction isCrossOrientationOpenKey(key, orientation, rtl) {\n const vertical = rtl ? key === ARROW_LEFT : key === ARROW_RIGHT;\n const horizontal = key === ARROW_DOWN;\n return doSwitch(orientation, vertical, horizontal);\n}\nfunction isCrossOrientationCloseKey(key, orientation, rtl, cols) {\n const vertical = rtl ? key === ARROW_RIGHT : key === ARROW_LEFT;\n const horizontal = key === ARROW_UP;\n if (orientation === 'both' || orientation === 'horizontal' && cols && cols > 1) {\n return key === ESCAPE;\n }\n return doSwitch(orientation, vertical, horizontal);\n}\n/**\n * Adds arrow key-based navigation of a list of items, either using real DOM\n * focus or virtual focus.\n * @see https://floating-ui.com/docs/useListNavigation\n */\nfunction useListNavigation(context, props) {\n const {\n open,\n onOpenChange,\n elements,\n floatingId\n } = context;\n const {\n listRef,\n activeIndex,\n onNavigate: unstable_onNavigate = () => {},\n enabled = true,\n selectedIndex = null,\n allowEscape = false,\n loop = false,\n nested = false,\n rtl = false,\n virtual = false,\n focusItemOnOpen = 'auto',\n focusItemOnHover = true,\n openOnArrowKeyDown = true,\n disabledIndices = undefined,\n orientation = 'vertical',\n parentOrientation,\n cols = 1,\n scrollItemIntoView = true,\n virtualItemRef,\n itemSizes,\n dense = false\n } = props;\n if (process.env.NODE_ENV !== \"production\") {\n if (allowEscape) {\n if (!loop) {\n warn('`useListNavigation` looping must be enabled to allow escaping.');\n }\n if (!virtual) {\n warn('`useListNavigation` must be virtual to allow escaping.');\n }\n }\n if (orientation === 'vertical' && cols > 1) {\n warn('In grid list navigation mode (`cols` > 1), the `orientation` should', 'be either \"horizontal\" or \"both\".');\n }\n }\n const floatingFocusElement = getFloatingFocusElement(elements.floating);\n const floatingFocusElementRef = useLatestRef(floatingFocusElement);\n const parentId = useFloatingParentNodeId();\n const tree = useFloatingTree();\n useModernLayoutEffect(() => {\n context.dataRef.current.orientation = orientation;\n }, [context, orientation]);\n const onNavigate = useEffectEvent(() => {\n unstable_onNavigate(indexRef.current === -1 ? null : indexRef.current);\n });\n const typeableComboboxReference = isTypeableCombobox(elements.domReference);\n const focusItemOnOpenRef = React.useRef(focusItemOnOpen);\n const indexRef = React.useRef(selectedIndex != null ? selectedIndex : -1);\n const keyRef = React.useRef(null);\n const isPointerModalityRef = React.useRef(true);\n const previousOnNavigateRef = React.useRef(onNavigate);\n const previousMountedRef = React.useRef(!!elements.floating);\n const previousOpenRef = React.useRef(open);\n const forceSyncFocusRef = React.useRef(false);\n const forceScrollIntoViewRef = React.useRef(false);\n const disabledIndicesRef = useLatestRef(disabledIndices);\n const latestOpenRef = useLatestRef(open);\n const scrollItemIntoViewRef = useLatestRef(scrollItemIntoView);\n const selectedIndexRef = useLatestRef(selectedIndex);\n const [activeId, setActiveId] = React.useState();\n const [virtualId, setVirtualId] = React.useState();\n const focusItem = useEffectEvent(() => {\n function runFocus(item) {\n if (virtual) {\n var _item$id;\n if ((_item$id = item.id) != null && _item$id.endsWith('-fui-option')) {\n item.id = floatingId + \"-\" + Math.random().toString(16).slice(2, 10);\n }\n setActiveId(item.id);\n tree == null || tree.events.emit('virtualfocus', item);\n if (virtualItemRef) {\n virtualItemRef.current = item;\n }\n } else {\n enqueueFocus(item, {\n sync: forceSyncFocusRef.current,\n preventScroll: true\n });\n }\n }\n const initialItem = listRef.current[indexRef.current];\n const forceScrollIntoView = forceScrollIntoViewRef.current;\n if (initialItem) {\n runFocus(initialItem);\n }\n const scheduler = forceSyncFocusRef.current ? v => v() : requestAnimationFrame;\n scheduler(() => {\n const waitedItem = listRef.current[indexRef.current] || initialItem;\n if (!waitedItem) return;\n if (!initialItem) {\n runFocus(waitedItem);\n }\n const scrollIntoViewOptions = scrollItemIntoViewRef.current;\n const shouldScrollIntoView = scrollIntoViewOptions && item && (forceScrollIntoView || !isPointerModalityRef.current);\n if (shouldScrollIntoView) {\n // JSDOM doesn't support `.scrollIntoView()` but it's widely supported\n // by all browsers.\n waitedItem.scrollIntoView == null || waitedItem.scrollIntoView(typeof scrollIntoViewOptions === 'boolean' ? {\n block: 'nearest',\n inline: 'nearest'\n } : scrollIntoViewOptions);\n }\n });\n });\n\n // Sync `selectedIndex` to be the `activeIndex` upon opening the floating\n // element. Also, reset `activeIndex` upon closing the floating element.\n useModernLayoutEffect(() => {\n if (!enabled) return;\n if (open && elements.floating) {\n if (focusItemOnOpenRef.current && selectedIndex != null) {\n // Regardless of the pointer modality, we want to ensure the selected\n // item comes into view when the floating element is opened.\n forceScrollIntoViewRef.current = true;\n indexRef.current = selectedIndex;\n onNavigate();\n }\n } else if (previousMountedRef.current) {\n // Since the user can specify `onNavigate` conditionally\n // (onNavigate: open ? setActiveIndex : setSelectedIndex),\n // we store and call the previous function.\n indexRef.current = -1;\n previousOnNavigateRef.current();\n }\n }, [enabled, open, elements.floating, selectedIndex, onNavigate]);\n\n // Sync `activeIndex` to be the focused item while the floating element is\n // open.\n useModernLayoutEffect(() => {\n if (!enabled) return;\n if (!open) return;\n if (!elements.floating) return;\n if (activeIndex == null) {\n forceSyncFocusRef.current = false;\n if (selectedIndexRef.current != null) {\n return;\n }\n\n // Reset while the floating element was open (e.g. the list changed).\n if (previousMountedRef.current) {\n indexRef.current = -1;\n focusItem();\n }\n\n // Initial sync.\n if ((!previousOpenRef.current || !previousMountedRef.current) && focusItemOnOpenRef.current && (keyRef.current != null || focusItemOnOpenRef.current === true && keyRef.current == null)) {\n let runs = 0;\n const waitForListPopulated = () => {\n if (listRef.current[0] == null) {\n // Avoid letting the browser paint if possible on the first try,\n // otherwise use rAF. Don't try more than twice, since something\n // is wrong otherwise.\n if (runs < 2) {\n const scheduler = runs ? requestAnimationFrame : queueMicrotask;\n scheduler(waitForListPopulated);\n }\n runs++;\n } else {\n indexRef.current = keyRef.current == null || isMainOrientationToEndKey(keyRef.current, orientation, rtl) || nested ? getMinListIndex(listRef, disabledIndicesRef.current) : getMaxListIndex(listRef, disabledIndicesRef.current);\n keyRef.current = null;\n onNavigate();\n }\n };\n waitForListPopulated();\n }\n } else if (!isIndexOutOfListBounds(listRef, activeIndex)) {\n indexRef.current = activeIndex;\n focusItem();\n forceScrollIntoViewRef.current = false;\n }\n }, [enabled, open, elements.floating, activeIndex, selectedIndexRef, nested, listRef, orientation, rtl, onNavigate, focusItem, disabledIndicesRef]);\n\n // Ensure the parent floating element has focus when a nested child closes\n // to allow arrow key navigation to work after the pointer leaves the child.\n useModernLayoutEffect(() => {\n var _nodes$find;\n if (!enabled || elements.floating || !tree || virtual || !previousMountedRef.current) {\n return;\n }\n const nodes = tree.nodesRef.current;\n const parent = (_nodes$find = nodes.find(node => node.id === parentId)) == null || (_nodes$find = _nodes$find.context) == null ? void 0 : _nodes$find.elements.floating;\n const activeEl = activeElement(getDocument$1(elements.floating));\n const treeContainsActiveEl = nodes.some(node => node.context && contains$1(node.context.elements.floating, activeEl));\n if (parent && !treeContainsActiveEl && isPointerModalityRef.current) {\n parent.focus({\n preventScroll: true\n });\n }\n }, [enabled, elements.floating, tree, parentId, virtual]);\n useModernLayoutEffect(() => {\n if (!enabled) return;\n if (!tree) return;\n if (!virtual) return;\n if (parentId) return;\n function handleVirtualFocus(item) {\n setVirtualId(item.id);\n if (virtualItemRef) {\n virtualItemRef.current = item;\n }\n }\n tree.events.on('virtualfocus', handleVirtualFocus);\n return () => {\n tree.events.off('virtualfocus', handleVirtualFocus);\n };\n }, [enabled, tree, virtual, parentId, virtualItemRef]);\n useModernLayoutEffect(() => {\n previousOnNavigateRef.current = onNavigate;\n previousOpenRef.current = open;\n previousMountedRef.current = !!elements.floating;\n });\n useModernLayoutEffect(() => {\n if (!open) {\n keyRef.current = null;\n focusItemOnOpenRef.current = focusItemOnOpen;\n }\n }, [open, focusItemOnOpen]);\n const hasActiveIndex = activeIndex != null;\n const item = React.useMemo(() => {\n function syncCurrentTarget(currentTarget) {\n if (!latestOpenRef.current) return;\n const index = listRef.current.indexOf(currentTarget);\n if (index !== -1 && indexRef.current !== index) {\n indexRef.current = index;\n onNavigate();\n }\n }\n const props = {\n onFocus(_ref) {\n let {\n currentTarget\n } = _ref;\n forceSyncFocusRef.current = true;\n syncCurrentTarget(currentTarget);\n },\n onClick: _ref2 => {\n let {\n currentTarget\n } = _ref2;\n return currentTarget.focus({\n preventScroll: true\n });\n },\n // Safari\n onMouseMove(_ref3) {\n let {\n currentTarget\n } = _ref3;\n forceSyncFocusRef.current = true;\n forceScrollIntoViewRef.current = false;\n if (focusItemOnHover) {\n syncCurrentTarget(currentTarget);\n }\n },\n onPointerLeave(_ref4) {\n let {\n pointerType\n } = _ref4;\n if (!isPointerModalityRef.current || pointerType === 'touch') {\n return;\n }\n forceSyncFocusRef.current = true;\n if (!focusItemOnHover) {\n return;\n }\n indexRef.current = -1;\n onNavigate();\n if (!virtual) {\n var _floatingFocusElement;\n (_floatingFocusElement = floatingFocusElementRef.current) == null || _floatingFocusElement.focus({\n preventScroll: true\n });\n }\n }\n };\n return props;\n }, [latestOpenRef, floatingFocusElementRef, focusItemOnHover, listRef, onNavigate, virtual]);\n const getParentOrientation = React.useCallback(() => {\n var _tree$nodesRef$curren;\n return parentOrientation != null ? parentOrientation : tree == null || (_tree$nodesRef$curren = tree.nodesRef.current.find(node => node.id === parentId)) == null || (_tree$nodesRef$curren = _tree$nodesRef$curren.context) == null || (_tree$nodesRef$curren = _tree$nodesRef$curren.dataRef) == null ? void 0 : _tree$nodesRef$curren.current.orientation;\n }, [parentId, tree, parentOrientation]);\n const commonOnKeyDown = useEffectEvent(event => {\n isPointerModalityRef.current = false;\n forceSyncFocusRef.current = true;\n\n // When composing a character, Chrome fires ArrowDown twice. Firefox/Safari\n // don't appear to suffer from this. `event.isComposing` is avoided due to\n // Safari not supporting it properly (although it's not needed in the first\n // place for Safari, just avoiding any possible issues).\n if (event.which === 229) {\n return;\n }\n\n // If the floating element is animating out, ignore navigation. Otherwise,\n // the `activeIndex` gets set to 0 despite not being open so the next time\n // the user ArrowDowns, the first item won't be focused.\n if (!latestOpenRef.current && event.currentTarget === floatingFocusElementRef.current) {\n return;\n }\n if (nested && isCrossOrientationCloseKey(event.key, orientation, rtl, cols)) {\n // If the nested list's close key is also the parent navigation key,\n // let the parent navigate. Otherwise, stop propagating the event.\n if (!isMainOrientationKey(event.key, getParentOrientation())) {\n stopEvent(event);\n }\n onOpenChange(false, event.nativeEvent, 'list-navigation');\n if (isHTMLElement(elements.domReference)) {\n if (virtual) {\n tree == null || tree.events.emit('virtualfocus', elements.domReference);\n } else {\n elements.domReference.focus();\n }\n }\n return;\n }\n const currentIndex = indexRef.current;\n const minIndex = getMinListIndex(listRef, disabledIndices);\n const maxIndex = getMaxListIndex(listRef, disabledIndices);\n if (!typeableComboboxReference) {\n if (event.key === 'Home') {\n stopEvent(event);\n indexRef.current = minIndex;\n onNavigate();\n }\n if (event.key === 'End') {\n stopEvent(event);\n indexRef.current = maxIndex;\n onNavigate();\n }\n }\n\n // Grid navigation.\n if (cols > 1) {\n const sizes = itemSizes || Array.from({\n length: listRef.current.length\n }, () => ({\n width: 1,\n height: 1\n }));\n // To calculate movements on the grid, we use hypothetical cell indices\n // as if every item was 1x1, then convert back to real indices.\n const cellMap = createGridCellMap(sizes, cols, dense);\n const minGridIndex = cellMap.findIndex(index => index != null && !isListIndexDisabled(listRef, index, disabledIndices));\n // last enabled index\n const maxGridIndex = cellMap.reduce((foundIndex, index, cellIndex) => index != null && !isListIndexDisabled(listRef, index, disabledIndices) ? cellIndex : foundIndex, -1);\n const index = cellMap[getGridNavigatedIndex({\n current: cellMap.map(itemIndex => itemIndex != null ? listRef.current[itemIndex] : null)\n }, {\n event,\n orientation,\n loop,\n rtl,\n cols,\n // treat undefined (empty grid spaces) as disabled indices so we\n // don't end up in them\n disabledIndices: getGridCellIndices([...((typeof disabledIndices !== 'function' ? disabledIndices : null) || listRef.current.map((_, index) => isListIndexDisabled(listRef, index, disabledIndices) ? index : undefined)), undefined], cellMap),\n minIndex: minGridIndex,\n maxIndex: maxGridIndex,\n prevIndex: getGridCellIndexOfCorner(indexRef.current > maxIndex ? minIndex : indexRef.current, sizes, cellMap, cols,\n // use a corner matching the edge closest to the direction\n // we're moving in so we don't end up in the same item. Prefer\n // top/left over bottom/right.\n event.key === ARROW_DOWN ? 'bl' : event.key === (rtl ? ARROW_LEFT : ARROW_RIGHT) ? 'tr' : 'tl'),\n stopEvent: true\n })];\n if (index != null) {\n indexRef.current = index;\n onNavigate();\n }\n if (orientation === 'both') {\n return;\n }\n }\n if (isMainOrientationKey(event.key, orientation)) {\n stopEvent(event);\n\n // Reset the index if no item is focused.\n if (open && !virtual && activeElement(event.currentTarget.ownerDocument) === event.currentTarget) {\n indexRef.current = isMainOrientationToEndKey(event.key, orientation, rtl) ? minIndex : maxIndex;\n onNavigate();\n return;\n }\n if (isMainOrientationToEndKey(event.key, orientation, rtl)) {\n if (loop) {\n indexRef.current = currentIndex >= maxIndex ? allowEscape && currentIndex !== listRef.current.length ? -1 : minIndex : findNonDisabledListIndex(listRef, {\n startingIndex: currentIndex,\n disabledIndices\n });\n } else {\n indexRef.current = Math.min(maxIndex, findNonDisabledListIndex(listRef, {\n startingIndex: currentIndex,\n disabledIndices\n }));\n }\n } else {\n if (loop) {\n indexRef.current = currentIndex <= minIndex ? allowEscape && currentIndex !== -1 ? listRef.current.length : maxIndex : findNonDisabledListIndex(listRef, {\n startingIndex: currentIndex,\n decrement: true,\n disabledIndices\n });\n } else {\n indexRef.current = Math.max(minIndex, findNonDisabledListIndex(listRef, {\n startingIndex: currentIndex,\n decrement: true,\n disabledIndices\n }));\n }\n }\n if (isIndexOutOfListBounds(listRef, indexRef.current)) {\n indexRef.current = -1;\n }\n onNavigate();\n }\n });\n const ariaActiveDescendantProp = React.useMemo(() => {\n return virtual && open && hasActiveIndex && {\n 'aria-activedescendant': virtualId || activeId\n };\n }, [virtual, open, hasActiveIndex, virtualId, activeId]);\n const floating = React.useMemo(() => {\n return {\n 'aria-orientation': orientation === 'both' ? undefined : orientation,\n ...(!typeableComboboxReference ? ariaActiveDescendantProp : {}),\n onKeyDown: commonOnKeyDown,\n onPointerMove() {\n isPointerModalityRef.current = true;\n }\n };\n }, [ariaActiveDescendantProp, commonOnKeyDown, orientation, typeableComboboxReference]);\n const reference = React.useMemo(() => {\n function checkVirtualMouse(event) {\n if (focusItemOnOpen === 'auto' && isVirtualClick(event.nativeEvent)) {\n focusItemOnOpenRef.current = true;\n }\n }\n function checkVirtualPointer(event) {\n // `pointerdown` fires first, reset the state then perform the checks.\n focusItemOnOpenRef.current = focusItemOnOpen;\n if (focusItemOnOpen === 'auto' && isVirtualPointerEvent(event.nativeEvent)) {\n focusItemOnOpenRef.current = true;\n }\n }\n return {\n ...ariaActiveDescendantProp,\n onKeyDown(event) {\n isPointerModalityRef.current = false;\n const isArrowKey = event.key.startsWith('Arrow');\n const isHomeOrEndKey = ['Home', 'End'].includes(event.key);\n const isMoveKey = isArrowKey || isHomeOrEndKey;\n const isCrossOpenKey = isCrossOrientationOpenKey(event.key, orientation, rtl);\n const isCrossCloseKey = isCrossOrientationCloseKey(event.key, orientation, rtl, cols);\n const isParentCrossOpenKey = isCrossOrientationOpenKey(event.key, getParentOrientation(), rtl);\n const isMainKey = isMainOrientationKey(event.key, orientation);\n const isNavigationKey = (nested ? isParentCrossOpenKey : isMainKey) || event.key === 'Enter' || event.key.trim() === '';\n if (virtual && open) {\n const rootNode = tree == null ? void 0 : tree.nodesRef.current.find(node => node.parentId == null);\n const deepestNode = tree && rootNode ? getDeepestNode(tree.nodesRef.current, rootNode.id) : null;\n if (isMoveKey && deepestNode && virtualItemRef) {\n const eventObject = new KeyboardEvent('keydown', {\n key: event.key,\n bubbles: true\n });\n if (isCrossOpenKey || isCrossCloseKey) {\n var _deepestNode$context, _deepestNode$context2;\n const isCurrentTarget = ((_deepestNode$context = deepestNode.context) == null ? void 0 : _deepestNode$context.elements.domReference) === event.currentTarget;\n const dispatchItem = isCrossCloseKey && !isCurrentTarget ? (_deepestNode$context2 = deepestNode.context) == null ? void 0 : _deepestNode$context2.elements.domReference : isCrossOpenKey ? listRef.current.find(item => (item == null ? void 0 : item.id) === activeId) : null;\n if (dispatchItem) {\n stopEvent(event);\n dispatchItem.dispatchEvent(eventObject);\n setVirtualId(undefined);\n }\n }\n if ((isMainKey || isHomeOrEndKey) && deepestNode.context) {\n if (deepestNode.context.open && deepestNode.parentId && event.currentTarget !== deepestNode.context.elements.domReference) {\n var _deepestNode$context$;\n stopEvent(event);\n (_deepestNode$context$ = deepestNode.context.elements.domReference) == null || _deepestNode$context$.dispatchEvent(eventObject);\n return;\n }\n }\n }\n return commonOnKeyDown(event);\n }\n // If a floating element should not open on arrow key down, avoid\n // setting `activeIndex` while it's closed.\n if (!open && !openOnArrowKeyDown && isArrowKey) {\n return;\n }\n if (isNavigationKey) {\n const isParentMainKey = isMainOrientationKey(event.key, getParentOrientation());\n keyRef.current = nested && isParentMainKey ? null : event.key;\n }\n if (nested) {\n if (isParentCrossOpenKey) {\n stopEvent(event);\n if (open) {\n indexRef.current = getMinListIndex(listRef, disabledIndicesRef.current);\n onNavigate();\n } else {\n onOpenChange(true, event.nativeEvent, 'list-navigation');\n }\n }\n return;\n }\n if (isMainKey) {\n if (selectedIndex != null) {\n indexRef.current = selectedIndex;\n }\n stopEvent(event);\n if (!open && openOnArrowKeyDown) {\n onOpenChange(true, event.nativeEvent, 'list-navigation');\n } else {\n commonOnKeyDown(event);\n }\n if (open) {\n onNavigate();\n }\n }\n },\n onFocus() {\n if (open && !virtual) {\n indexRef.current = -1;\n onNavigate();\n }\n },\n onPointerDown: checkVirtualPointer,\n onPointerEnter: checkVirtualPointer,\n onMouseDown: checkVirtualMouse,\n onClick: checkVirtualMouse\n };\n }, [activeId, ariaActiveDescendantProp, cols, commonOnKeyDown, disabledIndicesRef, focusItemOnOpen, listRef, nested, onNavigate, onOpenChange, open, openOnArrowKeyDown, orientation, getParentOrientation, rtl, selectedIndex, tree, virtual, virtualItemRef]);\n return React.useMemo(() => enabled ? {\n reference,\n floating,\n item\n } : {}, [enabled, reference, floating, item]);\n}\n\nconst componentRoleToAriaRoleMap = /*#__PURE__*/new Map([['select', 'listbox'], ['combobox', 'listbox'], ['label', false]]);\n\n/**\n * Adds base screen reader props to the reference and floating elements for a\n * given floating element `role`.\n * @see https://floating-ui.com/docs/useRole\n */\nfunction useRole(context, props) {\n var _elements$domReferenc, _componentRoleToAriaR;\n if (props === void 0) {\n props = {};\n }\n const {\n open,\n elements,\n floatingId: defaultFloatingId\n } = context;\n const {\n enabled = true,\n role = 'dialog'\n } = props;\n const defaultReferenceId = useId();\n const referenceId = ((_elements$domReferenc = elements.domReference) == null ? void 0 : _elements$domReferenc.id) || defaultReferenceId;\n const floatingId = React.useMemo(() => {\n var _getFloatingFocusElem;\n return ((_getFloatingFocusElem = getFloatingFocusElement(elements.floating)) == null ? void 0 : _getFloatingFocusElem.id) || defaultFloatingId;\n }, [elements.floating, defaultFloatingId]);\n const ariaRole = (_componentRoleToAriaR = componentRoleToAriaRoleMap.get(role)) != null ? _componentRoleToAriaR : role;\n const parentId = useFloatingParentNodeId();\n const isNested = parentId != null;\n const reference = React.useMemo(() => {\n if (ariaRole === 'tooltip' || role === 'label') {\n return {\n [\"aria-\" + (role === 'label' ? 'labelledby' : 'describedby')]: open ? floatingId : undefined\n };\n }\n return {\n 'aria-expanded': open ? 'true' : 'false',\n 'aria-haspopup': ariaRole === 'alertdialog' ? 'dialog' : ariaRole,\n 'aria-controls': open ? floatingId : undefined,\n ...(ariaRole === 'listbox' && {\n role: 'combobox'\n }),\n ...(ariaRole === 'menu' && {\n id: referenceId\n }),\n ...(ariaRole === 'menu' && isNested && {\n role: 'menuitem'\n }),\n ...(role === 'select' && {\n 'aria-autocomplete': 'none'\n }),\n ...(role === 'combobox' && {\n 'aria-autocomplete': 'list'\n })\n };\n }, [ariaRole, floatingId, isNested, open, referenceId, role]);\n const floating = React.useMemo(() => {\n const floatingProps = {\n id: floatingId,\n ...(ariaRole && {\n role: ariaRole\n })\n };\n if (ariaRole === 'tooltip' || role === 'label') {\n return floatingProps;\n }\n return {\n ...floatingProps,\n ...(ariaRole === 'menu' && {\n 'aria-labelledby': referenceId\n })\n };\n }, [ariaRole, floatingId, referenceId, role]);\n const item = React.useCallback(_ref => {\n let {\n active,\n selected\n } = _ref;\n const commonProps = {\n role: 'option',\n ...(active && {\n id: floatingId + \"-fui-option\"\n })\n };\n\n // For `menu`, we are unable to tell if the item is a `menuitemradio`\n // or `menuitemcheckbox`. For backwards-compatibility reasons, also\n // avoid defaulting to `menuitem` as it may overwrite custom role props.\n switch (role) {\n case 'select':\n case 'combobox':\n return {\n ...commonProps,\n 'aria-selected': selected\n };\n }\n return {};\n }, [floatingId, role]);\n return React.useMemo(() => enabled ? {\n reference,\n floating,\n item\n } : {}, [enabled, reference, floating, item]);\n}\n\n// Converts a JS style key like `backgroundColor` to a CSS transition-property\n// like `background-color`.\nconst camelCaseToKebabCase = str => str.replace(/[A-Z]+(?![a-z])|[A-Z]/g, ($, ofs) => (ofs ? '-' : '') + $.toLowerCase());\nfunction execWithArgsOrReturn(valueOrFn, args) {\n return typeof valueOrFn === 'function' ? valueOrFn(args) : valueOrFn;\n}\nfunction useDelayUnmount(open, durationMs) {\n const [isMounted, setIsMounted] = React.useState(open);\n if (open && !isMounted) {\n setIsMounted(true);\n }\n React.useEffect(() => {\n if (!open && isMounted) {\n const timeout = setTimeout(() => setIsMounted(false), durationMs);\n return () => clearTimeout(timeout);\n }\n }, [open, isMounted, durationMs]);\n return isMounted;\n}\n/**\n * Provides a status string to apply CSS transitions to a floating element,\n * correctly handling placement-aware transitions.\n * @see https://floating-ui.com/docs/useTransition#usetransitionstatus\n */\nfunction useTransitionStatus(context, props) {\n if (props === void 0) {\n props = {};\n }\n const {\n open,\n elements: {\n floating\n }\n } = context;\n const {\n duration = 250\n } = props;\n const isNumberDuration = typeof duration === 'number';\n const closeDuration = (isNumberDuration ? duration : duration.close) || 0;\n const [status, setStatus] = React.useState('unmounted');\n const isMounted = useDelayUnmount(open, closeDuration);\n if (!isMounted && status === 'close') {\n setStatus('unmounted');\n }\n useModernLayoutEffect(() => {\n if (!floating) return;\n if (open) {\n setStatus('initial');\n const frame = requestAnimationFrame(() => {\n // Ensure it opens before paint. With `FloatingDelayGroup`,\n // this avoids a flicker when moving between floating elements\n // to ensure one is always open with no missing frames.\n ReactDOM.flushSync(() => {\n setStatus('open');\n });\n });\n return () => {\n cancelAnimationFrame(frame);\n };\n }\n setStatus('close');\n }, [open, floating]);\n return {\n isMounted,\n status\n };\n}\n/**\n * Provides styles to apply CSS transitions to a floating element, correctly\n * handling placement-aware transitions. Wrapper around `useTransitionStatus`.\n * @see https://floating-ui.com/docs/useTransition#usetransitionstyles\n */\nfunction useTransitionStyles(context, props) {\n if (props === void 0) {\n props = {};\n }\n const {\n initial: unstable_initial = {\n opacity: 0\n },\n open: unstable_open,\n close: unstable_close,\n common: unstable_common,\n duration = 250\n } = props;\n const placement = context.placement;\n const side = placement.split('-')[0];\n const fnArgs = React.useMemo(() => ({\n side,\n placement\n }), [side, placement]);\n const isNumberDuration = typeof duration === 'number';\n const openDuration = (isNumberDuration ? duration : duration.open) || 0;\n const closeDuration = (isNumberDuration ? duration : duration.close) || 0;\n const [styles, setStyles] = React.useState(() => ({\n ...execWithArgsOrReturn(unstable_common, fnArgs),\n ...execWithArgsOrReturn(unstable_initial, fnArgs)\n }));\n const {\n isMounted,\n status\n } = useTransitionStatus(context, {\n duration\n });\n const initialRef = useLatestRef(unstable_initial);\n const openRef = useLatestRef(unstable_open);\n const closeRef = useLatestRef(unstable_close);\n const commonRef = useLatestRef(unstable_common);\n useModernLayoutEffect(() => {\n const initialStyles = execWithArgsOrReturn(initialRef.current, fnArgs);\n const closeStyles = execWithArgsOrReturn(closeRef.current, fnArgs);\n const commonStyles = execWithArgsOrReturn(commonRef.current, fnArgs);\n const openStyles = execWithArgsOrReturn(openRef.current, fnArgs) || Object.keys(initialStyles).reduce((acc, key) => {\n acc[key] = '';\n return acc;\n }, {});\n if (status === 'initial') {\n setStyles(styles => ({\n transitionProperty: styles.transitionProperty,\n ...commonStyles,\n ...initialStyles\n }));\n }\n if (status === 'open') {\n setStyles({\n transitionProperty: Object.keys(openStyles).map(camelCaseToKebabCase).join(','),\n transitionDuration: openDuration + \"ms\",\n ...commonStyles,\n ...openStyles\n });\n }\n if (status === 'close') {\n const styles = closeStyles || initialStyles;\n setStyles({\n transitionProperty: Object.keys(styles).map(camelCaseToKebabCase).join(','),\n transitionDuration: closeDuration + \"ms\",\n ...commonStyles,\n ...styles\n });\n }\n }, [closeDuration, closeRef, initialRef, openRef, commonRef, openDuration, status, fnArgs]);\n return {\n isMounted,\n styles\n };\n}\n\n/**\n * Provides a matching callback that can be used to focus an item as the user\n * types, often used in tandem with `useListNavigation()`.\n * @see https://floating-ui.com/docs/useTypeahead\n */\nfunction useTypeahead(context, props) {\n var _ref;\n const {\n open,\n dataRef\n } = context;\n const {\n listRef,\n activeIndex,\n onMatch: unstable_onMatch,\n onTypingChange: unstable_onTypingChange,\n enabled = true,\n findMatch = null,\n resetMs = 750,\n ignoreKeys = [],\n selectedIndex = null\n } = props;\n const timeoutIdRef = React.useRef(-1);\n const stringRef = React.useRef('');\n const prevIndexRef = React.useRef((_ref = selectedIndex != null ? selectedIndex : activeIndex) != null ? _ref : -1);\n const matchIndexRef = React.useRef(null);\n const onMatch = useEffectEvent(unstable_onMatch);\n const onTypingChange = useEffectEvent(unstable_onTypingChange);\n const findMatchRef = useLatestRef(findMatch);\n const ignoreKeysRef = useLatestRef(ignoreKeys);\n useModernLayoutEffect(() => {\n if (open) {\n clearTimeoutIfSet(timeoutIdRef);\n matchIndexRef.current = null;\n stringRef.current = '';\n }\n }, [open]);\n useModernLayoutEffect(() => {\n // Sync arrow key navigation but not typeahead navigation.\n if (open && stringRef.current === '') {\n var _ref2;\n prevIndexRef.current = (_ref2 = selectedIndex != null ? selectedIndex : activeIndex) != null ? _ref2 : -1;\n }\n }, [open, selectedIndex, activeIndex]);\n const setTypingChange = useEffectEvent(value => {\n if (value) {\n if (!dataRef.current.typing) {\n dataRef.current.typing = value;\n onTypingChange(value);\n }\n } else {\n if (dataRef.current.typing) {\n dataRef.current.typing = value;\n onTypingChange(value);\n }\n }\n });\n const onKeyDown = useEffectEvent(event => {\n function getMatchingIndex(list, orderedList, string) {\n const str = findMatchRef.current ? findMatchRef.current(orderedList, string) : orderedList.find(text => (text == null ? void 0 : text.toLocaleLowerCase().indexOf(string.toLocaleLowerCase())) === 0);\n return str ? list.indexOf(str) : -1;\n }\n const listContent = listRef.current;\n if (stringRef.current.length > 0 && stringRef.current[0] !== ' ') {\n if (getMatchingIndex(listContent, listContent, stringRef.current) === -1) {\n setTypingChange(false);\n } else if (event.key === ' ') {\n stopEvent(event);\n }\n }\n if (listContent == null || ignoreKeysRef.current.includes(event.key) ||\n // Character key.\n event.key.length !== 1 ||\n // Modifier key.\n event.ctrlKey || event.metaKey || event.altKey) {\n return;\n }\n if (open && event.key !== ' ') {\n stopEvent(event);\n setTypingChange(true);\n }\n\n // Bail out if the list contains a word like \"llama\" or \"aaron\". TODO:\n // allow it in this case, too.\n const allowRapidSuccessionOfFirstLetter = listContent.every(text => {\n var _text$, _text$2;\n return text ? ((_text$ = text[0]) == null ? void 0 : _text$.toLocaleLowerCase()) !== ((_text$2 = text[1]) == null ? void 0 : _text$2.toLocaleLowerCase()) : true;\n });\n\n // Allows the user to cycle through items that start with the same letter\n // in rapid succession.\n if (allowRapidSuccessionOfFirstLetter && stringRef.current === event.key) {\n stringRef.current = '';\n prevIndexRef.current = matchIndexRef.current;\n }\n stringRef.current += event.key;\n clearTimeoutIfSet(timeoutIdRef);\n timeoutIdRef.current = window.setTimeout(() => {\n stringRef.current = '';\n prevIndexRef.current = matchIndexRef.current;\n setTypingChange(false);\n }, resetMs);\n const prevIndex = prevIndexRef.current;\n const index = getMatchingIndex(listContent, [...listContent.slice((prevIndex || 0) + 1), ...listContent.slice(0, (prevIndex || 0) + 1)], stringRef.current);\n if (index !== -1) {\n onMatch(index);\n matchIndexRef.current = index;\n } else if (event.key !== ' ') {\n stringRef.current = '';\n setTypingChange(false);\n }\n });\n const reference = React.useMemo(() => ({\n onKeyDown\n }), [onKeyDown]);\n const floating = React.useMemo(() => {\n return {\n onKeyDown,\n onKeyUp(event) {\n if (event.key === ' ') {\n setTypingChange(false);\n }\n }\n };\n }, [onKeyDown, setTypingChange]);\n return React.useMemo(() => enabled ? {\n reference,\n floating\n } : {}, [enabled, reference, floating]);\n}\n\nfunction getArgsWithCustomFloatingHeight(state, height) {\n return {\n ...state,\n rects: {\n ...state.rects,\n floating: {\n ...state.rects.floating,\n height\n }\n }\n };\n}\n/**\n * Positions the floating element such that an inner element inside of it is\n * anchored to the reference element.\n * @see https://floating-ui.com/docs/inner\n * @deprecated\n */\nconst inner = props => ({\n name: 'inner',\n options: props,\n async fn(state) {\n const {\n listRef,\n overflowRef,\n onFallbackChange,\n offset: innerOffset = 0,\n index = 0,\n minItemsVisible = 4,\n referenceOverflowThreshold = 0,\n scrollRef,\n ...detectOverflowOptions\n } = evaluate(props, state);\n const {\n rects,\n platform,\n elements: {\n floating\n }\n } = state;\n const item = listRef.current[index];\n const scrollEl = (scrollRef == null ? void 0 : scrollRef.current) || floating;\n\n // Valid combinations:\n // 1. Floating element is the scrollRef and has a border (default)\n // 2. Floating element is not the scrollRef, floating element has a border\n // 3. Floating element is not the scrollRef, scrollRef has a border\n // Floating > {...getFloatingProps()} wrapper > scrollRef > items is not\n // allowed as VoiceOver doesn't work.\n const clientTop = floating.clientTop || scrollEl.clientTop;\n const floatingIsBordered = floating.clientTop !== 0;\n const scrollElIsBordered = scrollEl.clientTop !== 0;\n const floatingIsScrollEl = floating === scrollEl;\n if (process.env.NODE_ENV !== \"production\") {\n if (!state.placement.startsWith('bottom')) {\n warn('`placement` side must be \"bottom\" when using the `inner`', 'middleware.');\n }\n }\n if (!item) {\n return {};\n }\n const nextArgs = {\n ...state,\n ...(await offset(-item.offsetTop - floating.clientTop - rects.reference.height / 2 - item.offsetHeight / 2 - innerOffset).fn(state))\n };\n const overflow = await platform.detectOverflow(getArgsWithCustomFloatingHeight(nextArgs, scrollEl.scrollHeight + clientTop + floating.clientTop), detectOverflowOptions);\n const refOverflow = await platform.detectOverflow(nextArgs, {\n ...detectOverflowOptions,\n elementContext: 'reference'\n });\n const diffY = max(0, overflow.top);\n const nextY = nextArgs.y + diffY;\n const isScrollable = scrollEl.scrollHeight > scrollEl.clientHeight;\n const rounder = isScrollable ? v => v : round;\n const maxHeight = rounder(max(0, scrollEl.scrollHeight + (floatingIsBordered && floatingIsScrollEl || scrollElIsBordered ? clientTop * 2 : 0) - diffY - max(0, overflow.bottom)));\n scrollEl.style.maxHeight = maxHeight + \"px\";\n scrollEl.scrollTop = diffY;\n\n // There is not enough space, fallback to standard anchored positioning\n if (onFallbackChange) {\n const shouldFallback = scrollEl.offsetHeight < item.offsetHeight * min(minItemsVisible, listRef.current.length) - 1 || refOverflow.top >= -referenceOverflowThreshold || refOverflow.bottom >= -referenceOverflowThreshold;\n ReactDOM.flushSync(() => onFallbackChange(shouldFallback));\n }\n if (overflowRef) {\n overflowRef.current = await platform.detectOverflow(getArgsWithCustomFloatingHeight({\n ...nextArgs,\n y: nextY\n }, scrollEl.offsetHeight + clientTop + floating.clientTop), detectOverflowOptions);\n }\n return {\n y: nextY\n };\n }\n});\n/**\n * Changes the `inner` middleware's `offset` upon a `wheel` event to\n * expand the floating element's height, revealing more list items.\n * @see https://floating-ui.com/docs/inner\n * @deprecated\n */\nfunction useInnerOffset(context, props) {\n const {\n open,\n elements\n } = context;\n const {\n enabled = true,\n overflowRef,\n scrollRef,\n onChange: unstable_onChange\n } = props;\n const onChange = useEffectEvent(unstable_onChange);\n const controlledScrollingRef = React.useRef(false);\n const prevScrollTopRef = React.useRef(null);\n const initialOverflowRef = React.useRef(null);\n React.useEffect(() => {\n if (!enabled) return;\n function onWheel(e) {\n if (e.ctrlKey || !el || overflowRef.current == null) {\n return;\n }\n const dY = e.deltaY;\n const isAtTop = overflowRef.current.top >= -0.5;\n const isAtBottom = overflowRef.current.bottom >= -0.5;\n const remainingScroll = el.scrollHeight - el.clientHeight;\n const sign = dY < 0 ? -1 : 1;\n const method = dY < 0 ? 'max' : 'min';\n if (el.scrollHeight <= el.clientHeight) {\n return;\n }\n if (!isAtTop && dY > 0 || !isAtBottom && dY < 0) {\n e.preventDefault();\n ReactDOM.flushSync(() => {\n onChange(d => d + Math[method](dY, remainingScroll * sign));\n });\n } else if (/firefox/i.test(getUserAgent())) {\n // Needed to propagate scrolling during momentum scrolling phase once\n // it gets limited by the boundary. UX improvement, not critical.\n el.scrollTop += dY;\n }\n }\n const el = (scrollRef == null ? void 0 : scrollRef.current) || elements.floating;\n if (open && el) {\n el.addEventListener('wheel', onWheel);\n\n // Wait for the position to be ready.\n requestAnimationFrame(() => {\n prevScrollTopRef.current = el.scrollTop;\n if (overflowRef.current != null) {\n initialOverflowRef.current = {\n ...overflowRef.current\n };\n }\n });\n return () => {\n prevScrollTopRef.current = null;\n initialOverflowRef.current = null;\n el.removeEventListener('wheel', onWheel);\n };\n }\n }, [enabled, open, elements.floating, overflowRef, scrollRef, onChange]);\n const floating = React.useMemo(() => ({\n onKeyDown() {\n controlledScrollingRef.current = true;\n },\n onWheel() {\n controlledScrollingRef.current = false;\n },\n onPointerMove() {\n controlledScrollingRef.current = false;\n },\n onScroll() {\n const el = (scrollRef == null ? void 0 : scrollRef.current) || elements.floating;\n if (!overflowRef.current || !el || !controlledScrollingRef.current) {\n return;\n }\n if (prevScrollTopRef.current !== null) {\n const scrollDiff = el.scrollTop - prevScrollTopRef.current;\n if (overflowRef.current.bottom < -0.5 && scrollDiff < -1 || overflowRef.current.top < -0.5 && scrollDiff > 1) {\n ReactDOM.flushSync(() => onChange(d => d + scrollDiff));\n }\n }\n\n // [Firefox] Wait for the height change to have been applied.\n requestAnimationFrame(() => {\n prevScrollTopRef.current = el.scrollTop;\n });\n }\n }), [elements.floating, onChange, overflowRef, scrollRef]);\n return React.useMemo(() => enabled ? {\n floating\n } : {}, [enabled, floating]);\n}\n\nfunction getNodeChildren(nodes, id, onlyOpenChildren) {\n if (onlyOpenChildren === void 0) {\n onlyOpenChildren = true;\n }\n const directChildren = nodes.filter(node => {\n var _node$context;\n return node.parentId === id && (!onlyOpenChildren || ((_node$context = node.context) == null ? void 0 : _node$context.open));\n });\n return directChildren.flatMap(child => [child, ...getNodeChildren(nodes, child.id, onlyOpenChildren)]);\n}\n\nfunction isPointInPolygon(point, polygon) {\n const [x, y] = point;\n let isInside = false;\n const length = polygon.length;\n for (let i = 0, j = length - 1; i < length; j = i++) {\n const [xi, yi] = polygon[i] || [0, 0];\n const [xj, yj] = polygon[j] || [0, 0];\n const intersect = yi >= y !== yj >= y && x <= (xj - xi) * (y - yi) / (yj - yi) + xi;\n if (intersect) {\n isInside = !isInside;\n }\n }\n return isInside;\n}\nfunction isInside(point, rect) {\n return point[0] >= rect.x && point[0] <= rect.x + rect.width && point[1] >= rect.y && point[1] <= rect.y + rect.height;\n}\n/**\n * Generates a safe polygon area that the user can traverse without closing the\n * floating element once leaving the reference element.\n * @see https://floating-ui.com/docs/useHover#safepolygon\n */\nfunction safePolygon(options) {\n if (options === void 0) {\n options = {};\n }\n const {\n buffer = 0.5,\n blockPointerEvents = false,\n requireIntent = true\n } = options;\n const timeoutRef = {\n current: -1\n };\n let hasLanded = false;\n let lastX = null;\n let lastY = null;\n let lastCursorTime = typeof performance !== 'undefined' ? performance.now() : 0;\n function getCursorSpeed(x, y) {\n const currentTime = performance.now();\n const elapsedTime = currentTime - lastCursorTime;\n if (lastX === null || lastY === null || elapsedTime === 0) {\n lastX = x;\n lastY = y;\n lastCursorTime = currentTime;\n return null;\n }\n const deltaX = x - lastX;\n const deltaY = y - lastY;\n const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY);\n const speed = distance / elapsedTime; // px / ms\n\n lastX = x;\n lastY = y;\n lastCursorTime = currentTime;\n return speed;\n }\n const fn = _ref => {\n let {\n x,\n y,\n placement,\n elements,\n onClose,\n nodeId,\n tree\n } = _ref;\n return function onMouseMove(event) {\n function close() {\n clearTimeoutIfSet(timeoutRef);\n onClose();\n }\n clearTimeoutIfSet(timeoutRef);\n if (!elements.domReference || !elements.floating || placement == null || x == null || y == null) {\n return;\n }\n const {\n clientX,\n clientY\n } = event;\n const clientPoint = [clientX, clientY];\n const target = getTarget(event);\n const isLeave = event.type === 'mouseleave';\n const isOverFloatingEl = contains(elements.floating, target);\n const isOverReferenceEl = contains(elements.domReference, target);\n const refRect = elements.domReference.getBoundingClientRect();\n const rect = elements.floating.getBoundingClientRect();\n const side = placement.split('-')[0];\n const cursorLeaveFromRight = x > rect.right - rect.width / 2;\n const cursorLeaveFromBottom = y > rect.bottom - rect.height / 2;\n const isOverReferenceRect = isInside(clientPoint, refRect);\n const isFloatingWider = rect.width > refRect.width;\n const isFloatingTaller = rect.height > refRect.height;\n const left = (isFloatingWider ? refRect : rect).left;\n const right = (isFloatingWider ? refRect : rect).right;\n const top = (isFloatingTaller ? refRect : rect).top;\n const bottom = (isFloatingTaller ? refRect : rect).bottom;\n if (isOverFloatingEl) {\n hasLanded = true;\n if (!isLeave) {\n return;\n }\n }\n if (isOverReferenceEl) {\n hasLanded = false;\n }\n if (isOverReferenceEl && !isLeave) {\n hasLanded = true;\n return;\n }\n\n // Prevent overlapping floating element from being stuck in an open-close\n // loop: https://github.com/floating-ui/floating-ui/issues/1910\n if (isLeave && isElement(event.relatedTarget) && contains(elements.floating, event.relatedTarget)) {\n return;\n }\n\n // If any nested child is open, abort.\n if (tree && getNodeChildren(tree.nodesRef.current, nodeId).length) {\n return;\n }\n\n // If the pointer is leaving from the opposite side, the \"buffer\" logic\n // creates a point where the floating element remains open, but should be\n // ignored.\n // A constant of 1 handles floating point rounding errors.\n if (side === 'top' && y >= refRect.bottom - 1 || side === 'bottom' && y <= refRect.top + 1 || side === 'left' && x >= refRect.right - 1 || side === 'right' && x <= refRect.left + 1) {\n return close();\n }\n\n // Ignore when the cursor is within the rectangular trough between the\n // two elements. Since the triangle is created from the cursor point,\n // which can start beyond the ref element's edge, traversing back and\n // forth from the ref to the floating element can cause it to close. This\n // ensures it always remains open in that case.\n let rectPoly = [];\n switch (side) {\n case 'top':\n rectPoly = [[left, refRect.top + 1], [left, rect.bottom - 1], [right, rect.bottom - 1], [right, refRect.top + 1]];\n break;\n case 'bottom':\n rectPoly = [[left, rect.top + 1], [left, refRect.bottom - 1], [right, refRect.bottom - 1], [right, rect.top + 1]];\n break;\n case 'left':\n rectPoly = [[rect.right - 1, bottom], [rect.right - 1, top], [refRect.left + 1, top], [refRect.left + 1, bottom]];\n break;\n case 'right':\n rectPoly = [[refRect.right - 1, bottom], [refRect.right - 1, top], [rect.left + 1, top], [rect.left + 1, bottom]];\n break;\n }\n function getPolygon(_ref2) {\n let [x, y] = _ref2;\n switch (side) {\n case 'top':\n {\n const cursorPointOne = [isFloatingWider ? x + buffer / 2 : cursorLeaveFromRight ? x + buffer * 4 : x - buffer * 4, y + buffer + 1];\n const cursorPointTwo = [isFloatingWider ? x - buffer / 2 : cursorLeaveFromRight ? x + buffer * 4 : x - buffer * 4, y + buffer + 1];\n const commonPoints = [[rect.left, cursorLeaveFromRight ? rect.bottom - buffer : isFloatingWider ? rect.bottom - buffer : rect.top], [rect.right, cursorLeaveFromRight ? isFloatingWider ? rect.bottom - buffer : rect.top : rect.bottom - buffer]];\n return [cursorPointOne, cursorPointTwo, ...commonPoints];\n }\n case 'bottom':\n {\n const cursorPointOne = [isFloatingWider ? x + buffer / 2 : cursorLeaveFromRight ? x + buffer * 4 : x - buffer * 4, y - buffer];\n const cursorPointTwo = [isFloatingWider ? x - buffer / 2 : cursorLeaveFromRight ? x + buffer * 4 : x - buffer * 4, y - buffer];\n const commonPoints = [[rect.left, cursorLeaveFromRight ? rect.top + buffer : isFloatingWider ? rect.top + buffer : rect.bottom], [rect.right, cursorLeaveFromRight ? isFloatingWider ? rect.top + buffer : rect.bottom : rect.top + buffer]];\n return [cursorPointOne, cursorPointTwo, ...commonPoints];\n }\n case 'left':\n {\n const cursorPointOne = [x + buffer + 1, isFloatingTaller ? y + buffer / 2 : cursorLeaveFromBottom ? y + buffer * 4 : y - buffer * 4];\n const cursorPointTwo = [x + buffer + 1, isFloatingTaller ? y - buffer / 2 : cursorLeaveFromBottom ? y + buffer * 4 : y - buffer * 4];\n const commonPoints = [[cursorLeaveFromBottom ? rect.right - buffer : isFloatingTaller ? rect.right - buffer : rect.left, rect.top], [cursorLeaveFromBottom ? isFloatingTaller ? rect.right - buffer : rect.left : rect.right - buffer, rect.bottom]];\n return [...commonPoints, cursorPointOne, cursorPointTwo];\n }\n case 'right':\n {\n const cursorPointOne = [x - buffer, isFloatingTaller ? y + buffer / 2 : cursorLeaveFromBottom ? y + buffer * 4 : y - buffer * 4];\n const cursorPointTwo = [x - buffer, isFloatingTaller ? y - buffer / 2 : cursorLeaveFromBottom ? y + buffer * 4 : y - buffer * 4];\n const commonPoints = [[cursorLeaveFromBottom ? rect.left + buffer : isFloatingTaller ? rect.left + buffer : rect.right, rect.top], [cursorLeaveFromBottom ? isFloatingTaller ? rect.left + buffer : rect.right : rect.left + buffer, rect.bottom]];\n return [cursorPointOne, cursorPointTwo, ...commonPoints];\n }\n }\n }\n if (isPointInPolygon([clientX, clientY], rectPoly)) {\n return;\n }\n if (hasLanded && !isOverReferenceRect) {\n return close();\n }\n if (!isLeave && requireIntent) {\n const cursorSpeed = getCursorSpeed(event.clientX, event.clientY);\n const cursorSpeedThreshold = 0.1;\n if (cursorSpeed !== null && cursorSpeed < cursorSpeedThreshold) {\n return close();\n }\n }\n if (!isPointInPolygon([clientX, clientY], getPolygon([x, y]))) {\n close();\n } else if (!hasLanded && requireIntent) {\n timeoutRef.current = window.setTimeout(close, 40);\n }\n };\n };\n fn.__options = {\n blockPointerEvents\n };\n return fn;\n}\n\nexport { Composite, CompositeItem, FloatingArrow, FloatingDelayGroup, FloatingFocusManager, FloatingList, FloatingNode, FloatingOverlay, FloatingPortal, FloatingTree, NextFloatingDelayGroup, inner, safePolygon, useClick, useClientPoint, useDelayGroup, useDelayGroupContext, useDismiss, useFloating, useFloatingNodeId, useFloatingParentNodeId, useFloatingPortalNode, useFloatingRootContext, useFloatingTree, useFocus, useHover, useId, useInnerOffset, useInteractions, useListItem, useListNavigation, useMergeRefs, useNextDelayGroup, useRole, useTransitionStatus, useTransitionStyles, useTypeahead };\n","import React, { useEffect } from \"react\";\nimport { createPortal } from \"react-dom\";\nimport {\n autoUpdate,\n flip,\n offset as fOffset,\n shift,\n size,\n useFloating,\n type Placement,\n} from \"@floating-ui/react\";\n\ninterface PopoverProps {\n open: boolean;\n anchorEl: HTMLElement | null;\n onClose: () => void;\n placement?: Placement;\n offset?: number;\n sameWidth?: boolean;\n maxHeight?: number | string;\n zIndex?: number;\n className?: string;\n children: React.ReactNode;\n shouldIgnoreClose?: (target: Node) => boolean;\n}\n\nexport const Popover: React.FC<PopoverProps> = ({\n open,\n anchorEl,\n onClose,\n placement = \"bottom-start\",\n offset = 8,\n sameWidth = false,\n maxHeight,\n zIndex = 1000,\n className,\n children,\n shouldIgnoreClose,\n}) => {\n const { refs, floatingStyles, update } = useFloating({\n placement,\n whileElementsMounted: autoUpdate,\n middleware: [\n fOffset(offset),\n flip({ padding: 8 }),\n shift({ padding: 8 }),\n size({\n apply({ rects, elements, availableHeight, availableWidth }) {\n const el = elements.floating as HTMLElement;\n if (!el) return;\n if (sameWidth) {\n el.style.width = `${rects.reference.width}px`;\n }\n if (maxHeight != null) {\n el.style.maxHeight =\n typeof maxHeight === \"number\"\n ? `${maxHeight}px`\n : String(maxHeight);\n } else {\n el.style.maxHeight = `${availableHeight}px`;\n }\n if (availableWidth != null) {\n el.style.maxWidth = `${availableWidth}px`;\n }\n },\n }),\n ],\n });\n\n // Attach the reference programmatically\n useEffect(() => {\n if (anchorEl) refs.setReference(anchorEl);\n // Force an update when anchor changes\n if (open && update) update();\n }, [anchorEl, open, refs, update]);\n\n // Close on outside click and Escape\n useEffect(() => {\n if (!open) return;\n const onMouseDown = (e: MouseEvent) => {\n const t = e.target as Node;\n if (shouldIgnoreClose && shouldIgnoreClose(t)) return;\n const floating = refs.floating.current;\n if (!floating) return;\n if (\n (anchorEl && anchorEl.contains(t)) ||\n (floating && floating.contains(t))\n ) {\n return; // inside\n }\n onClose();\n };\n const onKeyDown = (e: KeyboardEvent) => {\n if (e.key === \"Escape\") onClose();\n };\n document.addEventListener(\"mousedown\", onMouseDown);\n document.addEventListener(\"keydown\", onKeyDown);\n return () => {\n document.removeEventListener(\"mousedown\", onMouseDown);\n document.removeEventListener(\"keydown\", onKeyDown);\n };\n }, [open, onClose, refs.floating, anchorEl]);\n\n if (!open || !anchorEl) return null;\n\n return createPortal(\n <div\n ref={refs.setFloating}\n data-popover-root=\"true\"\n style={{\n ...floatingStyles,\n zIndex,\n position: floatingStyles.position as any,\n overflowX: \"hidden\",\n }}\n className={className}\n >\n {children}\n </div>,\n document.body\n );\n};\n\nexport default Popover;\n","import {\n memo,\n useState,\n useRef,\n useEffect,\n ReactNode,\n ChangeEvent,\n useMemo,\n} from \"react\";\nimport {\n Search,\n Download,\n Filter,\n X,\n FileText,\n Database,\n Table,\n Settings,\n Eye,\n EyeOff,\n MoreHorizontal,\n Trash2,\n Copy,\n Edit,\n Archive,\n LocateFixed,\n} from \"../icons\";\nimport { ColumnFilterSelector } from \"./ColumnFilterSelector\";\nimport Popover from \"./Popover\";\nimport type { Density } from \"../types\";\n\nexport type ExportFormat = \"csv\" | \"json\" | \"xlsx\";\n// SearchMode removed along with UI\nexport type BulkAction = \"delete\" | \"archive\" | \"copy\" | \"edit\" | \"export\";\n\nexport interface BulkActionOption {\n id: BulkAction;\n label: string;\n icon: ReactNode;\n onClick: (selectedRows: Set<string | number>) => void;\n disabled?: boolean;\n destructive?: boolean;\n}\n\ninterface ColumnVisibility {\n [columnKey: string]: boolean;\n}\n\ninterface SavedFilter {\n id: string;\n name: string;\n globalFilter: string;\n columnFilters: Record<string, any>;\n}\n\ninterface SearchToolbarProps {\n globalFilter: string;\n filteredDataLength: number;\n totalDataLength: number;\n paginationMode?: \"client\" | \"server\";\n totalRows?: number;\n selectedRowsCount?: number;\n selectedRows?: Set<string | number>;\n showExport?: boolean;\n showRefresh?: boolean;\n showColumnToggle?: boolean;\n showBulkActions?: boolean;\n showSavedFilters?: boolean;\n columns?: Array<{\n key: string;\n header: string;\n visible?: boolean;\n filterOptions?: Array<{ label: string; value: string | number }>;\n filterType?: \"text\" | \"select\" | \"multiselect\";\n filterable?: any;\n }>;\n columnVisibility?: ColumnVisibility;\n columnFilters?: Record<string, any>;\n savedFilters?: SavedFilter[];\n bulkActions?: BulkActionOption[];\n isLoading?: boolean;\n exportOptions?: {\n enabled: boolean;\n formats?: ExportFormat[];\n filename?: string;\n onExport?: (format: ExportFormat, exportSelected: boolean) => void;\n };\n onGlobalFilterChange: (e: ChangeEvent<HTMLInputElement>) => void;\n onClearFilters?: () => void;\n onRefresh?: () => void;\n onColumnVisibilityChange?: (columnKey: string, visible: boolean) => void;\n onColumnFilter?: (columnKey: string, filter: any) => void;\n onSaveFilter?: (filter: Omit<SavedFilter, \"id\">) => void;\n onLoadFilter?: (filter: SavedFilter) => void;\n onDeleteFilter?: (filterId: string) => void;\n onRowSelect?: (selectedRows: number[]) => void;\n onToggleFilters?: (show: boolean) => void;\n onResetColumns?: () => void;\n // New: reorder support\n columnOrder?: string[];\n onColumnOrderChange?: (order: string[]) => void;\n pinnedColumns?: Set<string>;\n // Scroll to a specific column in the grid\n onScrollToColumn?: (columnKey: string) => void;\n // Density controls\n density?: Density;\n onDensityChange?: (density: Density) => void;\n showDensityControl?: boolean;\n // Custom content slots\n customLeftContent?: ReactNode;\n customRightContent?: ReactNode;\n}\n\nconst SearchToolbarComponent = ({\n globalFilter,\n filteredDataLength,\n selectedRowsCount = 0,\n selectedRows = new Set(),\n showExport = true,\n showColumnToggle = true,\n showBulkActions = true,\n columns = [],\n columnVisibility = {},\n columnFilters = {},\n bulkActions = [],\n exportOptions,\n onGlobalFilterChange,\n onClearFilters,\n onColumnVisibilityChange,\n onColumnFilter,\n onResetColumns,\n columnOrder = [],\n onColumnOrderChange,\n pinnedColumns,\n onScrollToColumn,\n density = \"md\",\n onDensityChange,\n showDensityControl = false,\n customLeftContent,\n customRightContent,\n}: SearchToolbarProps) => {\n const [showExportMenu, setShowExportMenu] = useState(false);\n const [showFilters, setShowFilters] = useState(false);\n const [showBulkActionsMenu, setShowBulkActionsMenu] = useState(false);\n const [showColumnMenu, setShowColumnMenu] = useState(false);\n const [columnSearch, setColumnSearch] = useState(\"\");\n // DnD state for in-menu reordering\n const [draggingKey, setDraggingKey] = useState<string | null>(null);\n const [dragOver, setDragOver] = useState<{\n key: string;\n position: \"before\" | \"after\";\n } | null>(null);\n\n const searchInputRef = useRef<HTMLInputElement>(null);\n const exportMenuRef = useRef<HTMLDivElement>(null);\n const bulkActionsRef = useRef<HTMLDivElement>(null);\n const columnMenuRef = useRef<HTMLDivElement>(null);\n const filtersMenuRef = useRef<HTMLDivElement>(null);\n const filtersAnchorRef = useRef<HTMLButtonElement | null>(null);\n const exportAnchorRef = useRef<HTMLButtonElement | null>(null);\n const bulkActionsAnchorRef = useRef<HTMLButtonElement | null>(null);\n const columnAnchorRef = useRef<HTMLButtonElement | null>(null);\n\n // Close menus when clicking outside\n useEffect(() => {\n const handleClickOutside = (event: MouseEvent) => {\n // If clicking inside any portal popover root, do nothing here.\n const isInAnyPopover = (target: any): boolean => {\n let node: any = target;\n while (node) {\n if (\n (node.getAttribute &&\n node.getAttribute(\"data-popover-root\") === \"true\") ||\n (node.dataset && (node.dataset as any).popoverRoot === \"true\")\n )\n return true;\n node = node.parentNode;\n }\n return false;\n };\n\n if (isInAnyPopover(event.target)) return;\n // Helper: detect if click occurred inside a MUI Date Picker popup so we don't treat it as outside\n const isInMuiDatePicker = (target: any): boolean => {\n let node: any = target;\n while (node) {\n if (node.classList) {\n const cls = Array.from(node.classList).join(\" \");\n if (/MuiPickers|MuiDatePicker|MuiPickersPopper/.test(cls))\n return true;\n }\n // Some pickers add role=\"dialog\"\n if (node.getAttribute && node.getAttribute(\"role\") === \"dialog\") {\n const cls = node.className?.toString() || \"\";\n if (/MuiPickers|MuiDatePicker/.test(cls)) return true;\n }\n node = node.parentNode;\n }\n return false;\n };\n\n if (\n exportMenuRef.current &&\n !exportMenuRef.current.contains(event.target as Node)\n ) {\n setShowExportMenu(false);\n }\n if (\n bulkActionsRef.current &&\n !bulkActionsRef.current.contains(event.target as Node)\n ) {\n setShowBulkActionsMenu(false);\n }\n if (\n columnMenuRef.current &&\n !columnMenuRef.current.contains(event.target as Node)\n ) {\n setShowColumnMenu(false);\n }\n if (\n filtersMenuRef.current &&\n !filtersMenuRef.current.contains(event.target as Node) &&\n !isInMuiDatePicker(event.target)\n ) {\n setShowFilters(false);\n }\n };\n\n document.addEventListener(\"mousedown\", handleClickOutside);\n return () => document.removeEventListener(\"mousedown\", handleClickOutside);\n }, []);\n\n const exportFormats = exportOptions?.formats || [\"xlsx\"];\n const hasActiveFilters =\n (globalFilter?.length ?? 0) > 0 ||\n Object.keys(columnFilters || {}).length > 0;\n const hasSelectedRows = selectedRowsCount > 0;\n const visibleColumnsCount = columns.filter(\n (col) => columnVisibility[col.key] !== false,\n ).length;\n\n // Build ordered list based on columnOrder, append any missing, then filter by search\n const orderedAll = (() => {\n const fromOrder = columnOrder\n .map((k) => columns.find((c) => c.key === k))\n .filter(Boolean) as typeof columns;\n const missing = columns.filter((c) => !columnOrder.includes(c.key));\n return [...fromOrder, ...missing];\n })();\n\n const filteredColumns = orderedAll.filter((c) =>\n c.header?.toLowerCase()?.includes(columnSearch?.toLowerCase()),\n );\n\n // Search mode UI removed per request; default behavior remains in parent handlers.\n\n const getExportIcon = (format: ExportFormat) => {\n switch (format) {\n case \"csv\":\n return <Table size={18} />;\n case \"json\":\n return <Database size={18} />;\n case \"xlsx\":\n return <FileText size={18} />;\n default:\n return <Download size={18} />;\n }\n };\n\n const getBulkActionIcon = (action: BulkAction) => {\n switch (action) {\n case \"delete\":\n return <Trash2 size={18} />;\n case \"archive\":\n return <Archive size={18} />;\n case \"copy\":\n return <Copy size={18} />;\n case \"edit\":\n return <Edit size={18} />;\n case \"export\":\n return <Download size={18} />;\n default:\n return <MoreHorizontal size={18} />;\n }\n };\n\n const getFormatLabel = (format: ExportFormat) => {\n switch (format) {\n case \"csv\":\n return \"CSV\";\n case \"json\":\n return \"JSON\";\n case \"xlsx\":\n return \"Excel\";\n default:\n return format;\n }\n };\n\n const handleExport = (\n format: ExportFormat,\n exportSelected: boolean = false,\n ) => {\n exportOptions?.onExport?.(format, exportSelected);\n setShowExportMenu(false);\n };\n\n const handleBulkAction = (action: BulkActionOption) => {\n if (!action.disabled) {\n action.onClick(selectedRows);\n setShowBulkActionsMenu(false);\n }\n };\n\n const handleColumnToggle = (columnKey: string) => {\n const isVisible = columnVisibility[columnKey] !== false;\n onColumnVisibilityChange?.(columnKey, !isVisible);\n };\n\n // DnD handlers for reordering within menu\n const handleDragStart = (\n columnKey: string,\n e: React.DragEvent<HTMLLabelElement>,\n ) => {\n setDraggingKey(columnKey);\n e.dataTransfer.effectAllowed = \"move\";\n e.dataTransfer.setData(\"text/plain\", columnKey);\n };\n\n const handleDragOver = (\n targetKey: string,\n e: React.DragEvent<HTMLLabelElement>,\n ) => {\n e.preventDefault();\n e.dataTransfer.dropEffect = \"move\";\n const rect = (e.currentTarget as HTMLLabelElement).getBoundingClientRect();\n const midpoint = rect.top + rect.height / 2;\n const position = e.clientY < midpoint ? \"before\" : \"after\";\n setDragOver({ key: targetKey, position });\n };\n\n const handleDrop = (targetKey: string) => {\n const sourceKey = draggingKey;\n if (!sourceKey || sourceKey === targetKey) return;\n\n // respect pinned vs unpinned if provided\n if (pinnedColumns) {\n const sPinned = pinnedColumns.has(sourceKey);\n const tPinned = pinnedColumns.has(targetKey);\n if (sPinned !== tPinned) {\n setDraggingKey(null);\n setDragOver(null);\n return;\n }\n }\n\n const before =\n dragOver?.key === targetKey ? dragOver.position === \"before\" : true;\n const base = (\n columnOrder && columnOrder.length\n ? columnOrder\n : columns.map((c) => c.key)\n ).filter((k) => k !== sourceKey);\n let idx = base.indexOf(targetKey);\n if (idx === -1) {\n onColumnOrderChange?.(base);\n setDraggingKey(null);\n setDragOver(null);\n return;\n }\n if (!before) idx += 1;\n base.splice(idx, 0, sourceKey);\n onColumnOrderChange?.(base);\n setDraggingKey(null);\n setDragOver(null);\n };\n\n const handleDragEnd = () => {\n setDraggingKey(null);\n setDragOver(null);\n };\n\n // Search mode handler removed with UI\n\n const handleResetColumns = () => {\n columns.forEach((column) => {\n onColumnVisibilityChange?.(column.key, column.visible !== false);\n });\n onColumnOrderChange?.(columns.map((column) => column.key));\n onResetColumns?.();\n };\n\n const hasFilterableColumns = useMemo(\n () => columns.some((col) => col.filterable),\n [columns],\n );\n\n return (\n <div\n className=\"bg-white dark:bg-gray-900 border-b border-gray-200 dark:border-gray-700\"\n role=\"toolbar\"\n aria-label=\"Data grid toolbar\"\n >\n {/* Screen reader status region */}\n <div\n id=\"search-results-status\"\n className=\"sr-only\"\n role=\"status\"\n aria-live=\"polite\"\n aria-atomic=\"true\"\n >\n {hasActiveFilters\n ? `Showing ${filteredDataLength} of ${filteredDataLength} rows`\n : `${filteredDataLength} total rows`}\n {hasSelectedRows &&\n `, ${selectedRowsCount} row${\n selectedRowsCount !== 1 ? \"s\" : \"\"\n } selected`}\n </div>\n\n {/* Main Toolbar */}\n <div className=\"px-3 py-2\">\n <div className=\"flex flex-wrap items-center justify-between gap-2 sm:gap-4\">\n {/* Left Section - Actions */}\n <div className=\"order-1 flex items-center flex-wrap gap-2 sm:gap-3\">\n {/* Filter Toggle */}\n <div className=\"relative\" ref={filtersMenuRef}>\n {hasFilterableColumns && (\n <button\n ref={(el) => {\n filtersAnchorRef.current = el;\n }}\n onClick={() => setShowFilters(!showFilters)}\n className={`flex cursor-pointer items-center gap-2 px-3 py-2 border rounded-lg transition-colors ${\n showFilters\n ? \"bg-blue-50 dark:bg-blue-900/40 border-blue-200 dark:border-blue-600 text-blue-700 dark:text-blue-300\"\n : \"border-gray-300 dark:border-gray-600 text-gray-600 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-800\"\n }`}\n title=\"Toggle column filters (Ctrl+K)\"\n aria-label=\"Toggle column filters\"\n aria-haspopup=\"menu\"\n aria-expanded={showFilters}\n aria-controls=\"filters-menu\"\n aria-keyshortcuts=\"Control+K\"\n >\n <Filter className=\"w-4 h-4\" />\n <span className=\"hidden sm:inline\">Filters</span>\n {Object.keys(columnFilters).length > 0 && (\n <button\n type=\"button\"\n onClick={(e) => {\n e.stopPropagation();\n onClearFilters?.();\n }}\n className=\"bg-red-500 cursor-pointer hover:bg-red-600 text-white text-xs px-1.5 py-0.5 rounded-full min-w-5 h-5 flex items-center justify-center transition-all group relative\"\n title=\"Clear all filters\"\n >\n <span className=\"group-hover:hidden\">\n {Object.keys(columnFilters).length}\n </span>\n <X className=\"w-3 h-3 hidden group-hover:block absolute\" />\n </button>\n )}\n </button>\n )}\n <Popover\n open={showFilters}\n anchorEl={filtersAnchorRef.current}\n onClose={() => setShowFilters(false)}\n placement=\"bottom-start\"\n offset={8}\n zIndex={1000}\n maxHeight={520}\n className=\"w-88 sm:w-88 max-w-[90vw] bg-white border border-gray-200 rounded-lg shadow-xl overflow-y-auto min-h-100\"\n shouldIgnoreClose={(target) => {\n // Ignore clicks inside MUI pickers (often portal-rooted)\n let node: any = target;\n while (node) {\n if (node.classList) {\n const cls = Array.from(node.classList).join(\" \");\n if (/MuiPickers|MuiDatePicker|MuiPickersPopper/.test(cls))\n return true;\n }\n if (\n node.getAttribute &&\n node.getAttribute(\"role\") === \"dialog\"\n ) {\n const cls = node.className?.toString() || \"\";\n if (/MuiPickers|MuiDatePicker/.test(cls)) return true;\n }\n node = node.parentNode;\n }\n return false;\n }}\n >\n <div className=\"flex items-center justify-between px-2\">\n <div className=\"p-3 border-b border-gray-100\">\n <h3 className=\"font-medium text-gray-900\">\n Column Filters\n </h3>\n <p className=\"text-xs text-gray-500 mt-1\">\n Filter data by column values\n </p>\n </div>\n <button\n onClick={onClearFilters}\n className=\"px-3 py-1.5 text-sm text-gray-600 border border-gray-300 rounded-md hover:bg-gray-50 transition-colors\"\n >\n Clear All\n </button>\n </div>\n <div className=\"p-3 space-y-3\">\n <ColumnFilterSelector\n columns={columns}\n columnFilters={columnFilters}\n onColumnFilter={onColumnFilter}\n />\n </div>\n <div className=\"flex items-center justify-between p-3 border-t border-gray-200\">\n <div className=\"text-sm text-gray-600\">\n {Object.keys(columnFilters).length > 0 && (\n <span>\n {Object.keys(columnFilters).length} filter\n {Object.keys(columnFilters).length !== 1\n ? \"s\"\n : \"\"}{\" \"}\n applied\n </span>\n )}\n </div>\n </div>\n </Popover>\n </div>\n\n {/* Custom Left Content Slot */}\n {customLeftContent}\n </div>\n\n {/* Right Section - Actions */}\n <div className=\"order-2 flex items-center gap-2 sm:gap-3 flex-wrap sm:flex-nowrap\">\n {/* Custom Right Content Slot */}\n {customRightContent}\n {/* Search mode option removed */}\n\n {/* Bulk Actions */}\n {showBulkActions && hasSelectedRows && bulkActions.length > 0 && (\n <div className=\"relative\" ref={bulkActionsRef}>\n <button\n ref={(el) => {\n bulkActionsAnchorRef.current = el;\n }}\n onClick={() => setShowBulkActionsMenu(!showBulkActionsMenu)}\n className=\"flex items-center gap-2 px-3 py-2.5 bg-orange-600 text-white rounded-lg hover:bg-orange-700 transition-colors\"\n title=\"Bulk actions\"\n >\n <MoreHorizontal className=\"w-4 h-4\" />\n <span className=\"hidden sm:inline text-sm font-medium\">\n Actions ({selectedRowsCount})\n </span>\n </button>\n <Popover\n open={showBulkActionsMenu}\n anchorEl={bulkActionsAnchorRef.current}\n onClose={() => setShowBulkActionsMenu(false)}\n placement=\"bottom-end\"\n offset={8}\n zIndex={1000}\n className=\"w-56 bg-white border border-gray-200 rounded-lg shadow-xl\"\n >\n <div className=\"p-3 border-b border-gray-100\">\n <h3 className=\"font-medium text-gray-900\">Bulk Actions</h3>\n <p className=\"text-xs text-gray-500 mt-1\">\n {selectedRowsCount} row\n {selectedRowsCount !== 1 ? \"s\" : \"\"} selected\n </p>\n </div>\n <div className=\"p-2\">\n {bulkActions.map((action) => (\n <button\n key={action.id}\n onClick={() => handleBulkAction(action)}\n disabled={action.disabled}\n className={`w-full flex items-center gap-3 px-3 py-2 text-sm rounded-md transition-colors ${\n action.disabled\n ? \"text-gray-400 cursor-not-allowed\"\n : action.destructive\n ? \"text-red-700 hover:bg-red-50\"\n : \"text-gray-700 hover:bg-gray-50\"\n }`}\n >\n {getBulkActionIcon(action.id)}\n {action.label}\n </button>\n ))}\n </div>\n </Popover>\n </div>\n )}\n\n {/* Column Visibility Toggle */}\n {showColumnToggle && columns.length > 0 && (\n <div className=\"relative\" ref={columnMenuRef}>\n <button\n ref={(el) => {\n columnAnchorRef.current = el;\n }}\n onClick={() => setShowColumnMenu(!showColumnMenu)}\n className=\"flex items-center gap-2 px-3 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors\"\n title=\"Column visibility\"\n aria-label={`Column visibility. ${visibleColumnsCount} of ${columns.length} columns visible`}\n aria-haspopup=\"menu\"\n aria-expanded={showColumnMenu}\n aria-controls=\"column-visibility-menu\"\n >\n <Settings className=\"w-4 h-4\" />\n <span className=\"hidden sm:inline text-sm font-medium\">\n Columns\n </span>\n <span className=\"hidden sm:inline text-xs text-gray-500\">\n ({visibleColumnsCount}/{columns.length})\n </span>\n </button>\n\n {/* Column Visibility Dropdown */}\n <Popover\n open={showColumnMenu}\n anchorEl={columnAnchorRef.current}\n onClose={() => setShowColumnMenu(false)}\n placement=\"bottom-end\"\n offset={8}\n zIndex={1000}\n className=\"w-[90vw] sm:w-72 max-w-[90vw] bg-white border border-gray-200 rounded-lg shadow-xl\"\n >\n <div className=\"p-3 border-b border-gray-100\">\n <h3 className=\"font-medium text-gray-900\">\n Show/Hide Columns\n </h3>\n <div className=\"relative mt-2\">\n <Search className=\"absolute left-2 top-1/2 -translate-y-1/2 text-gray-400 w-4 h-4\" />\n <input\n type=\"text\"\n placeholder=\"Search columns...\"\n className=\"w-full pl-8 pr-2 py-1.5 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-sm\"\n value={columnSearch}\n onChange={(e) => setColumnSearch(e.target.value)}\n />\n </div>\n </div>\n <div className=\"max-h-60 overflow-y-auto p-2\">\n {filteredColumns.map((column) => {\n const isVisible = columnVisibility[column.key] !== false;\n return (\n <label\n key={column.key}\n className={`flex items-center gap-3 p-2 hover:bg-gray-50 rounded-md cursor-grab relative ${\n draggingKey === column.key ? \"opacity-60\" : \"\"\n }`}\n draggable\n onDragStart={(e) => handleDragStart(column.key, e)}\n onDragOver={(e) => handleDragOver(column.key, e)}\n onDrop={() => handleDrop(column.key)}\n onDragEnd={handleDragEnd}\n >\n {dragOver?.key === column.key && (\n <span\n className=\"absolute left-2 right-2 h-0.5 bg-blue-600\"\n style={{\n top:\n dragOver.position === \"before\"\n ? 0\n : undefined,\n bottom:\n dragOver.position === \"after\" ? 0 : undefined,\n }}\n />\n )}\n <input\n type=\"checkbox\"\n checked={isVisible}\n onChange={() => handleColumnToggle(column.key)}\n className=\"rounded border-gray-300 text-blue-600 focus:ring-blue-500\"\n />\n {isVisible ? (\n <Eye className=\"w-4 h-4 text-green-600\" />\n ) : (\n <EyeOff className=\"w-4 h-4 text-gray-400\" />\n )}\n <span className=\"text-sm text-gray-700\">\n {column.header}\n </span>\n <button\n type=\"button\"\n onClick={(e) => {\n e.preventDefault();\n e.stopPropagation();\n // Ensure column is visible before scrolling\n if (!isVisible) {\n onColumnVisibilityChange?.(column.key, true);\n // Wait for visibility update to render before scrolling\n requestAnimationFrame(() =>\n onScrollToColumn?.(column.key),\n );\n } else {\n onScrollToColumn?.(column.key);\n }\n }}\n className=\"ml-auto p-1 text-gray-400 hover:text-blue-600\"\n title=\"Scroll to this column\"\n aria-label={`Scroll to column ${column.header}`}\n >\n <LocateFixed className=\"w-4 h-4\" />\n </button>\n </label>\n );\n })}\n </div>\n <div className=\"p-2 border-t border-gray-100\">\n <div className=\"flex items-center justify-between\">\n <label className=\"flex items-center gap-2 text-sm text-gray-600 hover:text-gray-900 cursor-pointer hover:bg-gray-50 px-3 py-1.5 rounded transition-colors min-h-9\">\n <input\n type=\"checkbox\"\n checked={filteredColumns.every(\n (col) => columnVisibility[col.key] !== false,\n )}\n onChange={(e) => {\n filteredColumns.forEach((column) => {\n onColumnVisibilityChange?.(\n column.key,\n e.target.checked,\n );\n });\n }}\n className=\"rounded border-gray-300 text-blue-600 focus:ring-blue-500\"\n />\n <span>Select All</span>\n </label>\n <button\n className=\"text-sm text-gray-600 hover:text-gray-900 hover:bg-gray-50 px-3 py-1.5 rounded transition-colors min-h-9\"\n onClick={() => {\n handleResetColumns();\n setShowColumnMenu(false);\n }}\n >\n Reset Columns\n </button>\n </div>\n {columnSearch && (\n <button\n className=\"text-xs text-blue-600 hover:underline mt-2\"\n onClick={() => setColumnSearch(\"\")}\n >\n Clear Search\n </button>\n )}\n </div>\n </Popover>\n </div>\n )}\n\n {/* Density Selector */}\n {showDensityControl && (\n <div className=\"flex items-center\">\n <div\n className=\"flex items-center gap-1 border border-gray-300 rounded-lg p-1\"\n title=\"Row density\"\n >\n {([\"sm\", \"md\", \"lg\"] as Density[]).map((d) => (\n <button\n key={d}\n className={`px-2 py-1 text-xs rounded-md ${\n density === d\n ? \"bg-blue-600 text-white\"\n : \"text-gray-700 hover:bg-gray-100\"\n }`}\n onClick={() => onDensityChange?.(d)}\n >\n {d.toUpperCase()}\n </button>\n ))}\n </div>\n </div>\n )}\n\n {/* Enhanced Search Panel - Right aligned */}\n <div className=\"flex items-center gap-2 order-3 w-full sm:order-0 sm:w-auto flex-1 min-w-0\">\n {/* Search Input with integrated match type */}\n <div className=\"relative\">\n <Search\n className=\"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4\"\n aria-hidden=\"true\"\n />\n <input\n ref={searchInputRef}\n type=\"text\"\n placeholder={`Search...`}\n className=\"w-full sm:w-64 pl-10 pr-10 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-800 dark:text-gray-200 transition-colors\"\n value={globalFilter}\n onChange={onGlobalFilterChange}\n aria-label=\"Search all columns\"\n aria-keyshortcuts=\"Control+F\"\n aria-describedby=\"search-results-status\"\n />\n {globalFilter && (\n <button\n onClick={() =>\n onGlobalFilterChange({\n target: { value: \"\" },\n } as ChangeEvent<HTMLInputElement>)\n }\n className=\"absolute right-2 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600 transition-colors\"\n title=\"Clear search\"\n >\n <X className=\"w-4 h-4\" />\n </button>\n )}\n </div>\n </div>\n\n {/* Export Icon Button */}\n {showExport && exportOptions?.enabled && (\n <div className=\"relative\" ref={exportMenuRef}>\n <button\n ref={(el) => {\n exportAnchorRef.current = el;\n }}\n onClick={() => setShowExportMenu(!showExportMenu)}\n className=\"p-2.5 cursor-pointer border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800 text-gray-700 dark:text-gray-300 transition-colors\"\n aria-label={`Export data${\n hasSelectedRows\n ? ` (${selectedRowsCount} rows selected)`\n : ` (${filteredDataLength} rows)`\n }`}\n aria-haspopup=\"menu\"\n aria-expanded={showExportMenu}\n aria-controls=\"export-menu\"\n aria-keyshortcuts=\"Control+E\"\n title=\"Export data (Ctrl+E)\"\n >\n <Download className=\"w-4 h-4\" />\n </button>\n <Popover\n open={showExportMenu}\n anchorEl={exportAnchorRef.current}\n onClose={() => setShowExportMenu(false)}\n placement=\"bottom-end\"\n offset={8}\n zIndex={1000}\n className=\"w-[90vw] sm:w-64 max-w-[90vw] bg-white border border-gray-200 rounded-lg shadow-xl\"\n >\n <div className=\"p-3 border-b border-gray-100\">\n <h3 className=\"font-medium text-gray-900\">Export Data</h3>\n <p className=\"text-xs text-gray-500 mt-1\">\n Choose format and data scope\n </p>\n </div>\n\n <div className=\"p-2\">\n {/* Export All */}\n <div className=\"mb-3\">\n <p className=\"text-xs font-medium text-gray-700 mb-2 px-2\">\n Export All Data\n </p>\n <div className=\"space-y-1\">\n {exportFormats.map((format) => (\n <button\n key={`all-${format}`}\n onClick={() => handleExport(format, false)}\n className=\" cursor-pointer w-full flex items-center gap-3 px-3 py-2 text-sm text-gray-700 hover:bg-gray-50 rounded-md transition-colors\"\n >\n {getExportIcon(format)}\n <span>Export as {getFormatLabel(format)}</span>\n <span className=\"ml-auto text-xs text-gray-500\">\n {filteredDataLength.toLocaleString()} rows\n </span>\n </button>\n ))}\n </div>\n </div>\n\n {/* Export Selected */}\n {hasSelectedRows && (\n <div>\n <p className=\"text-xs font-medium text-gray-700 mb-2 px-2\">\n Export Selected\n </p>\n <div className=\"space-y-1\">\n {exportFormats.map((format) => (\n <button\n key={`selected-${format}`}\n onClick={() => handleExport(format, true)}\n className=\"w-full flex items-center gap-3 px-3 py-2 text-sm text-blue-700 hover:bg-blue-50 rounded-md transition-colors\"\n >\n {getExportIcon(format)}\n <span>Export as {getFormatLabel(format)}</span>\n <span className=\"ml-auto text-xs text-blue-500\">\n {selectedRowsCount} rows\n </span>\n </button>\n ))}\n </div>\n </div>\n )}\n </div>\n </Popover>\n </div>\n )}\n </div>\n </div>\n </div>\n </div>\n );\n};\n\nSearchToolbarComponent.displayName = \"SearchToolbar\";\nexport const SearchToolbar = /*#__PURE__*/ memo(SearchToolbarComponent);\n","import {\n useState,\n useMemo,\n useCallback,\n useDeferredValue,\n useRef,\n useTransition,\n} from \"react\";\nimport {\n GridRow,\n GridColumn,\n ActiveFilters,\n ColumnFilterValue,\n} from \"../types\";\n\ninterface UseAdvancedFilteringProps {\n data: GridRow[];\n columns: GridColumn[];\n}\n\nexport const useAdvancedFiltering = ({\n data,\n columns,\n}: UseAdvancedFilteringProps) => {\n const [globalFilterState, setGlobalFilterState] = useState<string>(\"\");\n const [columnFilters, setColumnFilters] = useState<ActiveFilters>({});\n\n const [isFilterPending, startFilterTransition] = useTransition();\n const [, startColumnFilterTransition] = useTransition();\n\n // Public setter wraps update in a transition so the input field never lags\n const setGlobalFilter = useCallback((value: string) => {\n startFilterTransition(() => setGlobalFilterState(value));\n }, []);\n\n const deferredGlobalFilter = useDeferredValue(globalFilterState);\n\n const applyColumnFilter = useCallback(\n (\n row: GridRow,\n columnKey: string,\n filter: ColumnFilterValue,\n precomputed?: { filterTs?: number; secondTs?: number },\n ): boolean => {\n const value = row[columnKey];\n\n switch (filter.type) {\n case \"text\": {\n const textValue = String(value || \"\").toLowerCase();\n const filterText = String(filter.value || \"\").toLowerCase();\n switch (filter.operator) {\n case \"contains\":\n return textValue.includes(filterText);\n case \"equals\":\n return textValue === filterText;\n case \"startsWith\":\n return textValue.startsWith(filterText);\n case \"endsWith\":\n return textValue.endsWith(filterText);\n default:\n return textValue.includes(filterText);\n }\n }\n case \"number\": {\n const numValue = parseFloat(value);\n const filterNum = parseFloat(filter.value);\n if (isNaN(numValue) || isNaN(filterNum)) return false;\n switch (filter.operator) {\n case \"equals\":\n return numValue === filterNum;\n case \"gt\":\n return numValue > filterNum;\n case \"gte\":\n return numValue >= filterNum;\n case \"lt\":\n return numValue < filterNum;\n case \"lte\":\n return numValue <= filterNum;\n case \"between\": {\n const secondNum = parseFloat(filter.secondValue);\n return (\n !isNaN(secondNum) &&\n numValue >= filterNum &&\n numValue <= secondNum\n );\n }\n default:\n return numValue === filterNum;\n }\n }\n case \"date\": {\n // Use pre-parsed timestamps when available (avoids O(n) Date allocations)\n const filterTs = precomputed?.filterTs;\n const secondTs = precomputed?.secondTs;\n if (filterTs === undefined || isNaN(filterTs)) return false;\n\n const raw = new Date(value);\n if (isNaN(raw.getTime())) return false;\n const rowTs = new Date(\n raw.getFullYear(),\n raw.getMonth(),\n raw.getDate(),\n ).getTime();\n\n switch (filter.operator) {\n case \"equals\":\n return rowTs === filterTs;\n case \"gt\":\n return rowTs > filterTs;\n case \"gte\":\n return rowTs >= filterTs;\n case \"lt\":\n return rowTs < filterTs;\n case \"lte\":\n return rowTs <= filterTs;\n case \"between\":\n return (\n secondTs !== undefined &&\n !isNaN(secondTs) &&\n rowTs >= filterTs &&\n rowTs <= secondTs\n );\n default:\n return rowTs === filterTs;\n }\n }\n case \"boolean\":\n return Boolean(value) === Boolean(filter.value);\n\n case \"multiselect\": {\n const filterValues = Array.isArray(filter.value)\n ? filter.value\n : [filter.value];\n const normalizeBlank = (val: any) =>\n val === null ||\n val === undefined ||\n val === \"\" ||\n (typeof val === \"string\" && val.trim() === \"\")\n ? null\n : val;\n return filterValues\n .map(normalizeBlank)\n .includes(normalizeBlank(value));\n }\n default:\n return true;\n }\n },\n [],\n );\n\n // Optimized search cache with size limits for large datasets\n const rowSearchCacheRef = useRef<WeakMap<GridRow, string>>(new WeakMap());\n const cacheSizeRef = useRef(0);\n const maxCacheSize = 5000;\n\n const clearCacheIfNeeded = useCallback(() => {\n if (cacheSizeRef.current > maxCacheSize) {\n rowSearchCacheRef.current = new WeakMap();\n cacheSizeRef.current = 0;\n }\n }, []);\n\n const filteredData = useMemo(() => {\n clearCacheIfNeeded();\n\n const hasColumnFilters = Object.keys(columnFilters).length > 0;\n const hasGlobal = !!deferredGlobalFilter;\n if (!hasColumnFilters && !hasGlobal) return data;\n\n const lowerGlobal = deferredGlobalFilter.toLowerCase();\n const cache = rowSearchCacheRef.current!;\n let working = data;\n\n // Apply column filters first (usually more selective).\n // For date filters: pre-parse the filter timestamps ONCE here so that\n // applyColumnFilter doesn't create new Date() objects per row (O(n) allocs).\n if (hasColumnFilters) {\n for (const [columnKey, filter] of Object.entries(columnFilters)) {\n if (!filter) continue;\n\n // Pre-compute date timestamps for date-type filters\n let precomputed: { filterTs?: number; secondTs?: number } | undefined;\n if (filter.type === \"date\") {\n const fd = new Date(filter.value);\n const filterTs = isNaN(fd.getTime())\n ? NaN\n : new Date(fd.getFullYear(), fd.getMonth(), fd.getDate()).getTime();\n let secondTs: number | undefined;\n if (filter.secondValue) {\n const sd = new Date(filter.secondValue);\n secondTs = isNaN(sd.getTime())\n ? NaN\n : new Date(\n sd.getFullYear(),\n sd.getMonth(),\n sd.getDate(),\n ).getTime();\n }\n precomputed = { filterTs, secondTs };\n }\n\n working = working.filter((row) =>\n applyColumnFilter(row, columnKey, filter, precomputed),\n );\n if (working.length === 0) break;\n }\n }\n\n // Apply global filter with cache\n if (hasGlobal && working.length > 0) {\n const visibleColumns = columns.filter((col) => col.visible !== false);\n working = working.filter((row) => {\n let packed = cache.get(row);\n if (packed == null) {\n packed = visibleColumns\n .map((c) => {\n const v = row[c.key];\n if (v == null) return \"\";\n if (typeof v === \"string\") return v.toLowerCase();\n if (typeof v === \"number\" || typeof v === \"boolean\")\n return String(v).toLowerCase();\n const s = String(v);\n return s.length > 100 ? s.slice(0, 100) : s;\n })\n .join(\"|\");\n if (cacheSizeRef.current < maxCacheSize) {\n cache.set(row, packed);\n cacheSizeRef.current++;\n }\n }\n return packed.includes(lowerGlobal);\n });\n }\n\n return working;\n }, [\n data,\n columnFilters,\n deferredGlobalFilter,\n columns,\n applyColumnFilter,\n clearCacheIfNeeded,\n ]);\n\n const setColumnFilter = useCallback(\n (columnKey: string, filter: ColumnFilterValue | null) => {\n // Column filter changes also go through a transition so the grid stays\n // responsive while the filter dropdown is still open\n startColumnFilterTransition(() => {\n setColumnFilters((prev) => {\n const next = { ...prev };\n if (filter) {\n next[columnKey] = filter;\n } else {\n delete next[columnKey];\n }\n return next;\n });\n });\n },\n [],\n );\n\n const clearColumnFilter = useCallback(\n (columnKey: string) => {\n setColumnFilter(columnKey, null);\n },\n [setColumnFilter],\n );\n\n const clearAllFilters = useCallback(() => {\n startFilterTransition(() => setGlobalFilterState(\"\"));\n startColumnFilterTransition(() => setColumnFilters({}));\n rowSearchCacheRef.current = new WeakMap();\n cacheSizeRef.current = 0;\n }, []);\n\n const getActiveFilterCount = useCallback(() => {\n let count = 0;\n if (deferredGlobalFilter) count++;\n return count + Object.keys(columnFilters).length;\n }, [deferredGlobalFilter, columnFilters]);\n\n return {\n globalFilter: globalFilterState,\n setGlobalFilter,\n columnFilters,\n filteredData,\n setColumnFilter,\n clearColumnFilter,\n clearAllFilters,\n getActiveFilterCount,\n /** True while a filter transition is in-flight — use to show a loading indicator */\n isFilterPending,\n };\n};\n","import { useCallback, useEffect, useRef } from \"react\";\n\ntype SortCfg = { key: string; direction: \"asc\" | \"desc\" } | null;\n\n/**\n * Inline worker factory — serialised to a Blob so no external .ts file is\n * referenced at runtime. Avoids the \"Could not resolve entry module\" error\n * that occurs when downstream bundlers follow new URL(..., import.meta.url)\n * from a published npm package.\n */\nfunction workerFactory() {\n const ctx = self as any;\n\n const processData = (\n rows: any[],\n sort?: { key: string; direction: \"asc\" | \"desc\" } | null,\n ) => {\n if (!rows || rows.length === 0) return rows;\n if (!sort?.key) return rows;\n const { key, direction } = sort;\n const dir = direction === \"asc\" ? 1 : -1;\n return [...rows].sort((a, b) => {\n const av = a?.[key];\n const bv = b?.[key];\n if (av == null && bv == null) return 0;\n if (av == null) return -1 * dir;\n if (bv == null) return 1 * dir;\n if (typeof av === \"number\" && typeof bv === \"number\")\n return (av - bv) * dir;\n return String(av).localeCompare(String(bv)) * dir;\n });\n };\n\n ctx.onmessage = (e: MessageEvent) => {\n const msg = e.data;\n if (!msg || msg.type !== \"process\") return;\n try {\n const { rows, sort } = msg.payload;\n ctx.postMessage({\n type: \"result\",\n payload: { rows: processData(rows, sort ?? null) },\n });\n } catch {\n ctx.postMessage({\n type: \"result\",\n payload: { rows: msg.payload?.rows ?? [] },\n });\n }\n };\n}\n\n/** Lazily-created worker singleton per hook instance. */\nexport function useDataWorker(options?: { enabled?: boolean }) {\n const enabled = options?.enabled ?? true;\n const workerRef = useRef<Worker | null>(null);\n /** Holds both the resolve AND reject so we can cancel in-flight calls. */\n const resolverRef = useRef<{\n resolve: (rows: any[]) => void;\n reject: (reason?: any) => void;\n } | null>(null);\n const enabledRef = useRef(enabled);\n\n // Keep enabledRef in sync without affecting process() identity\n useEffect(() => {\n enabledRef.current = enabled;\n // If disabled after being enabled, terminate any live worker\n if (!enabled && workerRef.current) {\n workerRef.current.terminate();\n workerRef.current = null;\n if (resolverRef.current) {\n resolverRef.current.reject(\n new DOMException(\"Worker disabled\", \"AbortError\"),\n );\n resolverRef.current = null;\n }\n }\n }, [enabled]);\n\n /**\n * ensureWorker is kept in a ref so that `process` below never needs it in\n * its dependency array — giving `process` a permanently stable identity.\n * Without this, every time `useCallback` re-creates ensureWorker (e.g. when\n * `enabled` changes), `process` also gets a new reference, which triggers\n * the sort useEffect in DataGrid.tsx and causes an unnecessary re-sort.\n */\n const ensureWorkerRef = useRef<() => Worker | null>(() => null);\n\n ensureWorkerRef.current = () => {\n if (!enabledRef.current) return null;\n if (workerRef.current) return workerRef.current;\n\n const code = `(${workerFactory.toString()})()`;\n const blob = new Blob([code], { type: \"application/javascript\" });\n const blobUrl = URL.createObjectURL(blob);\n const w = new Worker(blobUrl);\n // Revoke immediately — browser has already parsed the script at this point.\n // The Worker thread holds its own internal reference, so this is safe and\n // prevents the object URL from leaking until the tab is closed.\n URL.revokeObjectURL(blobUrl);\n\n w.onmessage = (e: MessageEvent) => {\n if (e.data?.type === \"result\") {\n resolverRef.current?.resolve(e.data.payload.rows);\n resolverRef.current = null;\n }\n };\n\n workerRef.current = w;\n return w;\n };\n\n useEffect(() => {\n return () => {\n workerRef.current?.terminate();\n workerRef.current = null;\n if (resolverRef.current) {\n resolverRef.current.reject(new DOMException(\"Unmounted\", \"AbortError\"));\n resolverRef.current = null;\n }\n };\n }, []);\n\n /**\n * `process` has an EMPTY dependency array — it is stable for the entire\n * lifetime of the component. This means the sort useEffect in DataGrid.tsx\n * (which lists `workerProcess` as a dep) will NEVER fire due to a changed\n * process identity — only when the data/sort config actually changes.\n */\n const process = useCallback(\n (rows: any[], sort: SortCfg): Promise<any[]> => {\n if (!enabledRef.current) return Promise.resolve(rows);\n\n const w = ensureWorkerRef.current();\n if (!w) return Promise.resolve(rows);\n\n return new Promise<any[]>((resolve, reject) => {\n // Cancel any in-flight call — its promise is rejected with AbortError\n // so the caller can safely ignore it (e.g. .catch(() => {}) or check error.name)\n if (resolverRef.current) {\n resolverRef.current.reject(\n new DOMException(\"Superseded by newer sort\", \"AbortError\"),\n );\n }\n resolverRef.current = { resolve, reject };\n w.postMessage({ type: \"process\", payload: { rows, sort } });\n });\n },\n [], // ← stable forever: reads enabled via ref, worker via ref\n );\n\n return { process };\n}\n","import { useCallback } from \"react\";\nimport { GridRow, GridColumn } from \"../types\";\n\nexport type ExportFormat = \"csv\" | \"json\" | \"xlsx\";\n\ninterface UseExportProps {\n data: GridRow[];\n columns: GridColumn[];\n selectedRows?: Set<string | number>;\n filename?: string;\n columnVisibility?: Record<string, boolean>;\n}\n\nexport const useExport = ({\n data,\n columns,\n selectedRows,\n filename = \"data\",\n columnVisibility,\n}: UseExportProps) => {\n // Filter only visible columns (computed inline — no extra state)\n const getVisibleColumns = useCallback(\n () =>\n columnVisibility\n ? columns.filter((col) => columnVisibility[col.key] !== false)\n : columns,\n [columns, columnVisibility],\n );\n\n const downloadFile = useCallback(\n (content: string, fileName: string, mimeType: string) => {\n const blob = new Blob([content], { type: mimeType });\n const url = URL.createObjectURL(blob);\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = fileName;\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n URL.revokeObjectURL(url);\n },\n [],\n );\n\n const exportToCSV = useCallback(\n (exportData: GridRow[], exportFilename: string) => {\n const visibleColumns = getVisibleColumns();\n const headers = visibleColumns.map((col) => col.header).join(\",\");\n const rows = exportData.map((row) =>\n visibleColumns\n .map((col) => {\n const value = row[col.key];\n const s = String(value ?? \"\");\n return s.includes(\",\") || s.includes('\"')\n ? `\"${s.replace(/\"/g, '\"\"')}\"`\n : s;\n })\n .join(\",\"),\n );\n downloadFile(\n [headers, ...rows].join(\"\\n\"),\n `${exportFilename}.csv`,\n \"text/csv\",\n );\n },\n [getVisibleColumns, downloadFile],\n );\n\n const exportToJSON = useCallback(\n (exportData: GridRow[], exportFilename: string) => {\n const visibleColumns = getVisibleColumns();\n const jsonData = exportData.map((row) => {\n const out: Record<string, any> = {};\n for (const col of visibleColumns) out[col.header] = row[col.key];\n return out;\n });\n downloadFile(\n JSON.stringify(jsonData, null, 2),\n `${exportFilename}.json`,\n \"application/json\",\n );\n },\n [getVisibleColumns, downloadFile],\n );\n\n /**\n * XLSX export uses dynamic imports so that ExcelJS (~600 KB) and file-saver\n * are NEVER included in the initial bundle. They are only fetched when the\n * user actually requests an xlsx export.\n */\n const exportToXLSX = useCallback(\n async (exportData: GridRow[], exportFilename: string) => {\n const visibleColumns = getVisibleColumns();\n\n // Lazy-load heavy dependencies — won't appear in the main bundle\n const [{ default: ExcelJS }, { saveAs }] = await Promise.all([\n import(\"exceljs\"),\n import(\"file-saver\"),\n ]);\n\n const workbook = new ExcelJS.Workbook();\n const sheet = workbook.addWorksheet(\"Data\");\n\n const SAMPLE_COUNT = 50;\n const sampled = exportData.slice(0, SAMPLE_COUNT);\n\n const coerceValue = (v: any) => {\n if (v == null) return \"\";\n if (\n typeof v === \"number\" ||\n typeof v === \"boolean\" ||\n v instanceof Date\n )\n return v;\n const s = String(v);\n if (/[a-zA-Z]/.test(s)) return s;\n if (/^-?[\\d,]+\\.?\\d*$/.test(s.trim())) {\n const n = Number(s.replace(/,/g, \"\"));\n if (Number.isFinite(n)) return n;\n }\n return s;\n };\n\n sheet.columns = visibleColumns.map((col) => {\n const header = col.header || col.key;\n let maxLen = header?.length || 10;\n for (const row of sampled) {\n const s = row[col.key] == null ? \"\" : String(row[col.key]);\n if (s.length > maxLen) maxLen = s.length;\n }\n return {\n header,\n key: col.key,\n width: Math.max(8, Math.min(50, Math.ceil(maxLen * 1.1))),\n };\n });\n\n for (const row of exportData) {\n const obj: Record<string, any> = {};\n for (const col of visibleColumns)\n obj[col.key] = coerceValue(row[col.key]);\n sheet.addRow(obj);\n }\n\n const headerRow = sheet.getRow(1);\n headerRow.font = { bold: true };\n sheet.autoFilter = {\n from: { row: 1, column: 1 },\n to: { row: Math.max(1, sheet.rowCount), column: visibleColumns.length },\n };\n\n const buffer = await workbook.xlsx.writeBuffer();\n saveAs(\n new Blob([buffer], {\n type: \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\",\n }),\n `${exportFilename}.xlsx`,\n );\n },\n [getVisibleColumns],\n );\n\n const exportData = useCallback(\n (format: ExportFormat, exportSelected = false) => {\n const rows =\n exportSelected && selectedRows && selectedRows.size > 0\n ? data.filter((row) => selectedRows.has(row.id))\n : data;\n\n const name =\n exportSelected && selectedRows && selectedRows.size > 0\n ? `${filename}_selected_${selectedRows.size}_rows`\n : filename;\n\n switch (format) {\n case \"csv\":\n exportToCSV(rows, name);\n break;\n case \"json\":\n exportToJSON(rows, name);\n break;\n case \"xlsx\":\n void exportToXLSX(rows, name);\n break;\n default:\n console.warn(`[KDGrid] Unsupported export format: ${format}`);\n }\n },\n [data, selectedRows, filename, exportToCSV, exportToJSON, exportToXLSX],\n );\n\n return {\n exportData,\n canExportSelected: !!(selectedRows && selectedRows.size > 0),\n selectedCount: selectedRows?.size ?? 0,\n };\n};\n","import { useState, useMemo, useEffect } from \"react\";\nimport { GridRow, GroupConfig, GridColumn } from \"../types\";\n\ninterface UseGroupingProps {\n data: GridRow[];\n columns: GridColumn[];\n}\n\nconst UNKNOWN = \"Unknown\";\nconst buildPath = (parts: string[]) => parts.join(\"|\");\n\n/**\n * Shared utility — walks the grouped tree and collects every group path into `acc`.\n * Used by: auto-expand useEffect, expandAllGroups.\n */\nconst gatherGroupPaths = (\n rows: GridRow[],\n keys: string[],\n level: number,\n parts: string[],\n acc: Set<string>,\n): void => {\n const colKey = keys[level];\n const map = new Map<string, GridRow[]>();\n for (const r of rows) {\n const str = String((r as any)[colKey] ?? UNKNOWN);\n const arr = map.get(str);\n if (arr) arr.push(r);\n else map.set(str, [r]);\n }\n for (const [value, groupRows] of map.entries()) {\n const seg = `${colKey}=${value}`;\n const next = [...parts, seg];\n acc.add(buildPath(next));\n if (level < keys.length - 1) gatherGroupPaths(groupRows, keys, level + 1, next, acc);\n }\n};\n\n/**\n * Module-level aggregate computation — extracted from inside displayData useMemo\n * so it is not redeclared on every evaluation. `columns` is now passed explicitly,\n * which also means it can be listed as a proper useMemo dependency.\n */\nconst computeAggregates = (rows: GridRow[], columns: GridColumn[]): Record<string, any> => {\n const result: Record<string, any> = {};\n for (const col of columns) {\n if (!col.aggregate) continue;\n const values = rows.map((r) => (r as any)[col.key]);\n let aggVal: any = null;\n if (typeof col.aggregate === \"function\") {\n try {\n aggVal = col.aggregate(values);\n } catch (_) {\n aggVal = null;\n }\n } else {\n const isDateLike = (s: string) => {\n if (/^\\d{4}-\\d{2}-\\d{2}$/.test(s)) return true;\n if (/^\\d{2}-\\d{2}-\\d{4}$/.test(s)) return true;\n if (/^\\d{4}\\/\\d{2}\\/\\d{2}$/.test(s)) return true;\n if (/^\\d{2}\\/\\d{2}\\/\\d{4}$/.test(s)) return true;\n if ((s.includes(\"-\") || s.includes(\"/\")) && Number.isFinite(Date.parse(s))) return true;\n return false;\n };\n const nums = values\n .map((v) => {\n if (typeof v === \"number\") return v;\n if (v == null) return NaN;\n const sv = String(v);\n if (isDateLike(sv)) return NaN;\n const n = parseFloat(sv.replace(/,/g, \"\"));\n return Number.isFinite(n) ? n : NaN;\n })\n .filter((n) => Number.isFinite(n)) as number[];\n const tryDateNumbers = () =>\n values\n .map((v) => {\n if (v instanceof Date) return v.getTime();\n if (typeof v === \"string\" || typeof v === \"number\") {\n const t = Date.parse(String(v));\n return Number.isFinite(t) ? t : NaN;\n }\n return NaN;\n })\n .filter((t) => Number.isFinite(t)) as number[];\n\n if (col.aggregate === \"sum\" || col.aggregate === \"avg\") {\n if (nums.length) {\n aggVal = col.aggregate === \"sum\"\n ? nums.reduce((a, b) => a + b, 0)\n : nums.reduce((a, b) => a + b, 0) / nums.length;\n }\n } else if (col.aggregate === \"min\" || col.aggregate === \"max\") {\n if (nums.length) {\n aggVal = col.aggregate === \"min\" ? Math.min(...nums) : Math.max(...nums);\n } else {\n const dateNums = tryDateNumbers();\n if (dateNums.length) {\n const picked = col.aggregate === \"min\" ? Math.min(...dateNums) : Math.max(...dateNums);\n aggVal = new Date(picked);\n }\n }\n }\n }\n if (aggVal !== null && aggVal !== undefined) {\n result[col.key] = aggVal;\n }\n }\n return result;\n};\n\nexport const useGrouping = ({ data, columns }: UseGroupingProps) => {\n const [groupConfig, setGroupConfig] = useState<GroupConfig>({\n columnKeys: [],\n expanded: new Set<string>(),\n });\n\n type FlatRow = GridRow & {\n _isGroupHeader?: boolean;\n _groupKey?: string;\n _groupCount?: number;\n _groupLevel?: number;\n _groupColumnKey?: string;\n _groupValue?: string;\n _groupRows?: GridRow[];\n _isGroupFooter?: boolean;\n _groupAgg?: Record<string, any>;\n };\n\n // Build flattened rows with nested group headers based on columnKeys.\n // `columns` is listed as a dep so that aggregate function changes are picked up.\n const displayData = useMemo<FlatRow[]>(() => {\n const keys = groupConfig.columnKeys;\n if (!keys.length) return data as FlatRow[];\n\n const flat: FlatRow[] = [];\n\n const recurse = (rows: GridRow[], level: number, pathParts: string[]) => {\n const colKey = keys[level];\n const map = new Map<string, GridRow[]>();\n for (const r of rows) {\n const str = String((r as any)[colKey] ?? UNKNOWN);\n const arr = map.get(str);\n if (arr) arr.push(r);\n else map.set(str, [r]);\n }\n const entries = Array.from(map.entries()).sort(([a], [b]) => a.localeCompare(b));\n for (const [value, groupRows] of entries) {\n const seg = `${colKey}=${value}`;\n const nextPath = [...pathParts, seg];\n const pathStr = buildPath(nextPath);\n flat.push({\n id: `group-${pathStr}`,\n _isGroupHeader: true,\n _groupKey: pathStr,\n _groupCount: groupRows.length,\n _groupLevel: level,\n _groupColumnKey: colKey,\n _groupValue: value,\n _groupRows: groupRows,\n } as FlatRow);\n\n const isExpanded = groupConfig.expanded.has(pathStr);\n if (!isExpanded) continue;\n if (level < keys.length - 1) {\n recurse(groupRows, level + 1, nextPath);\n } else {\n for (const r of groupRows) flat.push(r);\n }\n\n // Append footer with aggregates for this group\n const agg = computeAggregates(groupRows, columns);\n flat.push({\n id: `group-footer-${pathStr}`,\n _isGroupFooter: true,\n _groupKey: pathStr,\n _groupLevel: level,\n _groupAgg: agg,\n } as FlatRow);\n }\n };\n\n recurse(data, 0, []);\n return flat;\n }, [data, columns, groupConfig.columnKeys, groupConfig.expanded]);\n\n // Always keep groups expanded by default when grouping is active.\n useEffect(() => {\n if (!groupConfig.columnKeys.length) return;\n const allPaths = new Set<string>();\n gatherGroupPaths(data, groupConfig.columnKeys, 0, [], allPaths);\n let differs = false;\n if (allPaths.size !== groupConfig.expanded.size) differs = true;\n else {\n for (const p of allPaths)\n if (!groupConfig.expanded.has(p)) { differs = true; break; }\n }\n if (differs) setGroupConfig((prev) => ({ ...prev, expanded: allPaths }));\n }, [groupConfig.columnKeys, data]);\n\n const handleGroupBy = (columnKey: string | null) => {\n setGroupConfig({ columnKeys: columnKey ? [columnKey] : [], expanded: new Set() });\n };\n\n const addGroupKey = (columnKey: string) => {\n setGroupConfig((prev) =>\n prev.columnKeys.includes(columnKey)\n ? prev\n : { ...prev, columnKeys: [...prev.columnKeys, columnKey] },\n );\n };\n\n const removeGroupKey = (columnKey: string) => {\n setGroupConfig((prev) => {\n const nextKeys = prev.columnKeys.filter((k) => k !== columnKey);\n const nextExpanded = new Set<string>();\n for (const p of prev.expanded)\n if (!p.includes(`${columnKey}=`)) nextExpanded.add(p);\n return { columnKeys: nextKeys, expanded: nextExpanded };\n });\n };\n\n const setGroupKeys = (columnKeys: string[]) => {\n setGroupConfig({ columnKeys: [...columnKeys], expanded: new Set() });\n };\n\n const toggleGroupExpansion = (groupPath: string) => {\n setGroupConfig((prev) => {\n const next = new Set(prev.expanded);\n if (next.has(groupPath)) next.delete(groupPath);\n else next.add(groupPath);\n return { ...prev, expanded: next };\n });\n };\n\n const expandAllGroups = () => {\n const keys = groupConfig.columnKeys;\n if (!keys.length) return;\n const acc = new Set<string>();\n gatherGroupPaths(data, keys, 0, [], acc);\n setGroupConfig((prev) => ({ ...prev, expanded: acc }));\n };\n\n const collapseAllGroups = () => {\n setGroupConfig((prev) => ({ ...prev, expanded: new Set<string>() }));\n };\n\n return {\n groupConfig,\n displayData,\n handleGroupBy,\n addGroupKey,\n removeGroupKey,\n setGroupKeys,\n toggleGroupExpansion,\n expandAllGroups,\n collapseAllGroups,\n isGrouped: groupConfig.columnKeys.length > 0,\n };\n};\n","import { useState, useMemo, useCallback, useEffect } from \"react\";\nimport { PaginationConfig, GridRow } from \"../types\";\n\ninterface UsePaginationProps {\n data: GridRow[];\n pagination?: {\n enabled?: boolean;\n mode?: \"client\" | \"server\";\n pageSize?: number;\n showPageSizeSelector?: boolean;\n pageSizeOptions?: number[];\n serverConfig?: {\n enabled: boolean;\n onPageChange: (page: number, pageSize: number) => Promise<void> | void;\n onPageSizeChange?: (pageSize: number) => Promise<void> | void;\n loading?: boolean;\n totalRows: number;\n };\n };\n}\n\nexport const usePagination = ({ data, pagination }: UsePaginationProps) => {\n const [currentPage, setCurrentPage] = useState(1);\n const [pageSize, setPageSize] = useState(pagination?.pageSize || 50);\n const [isServerLoading, setIsServerLoading] = useState(false);\n\n // Sync pageSize when the prop changes externally (e.g. user preferences loaded async).\n // Reset to page 1 to avoid an out-of-bounds page after the resize.\n useEffect(() => {\n const next = pagination?.pageSize;\n if (next && next !== pageSize) {\n setPageSize(next);\n setCurrentPage(1);\n }\n // We intentionally only track pagination?.pageSize, not pageSize itself\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [pagination?.pageSize]);\n\n const resetPage = useCallback(() => {\n setCurrentPage(1);\n }, []);\n\n const paginationConfig: PaginationConfig = useMemo(() => {\n const isEnabled = pagination?.enabled !== false;\n const mode = pagination?.mode || \"client\";\n const totalRows =\n mode === \"server\"\n ? pagination?.serverConfig?.totalRows || 0\n : data.length;\n const totalPages = Math.ceil(totalRows / pageSize);\n\n return {\n enabled: isEnabled,\n pageSize,\n currentPage,\n totalPages,\n totalRows,\n showPageSizeSelector: pagination?.showPageSizeSelector !== false,\n pageSizeOptions: pagination?.pageSizeOptions || [25, 50, 100, 200, 500],\n };\n }, [pagination, pageSize, currentPage, data.length]);\n\n const paginatedData = useMemo(() => {\n if (!paginationConfig.enabled || pagination?.mode === \"server\") {\n return data;\n }\n\n const startIndex = (currentPage - 1) * pageSize;\n const endIndex = startIndex + pageSize;\n return data.slice(startIndex, endIndex);\n }, [data, currentPage, pageSize, paginationConfig.enabled, pagination?.mode]);\n\n const handlePageChange = useCallback(\n async (page: number) => {\n if (\n pagination?.mode === \"server\" &&\n pagination?.serverConfig?.onPageChange\n ) {\n setIsServerLoading(true);\n try {\n await pagination.serverConfig.onPageChange(page, pageSize);\n } finally {\n setIsServerLoading(false);\n }\n }\n setCurrentPage(page);\n },\n [pagination, pageSize],\n );\n\n const handlePageSizeChange = useCallback(\n async (newPageSize: number) => {\n if (\n pagination?.mode === \"server\" &&\n pagination?.serverConfig?.onPageSizeChange\n ) {\n setIsServerLoading(true);\n try {\n await pagination.serverConfig.onPageSizeChange(newPageSize);\n } finally {\n setIsServerLoading(false);\n }\n }\n setPageSize(newPageSize);\n setCurrentPage(1);\n },\n [pagination],\n );\n\n return {\n currentPage,\n resetPage,\n paginationConfig,\n paginatedData,\n isServerLoading,\n handlePageChange,\n handlePageSizeChange,\n };\n};\n","import { useState, useCallback, useEffect, useMemo } from \"react\";\nimport { GridRow } from \"../types\";\n\ninterface UseSelectionProps {\n data: GridRow[];\n selectedRowIds?: Iterable<string | number> | null;\n onRowSelect?: (row: GridRow) => void;\n getRowId?: (row: GridRow) => string | number;\n}\n\nconst areSetsEqual = (a: Set<string | number>, b: Set<string | number>) => {\n if (a.size !== b.size) return false;\n for (const value of a) {\n if (!b.has(value)) return false;\n }\n return true;\n};\n\nexport const useSelection = ({\n data,\n selectedRowIds,\n onRowSelect,\n getRowId,\n}: UseSelectionProps) => {\n // Extract row IDs based on getRowId or fallback to row.id\n const extractRowId = useCallback(\n (row: GridRow, rowIndex?: number): string | number => {\n if (getRowId) {\n return getRowId(row);\n }\n if (row.id !== undefined) {\n return row.id;\n }\n // Fallback: use row index\n if (process.env.NODE_ENV === \"development\" && rowIndex === 0) {\n console.warn(\n \"[KDGrid] No row IDs found. Either:\\n\" +\n \" 1. Add 'id' property to each row object, or\\n\" +\n \" 2. Provide 'getRowId' prop to extract a unique identifier.\\n\" +\n \" Using row index as fallback ID, but this may cause issues with pagination/filtering.\",\n );\n }\n return rowIndex ?? 0;\n },\n [getRowId],\n );\n\n const [selectedRows, setSelectedRows] = useState<Set<string | number>>(\n () => new Set(selectedRowIds ? Array.from(selectedRowIds) : []),\n );\n\n // Sync with external selectedRowIds prop\n useEffect(() => {\n if (!selectedRowIds) return;\n setSelectedRows((prev) => {\n const next = new Set(Array.from(selectedRowIds));\n if (areSetsEqual(prev, next)) return prev;\n return next;\n });\n }, [selectedRowIds]);\n\n // Pre-build rowId → row map for O(1) lookup in handleRowSelect.\n // Replaces per-click data.find() which was O(n) — painful at 100K rows.\n const rowByIdMap = useMemo(() => {\n const m = new Map<string | number, GridRow>();\n data.forEach((row, idx) => m.set(extractRowId(row, idx), row));\n return m;\n }, [data, extractRowId]);\n\n // Prune selected IDs that no longer exist in data (e.g. after filtering).\n // Guards with early-exit conditions to avoid the expensive Set rebuild on\n // every filter keypress when the selection is unchanged.\n useEffect(() => {\n if (selectedRows.size === 0) return; // nothing selected — nothing to prune\n\n // Check if any selected ID would be invalid — only then build the full Set\n let needsPrune = false;\n for (const id of selectedRows) {\n if (!rowByIdMap.has(id)) {\n needsPrune = true;\n break;\n }\n }\n if (!needsPrune) return;\n\n setSelectedRows((prev) => {\n const next = new Set<string | number>();\n prev.forEach((id) => {\n if (rowByIdMap.has(id)) next.add(id);\n });\n if (areSetsEqual(prev, next)) return prev;\n return next;\n });\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [rowByIdMap]);\n\n const handleRowSelect = useCallback(\n (rowId: string | number, isSelected: boolean) => {\n setSelectedRows((prev) => {\n const newSet = new Set(prev);\n if (isSelected) {\n newSet.add(rowId);\n } else {\n newSet.delete(rowId);\n }\n return newSet;\n });\n\n if (onRowSelect) {\n // O(1) lookup via the pre-built Map instead of O(n) data.find()\n const row = rowByIdMap.get(rowId);\n if (row) onRowSelect(row);\n }\n },\n [rowByIdMap, onRowSelect],\n );\n\n const handleSelectAll = useCallback(\n (isSelected: boolean) => {\n if (isSelected) {\n setSelectedRows(\n new Set(data.map((row, idx) => extractRowId(row, idx))),\n );\n } else {\n setSelectedRows(new Set());\n }\n },\n [data, extractRowId],\n );\n\n return {\n selectedRows,\n handleRowSelect,\n handleSelectAll,\n };\n};\n","import {\n useState,\n useMemo,\n useCallback,\n useEffect,\n useRef,\n UIEvent,\n} from \"react\";\nimport { VirtualizedRange, GridRow } from \"../types\";\n\ninterface UseVirtualizationProps {\n data: GridRow[];\n virtualized?: boolean;\n rowHeight?: number;\n overscan?: number;\n height: number;\n}\n\nexport const useVirtualization = ({\n data,\n virtualized = true,\n rowHeight = 40,\n overscan = 10,\n height,\n}: UseVirtualizationProps) => {\n const scrollRef = useRef<HTMLDivElement>(null);\n const [scrollTop, setScrollTop] = useState(0);\n const rafIdRef = useRef<number | null>(null);\n const pendingScrollTopRef = useRef<number>(0);\n // Initialise from the prop; ResizeObserver will keep it accurate afterwards\n const [containerHeight, setContainerHeight] = useState(height);\n\n // Track the scroll container's actual height via ResizeObserver.\n // This is more reliable than the `height` prop for flex/grid layouts where\n // the container may resize without the prop ever changing.\n useEffect(() => {\n const el = scrollRef.current;\n if (!el) return;\n const ro = new ResizeObserver(([entry]) => {\n const h = entry.contentRect.height;\n if (h > 0) setContainerHeight(h);\n });\n ro.observe(el);\n // Seed from the element's initial size\n const initial = el.clientHeight;\n if (initial > 0) setContainerHeight(initial);\n return () => ro.disconnect();\n }, []); // empty — scrollRef.current is stable after first render\n\n // Fallback: also sync when the height prop changes (e.g. explicit resize from parent)\n useEffect(() => {\n if (height > 0) setContainerHeight(height);\n }, [height]);\n\n const virtualizedRange = useMemo((): VirtualizedRange => {\n if (!virtualized) {\n return {\n startIndex: 0,\n endIndex: data.length - 1,\n offsetY: 0,\n };\n }\n\n // Dynamic overscan scaled by viewport height (rows in view)\n const rowsInView = Math.max(1, Math.ceil(containerHeight / rowHeight));\n const dynamicOverscan = Math.max(\n overscan,\n Math.max(8, Math.min(rowsInView * 2, 50)),\n );\n\n const startIndex = Math.max(\n 0,\n Math.floor(scrollTop / rowHeight) - dynamicOverscan,\n );\n const visibleCount = Math.ceil(containerHeight / rowHeight);\n const endIndex = Math.min(\n data.length - 1,\n startIndex + visibleCount + dynamicOverscan * 2,\n );\n\n const offsetY = startIndex * rowHeight;\n return { startIndex, endIndex, offsetY };\n }, [\n scrollTop,\n containerHeight,\n data.length,\n rowHeight,\n overscan,\n virtualized,\n ]);\n\n const visibleData = useMemo(() => {\n if (!virtualized) return data;\n return data.slice(\n virtualizedRange.startIndex,\n virtualizedRange.endIndex + 1,\n );\n }, [data, virtualizedRange, virtualized]);\n\n const totalHeight = data.length * rowHeight;\n\n const handleScroll = useCallback((e: UIEvent<HTMLDivElement>) => {\n const target = e.target as HTMLDivElement;\n const nextTop = target.scrollTop;\n pendingScrollTopRef.current = nextTop;\n if (rafIdRef.current == null) {\n rafIdRef.current = requestAnimationFrame(() => {\n rafIdRef.current = null;\n setScrollTop(pendingScrollTopRef.current);\n });\n }\n }, []);\n\n useEffect(() => {\n return () => {\n if (rafIdRef.current != null) cancelAnimationFrame(rafIdRef.current);\n };\n }, []);\n\n return {\n scrollRef,\n virtualizedRange,\n visibleData,\n totalHeight,\n handleScroll,\n };\n};\n","import {\n ChangeEvent,\n forwardRef,\n useCallback,\n useEffect,\n useImperativeHandle,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport { FooterAggregate } from \"../components/FooterAggregate\";\nimport { GridHeader } from \"../components/GridHeader\";\nimport { GridRows } from \"../components/GridRows\";\nimport { GroupBar } from \"../components/GroupBar\";\nimport { GroupHeader } from \"../components/GroupHeader\";\nimport { NoDataMessage } from \"../components/NoDataMessage\";\nimport { PaginationControls } from \"../components/PaginationControls\";\nimport { SearchToolbar } from \"../components/SearchToolbar\";\nimport { SELECT_COL_WIDTH } from \"../constants\";\nimport { useAdvancedFiltering } from \"../hooks/useAdvancedFiltering\";\nimport { useDataWorker } from \"../hooks/useDataWorker\";\nimport { useExport } from \"../hooks/useExport\";\nimport { useGrouping } from \"../hooks/useGrouping\";\nimport { usePagination } from \"../hooks/usePagination\";\nimport { useSelection } from \"../hooks/useSelection\";\nimport { useVirtualization } from \"../hooks/useVirtualization\";\nimport type { KDGridProps, KDGridRef, Density } from \"../types\";\n\n/** Stable default outside the component so it never recreates on every render */\nconst DEFAULT_CAN_SELECT_CELL = () => true;\n\nexport const KDGrid = /*#__PURE__*/ forwardRef<KDGridRef, KDGridProps>(\n function KDGrid(\n {\n data,\n columns,\n getRowId,\n height,\n density: densityProp = \"md\",\n headerDensity,\n headerHeight: headerHeightProp,\n onDensityChange,\n showDensityControl = false,\n onRowSelect,\n onSelectedRowsChange,\n selectable = false,\n isRowSelectable,\n showToolbar = true,\n showExport = false,\n filterable = true,\n groupable = false,\n virtualized = true,\n rowHeight: rowHeightProp,\n overscan = 6,\n rowStyle,\n onContextMenu,\n onRowDoubleClick,\n onRowClick,\n onCellClick,\n onCellContextMenu,\n cellFocusEnabled = false,\n onCellFocusChange,\n cellSelectionEnabled = false,\n canSelectCell = DEFAULT_CAN_SELECT_CELL,\n onCellSelectionChange,\n pagination = { enabled: false, mode: \"client\", pageSize: 50 },\n virtualizationThreshold = 300,\n isLoading = false,\n onFilterChange,\n onSort,\n onColumnConfigChange,\n initialColumnConfig,\n toolbarLeft,\n toolbarRight,\n groupBarVisibility = \"auto\",\n groupFooterVariant = \"chips\",\n onCopyCells,\n selectedRowIds,\n performanceConfig = {},\n exportOptions: exportOptionsProp,\n renderGroupActions,\n }: KDGridProps,\n ref,\n ) {\n // ==== Container width tracking (for column flex support) ====\n const containerRef = useRef<HTMLDivElement>(null);\n const [containerWidth, setContainerWidth] = useState<number>(0);\n useEffect(() => {\n const el = containerRef.current;\n if (!el) return;\n const update = () => setContainerWidth(el.clientWidth || 0);\n update();\n // ResizeObserver already fires on window resize — no need for redundant listener\n const ro = new ResizeObserver(() => update());\n ro.observe(el);\n return () => ro.disconnect();\n }, []);\n // ===== Cell focus & rectangular selection state =====\n const [focusedCell, setFocusedCell] = useState<{\n rowId: string | number;\n columnKey: string;\n } | null>(null);\n const [selectionAnchor, setSelectionAnchor] = useState<{\n rowIndex: number;\n colIndex: number;\n } | null>(null);\n const [selectionEnd, setSelectionEnd] = useState<{\n rowIndex: number;\n colIndex: number;\n } | null>(null);\n const isMouseDownRef = useRef(false);\n const lastMousePosRef = useRef<{ x: number; y: number } | null>(null);\n const autoScrollRafRef = useRef<number | null>(null);\n const [dragOverlay, setDragOverlay] = useState<{\n x: number;\n y: number;\n rows: number;\n cols: number;\n } | null>(null);\n\n // ===== Density management and effective row height =====\n const [density, setDensity] = useState<Density>(densityProp);\n useEffect(() => {\n // keep in sync if parent changes controlled prop\n setDensity(densityProp);\n }, [densityProp]);\n\n const densityMap: Record<Density, number> = useMemo(\n () => ({ sm: 28, md: 40, lg: 56 }),\n [],\n );\n const resolvedRowHeight = useMemo(\n () => (rowHeightProp != null ? rowHeightProp : densityMap[density]),\n [rowHeightProp, density, densityMap],\n );\n // Header height: explicit headerHeight > headerDensity > default md\n const resolvedHeaderHeight = useMemo(() => {\n if (headerHeightProp != null) return headerHeightProp;\n const d = headerDensity ?? \"md\";\n return densityMap[d];\n }, [headerHeightProp, headerDensity, densityMap]);\n // Use custom hooks for different concerns - OPTIMIZED\n const {\n globalFilter,\n columnFilters,\n filteredData,\n setGlobalFilter,\n setColumnFilter,\n clearAllFilters,\n } = useAdvancedFiltering({ data, columns });\n\n // Sorting state (tri-state: asc -> desc -> none)\n const [sortConfig, setSortConfig] = useState<{\n key: string | null;\n direction: \"asc\" | \"desc\" | null;\n }>({\n key: null,\n direction: null,\n });\n\n // Column widths state\n const [columnWidths, setColumnWidths] = useState<Record<string, number>>(\n () => {\n const initialWidths: Record<string, number> = {};\n columns.forEach((col) => {\n initialWidths[col.key] = col.width || 100;\n });\n return initialWidths;\n },\n );\n\n // Keep an immutable snapshot of initial widths for reset\n const initialWidthsRef = useRef<Record<string, number>>(\n columns.reduce(\n (acc, c) => {\n acc[c.key] = c.width || 100;\n return acc;\n },\n {} as Record<string, number>,\n ),\n );\n\n // Column order state + initial snapshot\n const initialOrderRef = useRef<string[]>(columns.map((c) => c.key));\n const [columnOrder, setColumnOrder] = useState<string[]>(() =>\n initialOrderRef.current.slice(),\n );\n\n // Column pinning state\n const [pinnedColumns, setPinnedColumns] = useState<Set<string>>(new Set());\n\n // Column visibility state\n const [columnVisibility, setColumnVisibility] = useState<\n Record<string, boolean>\n >(() => {\n const initialVisibility: Record<string, boolean> = {};\n columns.forEach((col) => {\n initialVisibility[col.key] = true;\n });\n return initialVisibility;\n });\n\n const handleSort = useCallback(\n (key: string) => {\n let nextKey: string | null = key;\n let nextDir: \"asc\" | \"desc\" | null = \"asc\";\n\n if (sortConfig.key !== key) {\n nextKey = key;\n nextDir = \"asc\";\n } else if (sortConfig.direction === \"asc\") {\n nextDir = \"desc\";\n } else if (sortConfig.direction === \"desc\") {\n // clear sorting\n nextKey = null;\n nextDir = null;\n } else {\n nextDir = \"asc\";\n }\n\n setSortConfig({ key: nextKey, direction: nextDir });\n\n // Server-side sorting: only call when a direction is active\n if (onSort && pagination?.mode === \"server\" && nextKey && nextDir) {\n onSort(nextKey, nextDir);\n }\n },\n [onSort, pagination?.mode, sortConfig.key, sortConfig.direction],\n );\n\n const handleColumnResize = useCallback(\n (columnKey: string, width: number) => {\n setColumnWidths((prev) => ({\n ...prev,\n [columnKey]: width,\n }));\n },\n [],\n );\n\n // Heuristic text width calc using character count; padding accounts for cell padding/icons\n const estimateWidthForText = useCallback((text: any) => {\n if (text == null) return 0;\n const s = typeof text === \"string\" ? text : String(text);\n const avgCharPx = 8; // conservative average for grid font\n return s.length * avgCharPx;\n }, []);\n\n const autosizeColumn = useCallback(\n (columnKey: string) => {\n const col = columns.find((c) => c.key === columnKey);\n if (!col) return;\n const headerWidth = estimateWidthForText(col.header);\n const sample = data.slice(0, 500); // limit for perf\n let maxCell = 0;\n for (const row of sample) {\n const value = row[columnKey];\n maxCell = Math.max(maxCell, estimateWidthForText(value));\n }\n const padding = 32; // cell padding + sort/menu affordance\n const computed = Math.max(\n 60,\n Math.min(500, Math.max(headerWidth, maxCell) + padding),\n );\n setColumnWidths((prev) => ({ ...prev, [columnKey]: computed }));\n },\n [columns, data, estimateWidthForText],\n );\n\n const autosizeAllColumns = useCallback(() => {\n columns.forEach((c) => autosizeColumn(c.key));\n }, [columns, autosizeColumn]);\n\n const resetColumns = useCallback(() => {\n // reset widths\n setColumnWidths({ ...initialWidthsRef.current });\n // clear pinning\n setPinnedColumns(new Set());\n // show all columns\n setColumnVisibility((prev) => {\n const next: Record<string, boolean> = {};\n Object.keys(prev).forEach((k) => (next[k] = true));\n return next;\n });\n // reset order\n setColumnOrder(initialOrderRef.current.slice());\n }, []);\n\n const headerScrollRef = useRef<HTMLDivElement>(null);\n const footerScrollRef = useRef<HTMLDivElement>(null);\n\n const handleColumnPin = useCallback(\n (columnKey: string, pinned: boolean) => {\n setPinnedColumns((prev) => {\n const newSet = new Set(prev);\n if (pinned) {\n newSet.add(columnKey);\n } else {\n newSet.delete(columnKey);\n }\n return newSet;\n });\n },\n [],\n );\n\n const handleColumnVisibilityChange = useCallback(\n (columnKey: string, visible: boolean) => {\n setColumnVisibility((prev) => ({\n ...prev,\n [columnKey]: visible,\n }));\n },\n [],\n );\n\n // Apply sorting, with optional worker offload for large datasets\n const { process: workerProcess } = useDataWorker({ enabled: true });\n const [sortedData, setSortedData] = useState<any[]>(filteredData);\n\n // Worker threshold: large datasets offloaded to background\n const workerThreshold =\n (performanceConfig as any)?.sortWorkerThreshold ?? 5000;\n\n useEffect(() => {\n let cancelled = false;\n if (!sortConfig.key) {\n setSortedData(filteredData);\n return;\n }\n const rows = filteredData;\n if (rows.length < workerThreshold) {\n // inline sort for small lists\n const dir = sortConfig.direction === \"asc\" ? 1 : -1;\n const out = [...rows].sort((a, b) => {\n const av = a?.[sortConfig.key!];\n const bv = b?.[sortConfig.key!];\n if (av == null && bv == null) return 0;\n if (av == null) return -1 * dir;\n if (bv == null) return 1 * dir;\n if (typeof av === \"number\" && typeof bv === \"number\")\n return (av - bv) * dir;\n return String(av).localeCompare(String(bv)) * dir;\n });\n setSortedData(out);\n return;\n }\n workerProcess(rows, {\n key: sortConfig.key!,\n direction: sortConfig.direction as any,\n }).then((out) => {\n if (!cancelled) setSortedData(out);\n });\n return () => {\n cancelled = true;\n };\n }, [filteredData, sortConfig, workerProcess, workerThreshold]);\n\n const {\n paginationConfig,\n paginatedData,\n isServerLoading,\n handlePageChange,\n handlePageSizeChange,\n resetPage,\n currentPage,\n } = usePagination({ data: sortedData, pagination });\n\n // Unified loading state for header loader with smooth finish animation\n const loadingOverall = isLoading || isServerLoading;\n const [showLoader, setShowLoader] = useState<boolean>(loadingOverall);\n const [finishingLoader, setFinishingLoader] = useState<boolean>(false);\n const [loaderTop, setLoaderTop] = useState<number>(0);\n useEffect(() => {\n if (loadingOverall) {\n setShowLoader(true);\n setFinishingLoader(false);\n return;\n }\n if (showLoader) {\n setFinishingLoader(true);\n const t = setTimeout(() => {\n setShowLoader(false);\n setFinishingLoader(false);\n }, 200);\n return () => clearTimeout(t);\n }\n }, [loadingOverall]);\n\n const handleGlobalFilterChange = useCallback(\n (e: ChangeEvent<HTMLInputElement>) => {\n setGlobalFilter(e.target.value);\n },\n [setGlobalFilter],\n );\n\n // Grouping functionality\n const {\n groupConfig,\n displayData: groupedDisplayData,\n handleGroupBy,\n addGroupKey,\n removeGroupKey,\n setGroupKeys,\n toggleGroupExpansion,\n isGrouped,\n expandAllGroups,\n collapseAllGroups,\n } = useGrouping({ data: sortedData, columns });\n\n // Expose imperative grouping controls to parent components\n useImperativeHandle(\n ref,\n () => ({\n setGroupKeys,\n addGroupKey,\n removeGroupKey,\n expandAllGroups,\n collapseAllGroups,\n toggleGroupExpansion,\n getGroupConfig: () => groupConfig,\n // Filter methods\n setColumnFilter: (columnKey: string, filter: any) => {\n setColumnFilter(columnKey, filter);\n },\n clearColumnFilter: (columnKey: string) => {\n setColumnFilter(columnKey, null);\n },\n clearAllFilters: () => {\n clearAllFilters();\n },\n setGlobalFilter: (value: string) => {\n setGlobalFilter(value);\n },\n }),\n [groupConfig, setColumnFilter, clearAllFilters, setGlobalFilter],\n );\n\n // Do NOT pin grouped columns; only respect explicit pins.\n const effectivePinnedColumns = useMemo(() => {\n return new Set(pinnedColumns);\n }, [pinnedColumns]);\n\n const finalDisplayData = pagination?.enabled\n ? pagination.mode === \"server\"\n ? data\n : paginatedData\n : sortedData;\n\n const dataToDisplay = isGrouped ? groupedDisplayData : finalDisplayData;\n\n const { selectedRows, handleRowSelect, handleSelectAll } = useSelection({\n data: dataToDisplay,\n onRowSelect,\n selectedRowIds,\n getRowId,\n });\n\n // Keep stable ref for onSelectedRowsChange to avoid effect re-running on every parent render\n const onSelectedRowsChangeRef = useRef(onSelectedRowsChange);\n useEffect(() => {\n onSelectedRowsChangeRef.current = onSelectedRowsChange;\n }, [onSelectedRowsChange]);\n\n useEffect(() => {\n if (onSelectedRowsChangeRef.current) {\n onSelectedRowsChangeRef.current(selectedRows);\n }\n }, [selectedRows]);\n\n // Update export hook with selected rows\n const { exportData: exportDataWithSelection } = useExport({\n // Export the currently rendered dataset. In server mode this is the fetched page.\n data: finalDisplayData,\n columns,\n selectedRows,\n filename:\n (exportOptionsProp && exportOptionsProp.filename) || \"grid-data\",\n columnVisibility,\n });\n\n // Decide how to export: client (default) vs server callback\n const handleToolbarExport = useCallback(\n (format: any, exportSelected: boolean) => {\n const selectedIds = Array.from(selectedRows || []);\n if (\n exportOptionsProp?.exportMode === \"server\" &&\n typeof exportOptionsProp?.onServerExport === \"function\"\n ) {\n exportOptionsProp.onServerExport(format, exportSelected, selectedIds);\n } else {\n // Client mode: export only the data available in memory (filtered/paginated set)\n exportDataWithSelection(format, exportSelected);\n }\n },\n [\n exportOptionsProp?.exportMode,\n exportOptionsProp?.onServerExport,\n exportDataWithSelection,\n selectedRows,\n ],\n );\n\n const handleClearFilters = useCallback(() => {\n clearAllFilters();\n }, [clearAllFilters]);\n\n const handleSetDensity = useCallback(\n (d: Density) => {\n setDensity(d);\n if (onDensityChange) onDensityChange(d);\n },\n [onDensityChange],\n );\n\n const effectiveVirtualized = useMemo(() => {\n if (!virtualized) return false;\n return dataToDisplay.length > virtualizationThreshold;\n }, [virtualized, dataToDisplay.length, virtualizationThreshold]);\n\n // Performance configuration with defaults\n const perfConfig = useMemo(\n () => ({\n enableHorizontalVirtualization: true,\n horizontalVirtualizationThreshold: 50,\n sortWorkerThreshold: 5000,\n maxFilterCacheSize: 5000,\n enableAggressiveMemoization: true,\n ...performanceConfig,\n }),\n [performanceConfig],\n );\n\n const { scrollRef, virtualizedRange, visibleData, handleScroll } =\n useVirtualization({\n data: dataToDisplay,\n virtualized: effectiveVirtualized,\n rowHeight: resolvedRowHeight,\n overscan,\n height: height || 400,\n });\n\n // Position the loader bar just below the sticky header, regardless of horizontal scroll\n useEffect(() => {\n const update = () => {\n const el = scrollRef.current;\n if (!el) return;\n // offsetTop is relative to the closest positioned ancestor (the relative grid container)\n const top = (el.offsetTop || 0) + (resolvedHeaderHeight || 0) - 1;\n setLoaderTop(top);\n };\n update();\n const ro = new ResizeObserver(update);\n if (containerRef.current) ro.observe(containerRef.current);\n if (scrollRef.current) ro.observe(scrollRef.current);\n return () => ro.disconnect();\n }, [resolvedHeaderHeight]);\n\n // Horizontal virtualization state\n const [hScrollLeft, setHScrollLeft] = useState(0);\n const hScrollLeftRef = useRef(0);\n const hScrollRafRef = useRef<number | null>(null);\n const scheduleHScrollUpdate = useCallback((value: number) => {\n hScrollLeftRef.current = value;\n if (hScrollRafRef.current != null) return;\n hScrollRafRef.current = requestAnimationFrame(() => {\n hScrollRafRef.current = null;\n setHScrollLeft(hScrollLeftRef.current);\n });\n }, []);\n const [viewportWidth, setViewportWidth] = useState(0);\n useEffect(() => {\n const el = scrollRef.current;\n if (!el) return;\n const update = () => setViewportWidth(el.clientWidth || 0);\n update();\n const ro = new ResizeObserver(update);\n ro.observe(el);\n return () => ro.disconnect();\n }, [scrollRef]);\n\n // Notify parent of filter changes in server-side mode\n useEffect(() => {\n if (!onFilterChange) return;\n if (!(pagination?.enabled && pagination.mode === \"server\")) return;\n\n const filterableKeys = columns\n .filter((c) => !!c.filterable)\n .map((c) => c.key);\n\n onFilterChange({\n globalFilter,\n columnFilters,\n filterableKeys,\n });\n }, [globalFilter, columnFilters]);\n\n // Hydrate from initialColumnConfig on mount\n useEffect(() => {\n if (!initialColumnConfig) return;\n const existingKeys = new Set(columns.map((c) => c.key));\n\n if (initialColumnConfig.columnWidths) {\n const next = Object.fromEntries(\n Object.entries(initialColumnConfig.columnWidths).filter(([k]) =>\n existingKeys.has(k),\n ),\n );\n setColumnWidths((prev) => ({ ...prev, ...next }));\n }\n\n if (initialColumnConfig.columnVisibility) {\n const next = Object.fromEntries(\n Object.entries(initialColumnConfig.columnVisibility).filter(([k]) =>\n existingKeys.has(k),\n ),\n );\n setColumnVisibility((prev) => ({ ...prev, ...next }));\n }\n\n if (initialColumnConfig.pinnedColumns) {\n const pins = initialColumnConfig.pinnedColumns.filter((k) =>\n existingKeys.has(k),\n );\n setPinnedColumns(new Set(pins));\n }\n\n if (initialColumnConfig.sortConfig) {\n const dir =\n initialColumnConfig.sortConfig.direction === \"asc\" ||\n initialColumnConfig.sortConfig.direction === \"desc\"\n ? initialColumnConfig.sortConfig.direction\n : null;\n const key = dir ? initialColumnConfig.sortConfig.key : null;\n setSortConfig({ key, direction: dir });\n }\n\n if (initialColumnConfig.filters) {\n setGlobalFilter(initialColumnConfig.filters.globalFilter || \"\");\n const entries = Object.entries(\n initialColumnConfig.filters.columnFilters || {},\n ).filter(([k]) => existingKeys.has(k));\n for (const [k, v] of entries) setColumnFilter(k, v as any);\n }\n\n if (\n initialColumnConfig.columnOrder &&\n initialColumnConfig.columnOrder.length\n ) {\n const filtered = initialColumnConfig.columnOrder.filter((k) =>\n existingKeys.has(k),\n );\n // append any new columns not in saved order at the end, by original order\n const remaining = columns\n .map((c) => c.key)\n .filter((k) => !filtered.includes(k));\n setColumnOrder([...filtered, ...remaining]);\n }\n\n if (\n initialColumnConfig.groupConfig?.columnKeys &&\n initialColumnConfig.groupConfig.columnKeys.length\n ) {\n setGroupKeys(initialColumnConfig.groupConfig.columnKeys);\n } else if (initialColumnConfig.groupConfig?.columnKey) {\n handleGroupBy(initialColumnConfig.groupConfig.columnKey);\n }\n if (initialColumnConfig.density) {\n setDensity(initialColumnConfig.density as Density);\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n // Emit onColumnConfigChange when relevant state updates (debounced)\n useEffect(() => {\n if (!onColumnConfigChange) return;\n const timer = setTimeout(() => {\n onColumnConfigChange({\n columnWidths,\n columnVisibility,\n pinnedColumns: Array.from(pinnedColumns),\n sortConfig,\n groupConfig: { columnKeys: groupConfig.columnKeys },\n filters: { globalFilter, columnFilters },\n columnOrder,\n density,\n });\n }, 200);\n return () => clearTimeout(timer);\n }, [\n onColumnConfigChange,\n columnWidths,\n columnVisibility,\n pinnedColumns,\n sortConfig,\n groupConfig,\n globalFilter,\n columnFilters,\n columnOrder,\n density,\n ]);\n\n // Sync horizontal scroll between header, body, and footer\n // (moved scroll sync effect below after columnsWithWidths is defined)\n\n // Create columns with updated widths and handle pinning order - OPTIMIZED\n const columnsWithWidths = useMemo(() => {\n // Early return if no columns\n if (columns.length === 0) return [];\n\n // order columns by columnOrder first\n const orderIndex = new Map<string, number>(\n columnOrder.map((k, i) => [k, i] as const),\n );\n\n // Batch process columns more efficiently\n const visibleColumns = columns.filter(\n (col) => columnVisibility[col.key] !== false,\n );\n\n // Pre-sort and process in one pass\n const base = visibleColumns\n .sort(\n (a, b) => (orderIndex.get(a.key) || 0) - (orderIndex.get(b.key) || 0),\n )\n .map((col) => {\n const candidate = columnWidths[col.key] ?? col.width;\n const width = Number.isFinite(Number(candidate))\n ? Number(candidate)\n : 100;\n // Enforce default sortable=true unless explicitly false\n const sortable = col.sortable !== false;\n return { ...col, width, sortable } as typeof col & {\n width: number;\n sortable: boolean;\n };\n });\n\n // Optimized flex calculation - only if needed\n const viewportW = Math.max(\n 0,\n containerWidth - (selectable ? SELECT_COL_WIDTH : 0),\n );\n const baseTotal = base.reduce((sum, c) => sum + c.width, 0);\n\n if (viewportW > baseTotal) {\n const flexCols = base.filter((c) => c.flex);\n if (flexCols.length > 0) {\n const extra = viewportW - baseTotal;\n const totalWeight = flexCols.reduce((acc, c) => {\n const weight =\n c.flex === true ? 1 : typeof c.flex === \"number\" ? c.flex : 1;\n return acc + Math.max(0, weight);\n }, 0);\n\n if (totalWeight > 0) {\n // Batch update flex columns\n for (const col of flexCols) {\n const weight =\n col.flex === true\n ? 1\n : typeof col.flex === \"number\"\n ? col.flex\n : 1;\n const increment = (extra * weight) / totalWeight;\n const minW = col.minWidth ?? 0;\n const maxW = col.maxWidth ?? Number.POSITIVE_INFINITY;\n col.width = Math.max(minW, Math.min(maxW, col.width + increment));\n }\n }\n }\n }\n\n // Separate pinned and unpinned columns efficiently\n const pinned: typeof base = [];\n const unpinned: typeof base = [];\n\n for (const col of base) {\n if (effectivePinnedColumns.has(col.key)) {\n pinned.push(col);\n } else {\n unpinned.push(col);\n }\n }\n\n // Sort unpinned columns by grouping if needed\n if (groupConfig.columnKeys && groupConfig.columnKeys.length > 0) {\n const groupIndex = new Map(\n groupConfig.columnKeys.map((k, i) => [k, i]),\n );\n unpinned.sort((a, b) => {\n const aIdx = groupIndex.get(a.key) ?? Number.POSITIVE_INFINITY;\n const bIdx = groupIndex.get(b.key) ?? Number.POSITIVE_INFINITY;\n return aIdx - bIdx;\n });\n }\n\n return [...pinned, ...unpinned];\n }, [\n columns,\n columnWidths,\n effectivePinnedColumns,\n columnVisibility,\n columnOrder,\n groupConfig.columnKeys,\n containerWidth,\n selectable,\n ]);\n\n // Horizontal virtualization for large column sets\n const needsHorizontalVirtualization = useMemo(() => {\n return (\n perfConfig.enableHorizontalVirtualization &&\n columnsWithWidths.length > perfConfig.horizontalVirtualizationThreshold\n );\n }, [\n columnsWithWidths.length,\n perfConfig.enableHorizontalVirtualization,\n perfConfig.horizontalVirtualizationThreshold,\n ]);\n\n // Pinned/unpinned memo + prefix sums for binary search slicing\n const pinnedAll = useMemo(\n () => columnsWithWidths.filter((c) => effectivePinnedColumns.has(c.key)),\n [columnsWithWidths, effectivePinnedColumns],\n );\n const unpinnedAll = useMemo(\n () => columnsWithWidths.filter((c) => !effectivePinnedColumns.has(c.key)),\n [columnsWithWidths, effectivePinnedColumns],\n );\n const unpinnedMeta = useMemo(() => {\n const widths = unpinnedAll.map((c) => (c.width as number) || 100);\n const prefix = new Array(widths.length + 1).fill(0) as number[];\n for (let i = 0; i < widths.length; i++)\n prefix[i + 1] = prefix[i] + widths[i];\n const totalWidth = prefix[widths.length] || 0;\n return { widths, prefix, totalWidth };\n }, [unpinnedAll]);\n\n const visibleColumns = useMemo(() => {\n if (!needsHorizontalVirtualization) return columnsWithWidths;\n\n const leftPad = selectable ? SELECT_COL_WIDTH : 0;\n const pinnedTotal = pinnedAll.reduce(\n (sum, c) => sum + ((c.width as number) || 100),\n 0,\n );\n\n const targetLeft = Math.max(0, hScrollLeft - 200);\n const targetRight = hScrollLeft + viewportWidth + 200;\n\n // Map into unpinned local coordinates\n const base = leftPad + pinnedTotal;\n const localLeft = Math.max(0, targetLeft - base);\n const localRight = Math.max(\n 0,\n Math.min(unpinnedMeta.totalWidth, targetRight - base),\n );\n\n // Binary search over prefix sums\n const firstIndexWithRightGte = (x: number): number => {\n if (!unpinnedMeta.widths.length) return 0;\n let lo = 0,\n hi = unpinnedMeta.widths.length - 1,\n ans = 0;\n while (lo <= hi) {\n const mid = (lo + hi) >> 1;\n const right = unpinnedMeta.prefix[mid + 1];\n if (right >= x) {\n ans = mid;\n hi = mid - 1;\n } else {\n lo = mid + 1;\n }\n }\n return Math.max(0, Math.min(ans, unpinnedMeta.widths.length - 1));\n };\n const lastIndexWithLeftLte = (x: number): number => {\n if (!unpinnedMeta.widths.length) return -1;\n let lo = 0,\n hi = unpinnedMeta.widths.length - 1,\n ans = unpinnedMeta.widths.length - 1;\n while (lo <= hi) {\n const mid = (lo + hi) >> 1;\n const left = unpinnedMeta.prefix[mid];\n if (left <= x) {\n ans = mid;\n lo = mid + 1;\n } else {\n hi = mid - 1;\n }\n }\n return Math.max(0, Math.min(ans, unpinnedMeta.widths.length - 1));\n };\n\n const startIdx = firstIndexWithRightGte(localLeft);\n const endIdx = lastIndexWithLeftLte(localRight);\n const sliced =\n endIdx >= startIdx && endIdx >= 0\n ? unpinnedAll.slice(startIdx, endIdx + 1)\n : [];\n return [...pinnedAll, ...sliced];\n }, [\n needsHorizontalVirtualization,\n columnsWithWidths,\n hScrollLeft,\n viewportWidth,\n selectable,\n pinnedAll,\n unpinnedAll,\n unpinnedMeta,\n ]);\n\n // Memoized hvPadLeft/Right for header and rows\n const unpinnedIndexByKey = useMemo(() => {\n const m = new Map<string, number>();\n unpinnedAll.forEach((c, i) => m.set(c.key, i));\n return m;\n }, [unpinnedAll]);\n const { hvPadLeftMemo, hvPadRightMemo } = useMemo(() => {\n if (!needsHorizontalVirtualization)\n return { hvPadLeftMemo: 0, hvPadRightMemo: 0 } as const;\n const visibleUnpinned = visibleColumns.filter(\n (c) => !effectivePinnedColumns.has(c.key),\n );\n if (!visibleUnpinned.length)\n return { hvPadLeftMemo: 0, hvPadRightMemo: 0 } as const;\n const firstIdx = unpinnedIndexByKey.get(visibleUnpinned[0].key);\n const lastIdx = unpinnedIndexByKey.get(\n visibleUnpinned[visibleUnpinned.length - 1].key,\n );\n if (firstIdx == null || lastIdx == null)\n return { hvPadLeftMemo: 0, hvPadRightMemo: 0 } as const;\n const left = unpinnedMeta.prefix[firstIdx];\n const right = unpinnedMeta.totalWidth - unpinnedMeta.prefix[lastIdx + 1];\n return { hvPadLeftMemo: left, hvPadRightMemo: right } as const;\n }, [\n needsHorizontalVirtualization,\n visibleColumns,\n effectivePinnedColumns,\n unpinnedIndexByKey,\n unpinnedMeta,\n ]);\n\n // Determine footer aggregate presence and keep scroll areas in sync (header/body/footer)\n const hasFooterAggregate = useMemo(\n () => columnsWithWidths.some((c) => c.footer_aggregate),\n [columnsWithWidths],\n );\n\n useEffect(() => {\n const bodyElement = scrollRef.current;\n if (!bodyElement) return;\n\n let isBodyScrolling = false;\n\n const syncFromBody = () => {\n if (isBodyScrolling) return;\n isBodyScrolling = true;\n const footerEl = footerScrollRef.current;\n if (footerEl && footerEl.scrollLeft !== bodyElement.scrollLeft) {\n footerEl.scrollLeft = bodyElement.scrollLeft;\n }\n scheduleHScrollUpdate(bodyElement.scrollLeft);\n requestAnimationFrame(() => {\n isBodyScrolling = false;\n });\n };\n\n bodyElement.addEventListener(\"scroll\", syncFromBody, { passive: true });\n // align footer on mount\n if (footerScrollRef.current) {\n footerScrollRef.current.scrollLeft = bodyElement.scrollLeft;\n }\n\n return () => {\n bodyElement.removeEventListener(\"scroll\", syncFromBody);\n };\n }, [scrollRef, hasFooterAggregate]);\n\n // Column index lookup in current render order (pinned first)\n const colIndexByKey = useMemo(() => {\n const m = new Map<string, number>();\n columnsWithWidths.forEach((c, i) => m.set(c.key, i));\n return m;\n }, [columnsWithWidths]);\n\n const colByKey = useMemo(() => {\n const m = new Map<string, any>();\n columnsWithWidths.forEach((c) => m.set(c.key, c));\n return m;\n }, [columnsWithWidths]);\n\n // Flat list of data rows (exclude group headers) for selection math\n const flatRows = useMemo(\n () =>\n dataToDisplay.filter(\n (r: any) => !r._isGroupHeader && !r._isGroupFooter,\n ),\n [dataToDisplay],\n );\n const rowIndexById = useMemo(() => {\n const m = new Map<string | number, number>();\n flatRows.forEach((r, i) => m.set(r.id, i));\n return m;\n }, [flatRows]);\n\n const rowById = useMemo(() => {\n const m = new Map<string | number, any>();\n flatRows.forEach((r) => m.set(r.id, r));\n return m;\n }, [flatRows]);\n\n // Keep a stable reference to the latest onCellSelectionChange and a signature of last emitted selection\n const prevSelectionSignatureRef = useRef<string | null>(null);\n const onCellSelectionChangeRef = useRef(onCellSelectionChange);\n const onCopyCellsRef = useRef(onCopyCells);\n useEffect(() => {\n onCopyCellsRef.current = onCopyCells;\n }, [onCopyCells]);\n useEffect(() => {\n onCellSelectionChangeRef.current = onCellSelectionChange;\n }, [onCellSelectionChange]);\n // (onCopyCells handled separately above)\n\n // Derive a stable dependency for columns (by keys) to avoid re-running effects on width changes\n const columnKeys = useMemo(\n () => columnsWithWidths.map((c) => c.key),\n [columnsWithWidths],\n );\n\n // Selection predicates\n const isCellSelected = useMemo(\n () => (rowId: string | number, columnKey: string) => {\n if (!cellSelectionEnabled) return false;\n if (!selectionAnchor || !selectionEnd) return false;\n const r = rowIndexById.get(rowId);\n const c = colIndexByKey.get(columnKey);\n if (r == null || c == null) return false;\n const rowObj = rowById.get(rowId);\n const colObj = colByKey.get(columnKey);\n if (rowObj && colObj && !canSelectCell(rowObj, colObj)) return false;\n const rMin = Math.min(selectionAnchor.rowIndex, selectionEnd.rowIndex);\n const rMax = Math.max(selectionAnchor.rowIndex, selectionEnd.rowIndex);\n const cMin = Math.min(selectionAnchor.colIndex, selectionEnd.colIndex);\n const cMax = Math.max(selectionAnchor.colIndex, selectionEnd.colIndex);\n return r >= rMin && r <= rMax && c >= cMin && c <= cMax;\n },\n [\n cellSelectionEnabled,\n selectionAnchor,\n selectionEnd,\n rowIndexById,\n colIndexByKey,\n rowById,\n colByKey,\n canSelectCell,\n ],\n );\n\n const isCellFocused = useMemo(\n () => (rowId: string | number, columnKey: string) =>\n focusedCell?.rowId === rowId && focusedCell?.columnKey === columnKey,\n [focusedCell],\n );\n\n // Forward horizontal wheel/trackpad scrolls from header/footer to body to keep a single scroll source\n const forwardWheelToBody = useCallback(\n (e: React.WheelEvent<HTMLDivElement>) => {\n const bodyEl = scrollRef.current;\n if (!bodyEl) return;\n const primarilyHorizontal = Math.abs(e.deltaX) >= Math.abs(e.deltaY);\n const dx = primarilyHorizontal ? e.deltaX : e.deltaY;\n if (dx !== 0) {\n e.preventDefault();\n bodyEl.scrollBy({ left: dx, top: 0, behavior: \"auto\" });\n }\n },\n [],\n );\n\n // Mouse handlers for drag selection\n const handleCellMouseDown = useCallback(\n ({ row, column, event }: { row: any; column: any; event: any }) => {\n const rIndex = rowIndexById.get(row.id);\n const cIndex = colIndexByKey.get(column.key);\n\n // Always set focused cell when focus mode is enabled\n if (cellFocusEnabled && rIndex != null && cIndex != null) {\n // Don't update focus if modal is open\n if (!document.body.hasAttribute(\"data-modal-open\")) {\n setFocusedCell({ rowId: row.id, columnKey: column.key });\n if (onCellFocusChange) {\n onCellFocusChange({\n row,\n column,\n value: row[column.key],\n rowIndex: rIndex,\n colIndex: cIndex,\n });\n }\n }\n }\n\n // Handle rectangular selection only when enabled and left button\n if (!cellSelectionEnabled) return;\n if (!canSelectCell(row, column)) return;\n if (event.button !== 0) return; // left button only\n isMouseDownRef.current = true;\n lastMousePosRef.current = { x: event.clientX, y: event.clientY };\n if (rIndex == null || cIndex == null) return;\n setFocusedCell({ rowId: row.id, columnKey: column.key });\n setSelectionAnchor({ rowIndex: rIndex, colIndex: cIndex });\n setSelectionEnd({ rowIndex: rIndex, colIndex: cIndex });\n // Initialize overlay\n setDragOverlay({\n x: event.clientX,\n y: event.clientY,\n rows: 1,\n cols: 1,\n });\n },\n [\n cellFocusEnabled,\n onCellFocusChange,\n cellSelectionEnabled,\n canSelectCell,\n rowIndexById,\n colIndexByKey,\n ],\n );\n\n const handleCellMouseEnter = useCallback(\n ({ row, column, event }: { row: any; column: any; event: any }) => {\n if (!cellSelectionEnabled) return;\n if (!isMouseDownRef.current || !selectionAnchor) return;\n if (!canSelectCell(row, column)) return;\n const rIndex = rowIndexById.get(row.id);\n const cIndex = colIndexByKey.get(column.key);\n if (rIndex == null || cIndex == null) return;\n setSelectionEnd({ rowIndex: rIndex, colIndex: cIndex });\n // Update last mouse and overlay\n lastMousePosRef.current = { x: event.clientX, y: event.clientY };\n const rMin = Math.min(selectionAnchor.rowIndex, rIndex);\n const rMax = Math.max(selectionAnchor.rowIndex, rIndex);\n const cMin = Math.min(selectionAnchor.colIndex, cIndex);\n const cMax = Math.max(selectionAnchor.colIndex, cIndex);\n setDragOverlay({\n x: event.clientX,\n y: event.clientY,\n rows: rMax - rMin + 1,\n cols: cMax - cMin + 1,\n });\n },\n [\n cellSelectionEnabled,\n canSelectCell,\n selectionAnchor,\n rowIndexById,\n colIndexByKey,\n ],\n );\n\n useEffect(() => {\n const onUp = () => {\n isMouseDownRef.current = false;\n setDragOverlay(null);\n if (autoScrollRafRef.current) {\n cancelAnimationFrame(autoScrollRafRef.current);\n autoScrollRafRef.current = null;\n }\n };\n window.addEventListener(\"mouseup\", onUp);\n return () => window.removeEventListener(\"mouseup\", onUp);\n }, []);\n\n // Global mousemove to keep tracking position while dragging (even outside cells)\n useEffect(() => {\n const onMove = (e: MouseEvent) => {\n if (!isMouseDownRef.current) return;\n lastMousePosRef.current = { x: e.clientX, y: e.clientY };\n };\n window.addEventListener(\"mousemove\", onMove as any);\n return () => window.removeEventListener(\"mousemove\", onMove as any);\n }, []);\n\n // Auto-scroll while dragging near edges of the scroll container\n const ensureAutoScrollLoop = useCallback(() => {\n if (autoScrollRafRef.current != null) return;\n const step = () => {\n autoScrollRafRef.current = null;\n if (!isMouseDownRef.current) return;\n const el = scrollRef.current;\n const mp = lastMousePosRef.current;\n if (el && mp) {\n const rect = el.getBoundingClientRect();\n const margin = 24; // px\n const maxSpeed = 24; // px per frame approx\n let dx = 0;\n let dy = 0;\n if (mp.x < rect.left + margin) dx = -(rect.left + margin - mp.x);\n else if (mp.x > rect.right - margin)\n dx = mp.x - (rect.right - margin);\n if (mp.y < rect.top + margin) dy = -(rect.top + margin - mp.y);\n else if (mp.y > rect.bottom - margin)\n dy = mp.y - (rect.bottom - margin);\n // Normalize to maxSpeed\n const clamp = (v: number) =>\n Math.max(-maxSpeed, Math.min(maxSpeed, v));\n dx = clamp(dx);\n dy = clamp(dy);\n if (dx !== 0 || dy !== 0) {\n el.scrollBy({ left: dx, top: dy, behavior: \"auto\" });\n }\n }\n autoScrollRafRef.current = requestAnimationFrame(step);\n };\n autoScrollRafRef.current = requestAnimationFrame(step);\n }, []);\n\n // Kick the auto-scroll loop when we start a drag\n useEffect(() => {\n if (isMouseDownRef.current) {\n ensureAutoScrollLoop();\n }\n }, [ensureAutoScrollLoop, selectionAnchor]);\n\n // Keyboard: ESC clears selection; Shift+Arrows expands selection\n useEffect(() => {\n const onKey = (e: KeyboardEvent) => {\n if (e.key === \"Escape\") {\n setSelectionAnchor(null);\n setSelectionEnd(null);\n setFocusedCell(null);\n setDragOverlay(null);\n return;\n }\n const isShift = e.shiftKey;\n const arrow = [\n \"ArrowUp\",\n \"ArrowDown\",\n \"ArrowLeft\",\n \"ArrowRight\",\n ].includes(e.key);\n if (!isShift || !arrow || !cellSelectionEnabled) return;\n e.preventDefault();\n // Determine base cell\n let base = selectionEnd;\n if (!base) {\n if (focusedCell) {\n const r = rowIndexById.get(focusedCell.rowId);\n const c = colIndexByKey.get(focusedCell.columnKey);\n if (r != null && c != null) {\n setSelectionAnchor({ rowIndex: r, colIndex: c });\n base = { rowIndex: r, colIndex: c };\n } else {\n return;\n }\n } else {\n return;\n }\n }\n const maxRow = flatRows.length - 1;\n const maxCol = columnsWithWidths.length - 1;\n let nr = base.rowIndex;\n let nc = base.colIndex;\n if (e.key === \"ArrowUp\") nr = Math.max(0, nr - 1);\n if (e.key === \"ArrowDown\") nr = Math.min(maxRow, nr + 1);\n if (e.key === \"ArrowLeft\") nc = Math.max(0, nc - 1);\n if (e.key === \"ArrowRight\") nc = Math.min(maxCol, nc + 1);\n setSelectionEnd({ rowIndex: nr, colIndex: nc });\n // Update overlay near the scroll container center\n const el = scrollRef.current;\n if (el) {\n const rect = el.getBoundingClientRect();\n setDragOverlay({\n x: rect.right - 16,\n y: rect.bottom - 16,\n rows: Math.abs((selectionAnchor?.rowIndex ?? nr) - nr) + 1,\n cols: Math.abs((selectionAnchor?.colIndex ?? nc) - nc) + 1,\n });\n }\n };\n window.addEventListener(\"keydown\", onKey);\n return () => window.removeEventListener(\"keydown\", onKey);\n }, [\n cellSelectionEnabled,\n focusedCell,\n selectionAnchor,\n selectionEnd,\n rowIndexById,\n colIndexByKey,\n flatRows.length,\n columnsWithWidths.length,\n ]);\n\n // Keyboard navigation for focused cell\n useEffect(() => {\n if (!cellFocusEnabled) return;\n const bodyEl = scrollRef.current;\n const headerEl = headerScrollRef.current;\n\n const ensureVisible = (rowIndex: number, colIndex: number) => {\n if (!bodyEl) return;\n // Vertical\n const viewportH = bodyEl.clientHeight;\n const targetTop = rowIndex * resolvedRowHeight;\n const targetBottom = targetTop + resolvedRowHeight;\n if (targetTop < bodyEl.scrollTop) bodyEl.scrollTop = targetTop;\n else if (targetBottom > bodyEl.scrollTop + viewportH)\n bodyEl.scrollTop = targetBottom - viewportH;\n\n // Horizontal\n const colWidth = (columnsWithWidths[colIndex]?.width as number) || 100;\n let left = selectable ? SELECT_COL_WIDTH : 0;\n for (let i = 0; i < colIndex; i++) {\n left += (columnsWithWidths[i]?.width as number) || 100;\n }\n const right = left + colWidth;\n const viewportW = bodyEl.clientWidth;\n if (left < bodyEl.scrollLeft) {\n bodyEl.scrollLeft = left;\n } else if (right > bodyEl.scrollLeft + viewportW) {\n bodyEl.scrollLeft = right - viewportW;\n }\n if (headerEl) headerEl.scrollLeft = bodyEl.scrollLeft;\n };\n\n const handler = (e: KeyboardEvent) => {\n if (!focusedCell) return;\n // Don't handle keyboard navigation if modal is open\n if (document.body.hasAttribute(\"data-modal-open\")) return;\n const { key } = e;\n if (\n key !== \"ArrowLeft\" &&\n key !== \"ArrowRight\" &&\n key !== \"ArrowUp\" &&\n key !== \"ArrowDown\"\n )\n return;\n e.preventDefault();\n const currentRowIdx = rowIndexById.get(focusedCell.rowId);\n const currentColIdx = colIndexByKey.get(focusedCell.columnKey);\n if (currentRowIdx == null || currentColIdx == null) return;\n let nextRow = currentRowIdx;\n let nextCol = currentColIdx;\n if (e.key === \"ArrowLeft\") nextCol = Math.max(0, currentColIdx - 1);\n if (e.key === \"ArrowRight\")\n nextCol = Math.min(columnsWithWidths.length - 1, currentColIdx + 1);\n if (e.key === \"ArrowUp\") nextRow = Math.max(0, currentRowIdx - 1);\n if (e.key === \"ArrowDown\")\n nextRow = Math.min(flatRows.length - 1, currentRowIdx + 1);\n\n const row = flatRows[nextRow];\n const column = columnsWithWidths[nextCol];\n if (!row || !column) return;\n\n setFocusedCell({ rowId: row.id, columnKey: column.key });\n if (onCellFocusChange) {\n onCellFocusChange({\n row,\n column,\n value: row[column.key],\n rowIndex: nextRow,\n colIndex: nextCol,\n });\n }\n ensureVisible(nextRow, nextCol);\n };\n window.addEventListener(\"keydown\", handler);\n return () => window.removeEventListener(\"keydown\", handler);\n }, [\n cellFocusEnabled,\n focusedCell,\n flatRows,\n columnsWithWidths,\n resolvedRowHeight,\n selectable,\n rowIndexById,\n colIndexByKey,\n onCellFocusChange,\n ]);\n\n // Notify parent about selection rectangle (guarded to avoid redundant callbacks)\n useEffect(() => {\n if (!cellSelectionEnabled || !selectionAnchor || !selectionEnd) {\n const payload = { bounds: null as any, cells: [] as any[] };\n const sig = \"none\";\n if (sig !== prevSelectionSignatureRef.current) {\n prevSelectionSignatureRef.current = sig;\n onCellSelectionChangeRef.current?.(payload);\n }\n return;\n }\n\n const rowStart = Math.min(\n selectionAnchor.rowIndex,\n selectionEnd.rowIndex,\n );\n const rowEnd = Math.max(selectionAnchor.rowIndex, selectionEnd.rowIndex);\n const colStart = Math.min(\n selectionAnchor.colIndex,\n selectionEnd.colIndex,\n );\n const colEnd = Math.max(selectionAnchor.colIndex, selectionEnd.colIndex);\n\n const cells: Array<{\n row: any;\n column: any;\n value: any;\n rowIndex: number;\n colIndex: number;\n }> = [];\n for (let r = rowStart; r <= rowEnd; r++) {\n const row = flatRows[r];\n if (!row) continue;\n for (let c = colStart; c <= colEnd; c++) {\n const column = columnsWithWidths[c];\n if (!column) continue;\n if (!canSelectCell(row, column)) continue;\n cells.push({\n row,\n column,\n value: row[column.key],\n rowIndex: r,\n colIndex: c,\n });\n }\n }\n\n const payload = {\n bounds: { rowStart, rowEnd, colStart, colEnd },\n cells,\n };\n const sig = `${rowStart}-${rowEnd}-${colStart}-${colEnd}|len:${cells.length}`;\n if (sig === prevSelectionSignatureRef.current) return;\n prevSelectionSignatureRef.current = sig;\n onCellSelectionChangeRef.current?.(payload);\n }, [\n cellSelectionEnabled,\n selectionAnchor,\n selectionEnd,\n flatRows,\n columnKeys,\n canSelectCell,\n ]);\n\n // ================= COPY HANDLING (Ctrl/Cmd + C) =================\n useEffect(() => {\n // Enable custom copy when either rectangular selection or cell focus mode is active.\n if (!cellSelectionEnabled && !cellFocusEnabled) return;\n const onKeyDown = async (e: KeyboardEvent) => {\n const meta = e.metaKey || e.ctrlKey;\n if (!meta || e.key.toLowerCase() !== \"c\") return;\n const includeHeaders = !!e.shiftKey; // Hold Shift to include header row\n // Determine context\n const hasRect = !!(selectionAnchor && selectionEnd);\n const hasFocus = !!(cellFocusEnabled && focusedCell);\n if (!hasRect && !hasFocus) return; // nothing to do\n\n // If only focused cell (no rectangle) and user has an actual text selection or editing input, allow default behavior\n if (!hasRect && hasFocus) {\n const sel = window.getSelection();\n if (sel && sel.toString().length > 0) return; // user selected text manually\n const active = document.activeElement as HTMLElement | null;\n if (\n active &&\n (active.tagName === \"INPUT\" ||\n active.tagName === \"TEXTAREA\" ||\n active.isContentEditable)\n ) {\n return; // let native copy proceed inside editable fields\n }\n }\n\n // We'll handle copy ourselves now\n e.preventDefault();\n\n const collectCells = (): Array<{\n row: any;\n column: any;\n value: any;\n rowIndex: number;\n colIndex: number;\n }> => {\n const cells: Array<{\n row: any;\n column: any;\n value: any;\n rowIndex: number;\n colIndex: number;\n }> = [];\n if (hasRect && selectionAnchor && selectionEnd) {\n const rowStart = Math.min(\n selectionAnchor.rowIndex,\n selectionEnd.rowIndex,\n );\n const rowEnd = Math.max(\n selectionAnchor.rowIndex,\n selectionEnd.rowIndex,\n );\n const colStart = Math.min(\n selectionAnchor.colIndex,\n selectionEnd.colIndex,\n );\n const colEnd = Math.max(\n selectionAnchor.colIndex,\n selectionEnd.colIndex,\n );\n for (let r = rowStart; r <= rowEnd; r++) {\n const row = flatRows[r];\n if (!row) continue;\n for (let c = colStart; c <= colEnd; c++) {\n const column = columnsWithWidths[c];\n if (!column) continue;\n if (!canSelectCell(row, column)) continue;\n cells.push({\n row,\n column,\n value: row[column.key],\n rowIndex: r,\n colIndex: c,\n });\n }\n }\n } else if (hasFocus && focusedCell) {\n const rIndex = rowIndexById.get(focusedCell.rowId);\n const cIndex = colIndexByKey.get(focusedCell.columnKey);\n if (rIndex != null && cIndex != null) {\n const row = flatRows[rIndex];\n const column = columnsWithWidths[cIndex];\n if (row && column) {\n cells.push({\n row,\n column,\n value: row[column.key],\n rowIndex: rIndex,\n colIndex: cIndex,\n });\n }\n }\n }\n return cells;\n };\n\n const cells = collectCells();\n if (!cells.length) return;\n\n const escapeCell = (val: any): string => {\n const s = val == null ? \"\" : String(val);\n if (\n s.includes('\"') ||\n s.includes(\"\\t\") ||\n s.includes(\"\\n\") ||\n s.includes(\"\\r\")\n ) {\n return '\"' + s.replace(/\"/g, '\"\"') + '\"';\n }\n return s;\n };\n\n // Build tab / newline delimited text (Excel friendly)\n let text = \"\";\n if (hasRect && selectionAnchor && selectionEnd) {\n const rowStart = Math.min(\n selectionAnchor.rowIndex,\n selectionEnd.rowIndex,\n );\n const rowEnd = Math.max(\n selectionAnchor.rowIndex,\n selectionEnd.rowIndex,\n );\n const colStart = Math.min(\n selectionAnchor.colIndex,\n selectionEnd.colIndex,\n );\n const colEnd = Math.max(\n selectionAnchor.colIndex,\n selectionEnd.colIndex,\n );\n if (includeHeaders) {\n const headers: string[] = [];\n for (let c = colStart; c <= colEnd; c++) {\n const column = columnsWithWidths[c];\n if (!column) continue;\n headers.push(escapeCell((column as any).header ?? column.key));\n }\n text += headers.join(\"\\t\") + \"\\n\";\n }\n for (let r = rowStart; r <= rowEnd; r++) {\n const row = flatRows[r];\n if (!row) continue;\n const line: string[] = [];\n for (let c = colStart; c <= colEnd; c++) {\n const column = columnsWithWidths[c];\n if (!column) continue;\n if (!canSelectCell(row, column)) {\n line.push(\"\");\n continue;\n }\n const raw = row[column.key];\n line.push(escapeCell(raw));\n }\n text += line.join(\"\\t\");\n if (r < rowEnd) text += \"\\n\";\n }\n } else {\n // Single focused cell\n const cell = cells[0];\n text = escapeCell(cell.value);\n }\n\n try {\n await navigator.clipboard.writeText(text);\n } catch {\n console.warn(\"Failed to write to clipboard\");\n }\n\n // Fire optional callback if provided\n if (typeof onCopyCellsRef.current === \"function\") {\n const bounds =\n hasRect && selectionAnchor && selectionEnd\n ? {\n rowStart: Math.min(\n selectionAnchor.rowIndex,\n selectionEnd.rowIndex,\n ),\n rowEnd: Math.max(\n selectionAnchor.rowIndex,\n selectionEnd.rowIndex,\n ),\n colStart: Math.min(\n selectionAnchor.colIndex,\n selectionEnd.colIndex,\n ),\n colEnd: Math.max(\n selectionAnchor.colIndex,\n selectionEnd.colIndex,\n ),\n }\n : null;\n try {\n onCopyCellsRef.current({\n text,\n bounds,\n cells,\n isRectangular: !!bounds,\n isFocusedCell: !bounds,\n });\n } catch {\n /* swallow */\n }\n }\n };\n window.addEventListener(\"keydown\", onKeyDown);\n return () => window.removeEventListener(\"keydown\", onKeyDown);\n }, [\n cellSelectionEnabled,\n cellFocusEnabled,\n selectionAnchor,\n selectionEnd,\n focusedCell,\n flatRows,\n columnsWithWidths,\n canSelectCell,\n rowIndexById,\n colIndexByKey,\n ref,\n ]);\n\n const totalWidth = columnsWithWidths.reduce(\n (sum, col) => sum + (col.width || 100),\n 0,\n );\n\n useEffect(() => {\n if (currentPage !== 1) {\n // When filters change, reset pagination to the first page.\n // In server mode, also trigger a server fetch for page 1.\n if (pagination?.enabled && pagination.mode === \"server\") {\n handlePageChange(1);\n } else {\n resetPage();\n }\n }\n // Note: do not depend on currentPage or pagination props here,\n // to avoid resetting when the user simply navigates pages.\n // This effect should only respond to filter changes.\n }, [globalFilter, columnFilters]);\n\n return (\n <div\n ref={containerRef}\n className=\"border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden bg-white dark:bg-gray-900 h-full flex flex-col\"\n data-grid-container\n >\n {/* Search Toolbar */}\n {showToolbar && filterable && (\n <SearchToolbar\n globalFilter={globalFilter}\n filteredDataLength={filteredData.length}\n totalDataLength={paginationConfig.totalRows}\n paginationMode={pagination?.mode}\n selectedRowsCount={selectedRows.size}\n showExport={showExport}\n columns={columns}\n columnFilters={columnFilters}\n columnVisibility={columnVisibility}\n onResetColumns={resetColumns}\n exportOptions={{\n enabled: (exportOptionsProp?.enabled ?? true) && showExport,\n formats: exportOptionsProp?.formats ?? [\"xlsx\"],\n filename: exportOptionsProp?.filename ?? \"grid-data\",\n onExport: handleToolbarExport,\n }}\n customLeftContent={toolbarLeft}\n customRightContent={toolbarRight}\n onGlobalFilterChange={handleGlobalFilterChange}\n onClearFilters={handleClearFilters}\n onColumnFilter={setColumnFilter}\n onColumnVisibilityChange={handleColumnVisibilityChange}\n columnOrder={columnOrder}\n onColumnOrderChange={setColumnOrder}\n pinnedColumns={pinnedColumns}\n onScrollToColumn={(columnKey) => {\n const bodyEl = scrollRef.current;\n const headerEl = headerScrollRef.current;\n if (!bodyEl) return;\n // Find column index in current render order\n const idx = colIndexByKey.get(columnKey);\n if (idx == null) return;\n // Compute left position of the column by summing widths of previous columns\n const colWidth = (columnsWithWidths[idx]?.width as number) || 100;\n let left = selectable ? SELECT_COL_WIDTH : 0;\n for (let i = 0; i < idx; i++) {\n left += (columnsWithWidths[i]?.width as number) || 100;\n }\n const right = left + colWidth;\n const viewportW = bodyEl.clientWidth;\n // Scroll behavior: if already in view, minimal movement; otherwise align left\n if (left < bodyEl.scrollLeft) {\n bodyEl.scrollTo({ left, behavior: \"smooth\" });\n } else if (right > bodyEl.scrollLeft + viewportW) {\n bodyEl.scrollTo({\n left: right - viewportW,\n behavior: \"smooth\",\n });\n } else {\n // Nudge slightly to center it\n const center = Math.max(\n 0,\n left - Math.max(0, (viewportW - colWidth) / 2),\n );\n bodyEl.scrollTo({ left: center, behavior: \"smooth\" });\n }\n if (headerEl) headerEl.scrollLeft = bodyEl.scrollLeft;\n }}\n density={density}\n onDensityChange={handleSetDensity}\n showDensityControl={showDensityControl}\n />\n )}\n\n {/* Grid Container */}\n <div className=\"flex flex-col relative flex-1 min-h-50\">\n {/* Group Bar (drag columns here to group) */}\n {groupable &&\n (groupBarVisibility === \"visible\" ||\n (groupBarVisibility === \"auto\" &&\n groupConfig.columnKeys.length > 0)) && (\n <GroupBar\n columns={columns}\n groupedKeys={groupConfig.columnKeys}\n onRemove={removeGroupKey}\n onReorder={setGroupKeys}\n onDropColumnKey={addGroupKey}\n isAnyExpanded={groupConfig.expanded.size > 0}\n onToggleExpandAll={() => {\n if (groupConfig.expanded.size > 0) {\n collapseAllGroups();\n } else {\n expandAllGroups();\n }\n }}\n />\n )}\n {/* Header moved inside body scroll area as sticky for perfect sync */}\n\n {/* Body */}\n <div\n ref={scrollRef}\n className={`flex-1 overflow-auto relative [&::-webkit-scrollbar]:thin ${\n cellSelectionEnabled ? \"select-none\" : \"\"\n }`}\n onScroll={handleScroll}\n >\n {/* Sticky header inside the same scroll container */}\n <div className=\"sticky top-0 z-3\">\n <div\n style={{\n minWidth: `${\n totalWidth + (selectable ? SELECT_COL_WIDTH : 0)\n }px`,\n }}\n >\n {(() => {\n const headerPinned = pinnedAll;\n const headerUnpinned = visibleColumns.filter(\n (c) => !effectivePinnedColumns.has(c.key),\n );\n\n return (\n <GridHeader\n pinnedColumns={headerPinned}\n unpinnedColumns={headerUnpinned}\n hvPadLeft={hvPadLeftMemo}\n hvPadRight={hvPadRightMemo}\n headerHeight={resolvedHeaderHeight}\n sortConfig={sortConfig}\n columnFilters={columnFilters}\n selectable={selectable}\n selectedRows={selectedRows}\n totalRows={dataToDisplay.length}\n data={data}\n onSort={handleSort}\n onColumnFilter={setColumnFilter}\n onSelectAll={() =>\n handleSelectAll(\n selectedRows.size !== dataToDisplay.length,\n )\n }\n onColumnResize={handleColumnResize}\n pinnedKeySet={effectivePinnedColumns}\n onColumnPin={handleColumnPin}\n groupable={groupable}\n groupedByColumn={groupConfig.columnKeys[0] || null}\n groupedByColumns={groupConfig.columnKeys}\n onGroupToggle={(key, next) =>\n next ? addGroupKey(key) : removeGroupKey(key)\n }\n onGroupBy={handleGroupBy}\n onAutosizeColumn={autosizeColumn}\n onAutosizeAllColumns={autosizeAllColumns}\n onResetColumns={resetColumns}\n columnOrder={columnOrder}\n onColumnOrderChange={setColumnOrder}\n paginationMode={\n pagination?.enabled ? pagination.mode : null\n }\n />\n );\n })()}\n </div>\n </div>\n\n <div\n style={{\n minWidth: `${totalWidth + (selectable ? SELECT_COL_WIDTH : 0)}px`,\n height: effectiveVirtualized\n ? `${dataToDisplay.length * resolvedRowHeight}px`\n : \"auto\",\n }}\n >\n {/* Loading bar is rendered at the bottom of the sticky header above */}\n {/* Empty state: content area renders nothing; overlay is placed outside scrollRef */}\n {!isLoading && dataToDisplay.length === 0 ? (\n <></>\n ) : (\n <div\n style={{\n transform: `translateY(${\n effectiveVirtualized ? virtualizedRange.offsetY : 0\n }px)`,\n willChange: \"transform\",\n contain: \"content\",\n }}\n >\n {(() => {\n const nodes: React.ReactNode[] = [];\n let chunk: any[] = [];\n const flush = () => {\n if (!chunk.length) return;\n const key = `chunk-${chunk[0]?.id}-${chunk.length}-${virtualizedRange.offsetY}`;\n nodes.push(\n <div key={key} style={{ opacity: isLoading ? 0.5 : 1 }}>\n <GridRows\n data={chunk}\n columns={visibleColumns}\n selectedRows={selectedRows}\n virtualized={false}\n virtualizedRange={{\n startIndex: 0,\n endIndex: chunk.length - 1,\n offsetY: 0,\n }}\n rowHeight={resolvedRowHeight}\n selectable={selectable}\n isRowSelectable={isRowSelectable}\n onRowSelect={handleRowSelect}\n pinnedColumns={effectivePinnedColumns}\n hvPadLeft={hvPadLeftMemo}\n hvPadRight={hvPadRightMemo}\n rowStyle={rowStyle}\n globalFilter={globalFilter}\n onContextMenu={onContextMenu}\n onRowDoubleClick={onRowDoubleClick}\n onRowClick={onRowClick}\n onCellClick={onCellClick}\n onCellContextMenu={onCellContextMenu}\n isCellFocused={isCellFocused}\n isCellSelected={isCellSelected}\n onCellMouseDown={handleCellMouseDown}\n onCellMouseEnter={handleCellMouseEnter}\n getRowId={getRowId}\n />\n </div>,\n );\n chunk = [];\n };\n\n for (const row of visibleData) {\n if ((row as any)._isGroupHeader) {\n flush();\n nodes.push(\n <GroupHeader\n key={row.id}\n row={row}\n isExpanded={groupConfig.expanded.has(\n row._groupKey || \"\",\n )}\n onToggle={toggleGroupExpansion}\n viewportWidth={containerWidth}\n selectable={selectable}\n rowHeight={resolvedRowHeight}\n getHeaderLabel={(colKey) =>\n columns.find((c) => c.key === colKey)?.header ||\n colKey\n }\n getValueLabel={(colKey, raw) => {\n const col = columns.find((c) => c.key === colKey);\n if (col?.formatter) {\n try {\n return col.formatter(raw);\n } catch (_) {\n return String(raw ?? \"\");\n }\n }\n return String(raw ?? \"\");\n }}\n renderGroupActions={renderGroupActions}\n />,\n );\n } else if ((row as any)._isGroupFooter) {\n flush();\n // Use a consistent light blue theme for aggregate footers (with dark mode support)\n if (groupFooterVariant === \"chips\") {\n // Build chips for columns that requested aggregation and have a value\n const chips = columnsWithWidths\n .filter(\n (c) =>\n !!c.aggregate &&\n (row as any)._groupAgg &&\n (row as any)._groupAgg[c.key] !== undefined,\n )\n .map((c) => {\n const rawVal = (row as any)._groupAgg[c.key];\n const fmt = c.aggregateFormatter || c.formatter;\n const display = fmt\n ? (() => {\n try {\n return fmt(rawVal);\n } catch {\n return String(rawVal);\n }\n })()\n : String(rawVal);\n return (\n <span\n key={c.key}\n className={\n // Use static Tailwind classes to avoid JIT purge issues\n \"px-2.5 py-1 rounded-md bg-blue-50 dark:bg-blue-900/40 text-blue-700 dark:text-blue-200 text-xs font-medium\"\n }\n title={`${c.header}`}\n >\n {c.header}: {display}\n </span>\n );\n });\n\n nodes.push(\n <div\n key={row.id}\n className=\"sticky left-0 z-1\"\n style={{\n minWidth: `${\n totalWidth +\n (selectable ? SELECT_COL_WIDTH : 0)\n }px`,\n height: `${resolvedRowHeight}px`,\n }}\n >\n <div\n className={\n // Static Tailwind classes for 'blue' theme\n \"flex items-center justify-between h-full border-t border-blue-200 dark:border-blue-800 bg-blue-50/60 dark:bg-blue-900/20 px-4\"\n }\n role=\"contentinfo\"\n >\n <div className=\"flex items-center gap-2 flex-wrap overflow-hidden\">\n {chips.length ? (\n chips\n ) : (\n <span className=\"text-xs text-gray-500\">\n No aggregates\n </span>\n )}\n </div>\n <span className=\"text-[10px] uppercase tracking-wide text-blue-700 dark:text-blue-300\">\n Group Summary\n </span>\n </div>\n </div>,\n );\n } else {\n // columns variant: show aggregate values in-place under their respective columns\n nodes.push(\n <div\n key={row.id}\n className=\"sticky left-0 z-1 bg-blue-100 dark:bg-gray-900\"\n style={{\n minWidth: `${\n totalWidth +\n (selectable ? SELECT_COL_WIDTH : 0)\n }px`,\n height: `${resolvedRowHeight}px`,\n }}\n >\n <div\n className={\n // Static Tailwind classes matching the 'chips' variant theme\n \"flex h-full border-t border-blue-200 dark:border-blue-800 bg-blue-50/60 dark:bg-blue-900/20\"\n }\n role=\"contentinfo\"\n >\n {selectable && (\n <div\n style={{ width: SELECT_COL_WIDTH }}\n className=\"shrink-0\"\n />\n )}\n {columnsWithWidths.map((col) => {\n const width = (col.width as number) || 100;\n const rawVal = (row as any)._groupAgg\n ? (row as any)._groupAgg[col.key]\n : undefined;\n const fmt =\n col.aggregateFormatter || col.formatter;\n const raw =\n rawVal === undefined\n ? \"\"\n : fmt\n ? (() => {\n try {\n return fmt(rawVal);\n } catch {\n return rawVal;\n }\n })()\n : rawVal;\n\n // ensure final format is 2 decimals only for decimal numbers\n let display;\n if (typeof raw === \"number\") {\n display = Number.isInteger(raw)\n ? String(raw)\n : raw.toFixed(2);\n } else if (\n !isNaN(raw) &&\n raw !== \"\" &&\n raw !== null\n ) {\n // also handles when formatter returned string numbers\n const num = Number(raw);\n display = Number.isInteger(num)\n ? String(num)\n : num.toFixed(2);\n } else {\n display = String(raw ?? \"\");\n }\n return (\n <div\n key={`agg-cell-${(row as any)._groupKey}-${\n col.key\n }`}\n className=\"px-2 text-xs font-medium text-blue-800 dark:text-blue-200 flex items-center overflow-hidden\"\n style={{\n width,\n minWidth: width,\n maxWidth: width,\n }}\n title={\n display\n ? `${col.header}: ${display}`\n : undefined\n }\n >\n <span className=\"truncate w-full\">\n {display}\n </span>\n </div>\n );\n })}\n </div>\n </div>,\n );\n }\n } else {\n chunk.push(row);\n }\n }\n flush();\n return nodes;\n })()}\n </div>\n )}\n </div>\n </div>\n {/* Loading bar overlay (outside scroll area, like NoDataMessage) */}\n {showLoader && (\n <div\n className={`pointer-events-none absolute left-0 right-0 h-1 bg-gray-200 overflow-hidden z-30 ${\n finishingLoader\n ? \"opacity-0 transition-opacity duration-200\"\n : \"opacity-100\"\n }`}\n style={{ top: loaderTop }}\n >\n <div className=\"h-full w-1/3 bg-blue-500 animate-[slide_1.2s_linear_infinite]\" />\n </div>\n )}\n {/* Viewport overlay for NoDataMessage that does not scroll horizontally/vertically */}\n {!isLoading && dataToDisplay.length === 0 && (\n <div className=\"pointer-events-none absolute inset-0 z-0 flex items-center justify-center\">\n <div className=\"pointer-events-auto\">\n <NoDataMessage\n hasFilters={\n !!globalFilter || Object.keys(columnFilters).length > 0\n }\n hasData={data.length > 0}\n />\n </div>\n </div>\n )}\n </div>\n\n {/* Footer Aggregate */}\n {hasFooterAggregate && (\n <div\n ref={footerScrollRef}\n className=\"shrink-0 overflow-x-hidden overflow-y-visible [&::-webkit-scrollbar]:hidden\"\n style={{ scrollbarWidth: \"none\", msOverflowStyle: \"none\" }}\n onWheel={forwardWheelToBody}\n >\n <div\n className=\"bg-gray-50 dark:bg-gray-800 border-t border-gray-200 dark:border-gray-700\"\n style={{\n minWidth: `${totalWidth + (selectable ? SELECT_COL_WIDTH : 0)}px`,\n height: `${resolvedRowHeight}px`,\n }}\n >\n <FooterAggregate\n columns={columnsWithWidths}\n data={flatRows}\n selectable={selectable}\n rowHeight={resolvedRowHeight}\n pinnedColumns={effectivePinnedColumns}\n />\n </div>\n </div>\n )}\n\n {/* Pagination Footer */}\n\n <PaginationControls\n paginationConfig={paginationConfig}\n currentPage={paginationConfig.currentPage}\n isServerLoading={isServerLoading}\n selectedRowsCount={selectedRows.size}\n totalDataLength={data.length}\n filteredDataLength={\n pagination?.mode === \"server\"\n ? undefined // Don't pass filtered data length for server mode\n : filteredData.length\n }\n paginationMode={pagination.mode}\n onPageChange={handlePageChange}\n onPageSizeChange={handlePageSizeChange}\n />\n\n {/* Drag selection overlay (fixed near cursor) */}\n {dragOverlay && (\n <div\n className=\"fixed z-50 pointer-events-none select-none\"\n style={{ top: dragOverlay.y + 12, left: dragOverlay.x + 12 }}\n >\n <div className=\"px-2 py-1 rounded bg-gray-800 text-white text-xs shadow-lg opacity-90\">\n {dragOverlay.rows} × {dragOverlay.cols}\n </div>\n </div>\n )}\n </div>\n );\n },\n);\n\nexport default KDGrid;\n"],"names":["REACT_ELEMENT_TYPE","Symbol","for","REACT_FRAGMENT_TYPE","jsxProd","type","config","maybeKey","key","propName","$$typeof","ref","props","reactJsxRuntime_production","Fragment","jsx","jsxs","process","env","NODE_ENV","getComponentNameFromType","REACT_CLIENT_REFERENCE","displayName","name","REACT_PROFILER_TYPE","REACT_STRICT_MODE_TYPE","REACT_SUSPENSE_TYPE","REACT_SUSPENSE_LIST_TYPE","REACT_ACTIVITY_TYPE","tag","console","error","REACT_PORTAL_TYPE","REACT_CONTEXT_TYPE","REACT_CONSUMER_TYPE","_context","REACT_FORWARD_REF_TYPE","innerType","render","REACT_MEMO_TYPE","REACT_LAZY_TYPE","_payload","_init","x","testStringCoercion","value","checkKeyStringCoercion","JSCompiler_inline_result","e","JSCompiler_inline_result$jscomp$0","toStringTag","constructor","call","getTaskName","UnknownOwner","Error","elementRefGetterWithDeprecationWarning","componentName","this","didWarnAboutElementRef","jsxDEVImpl","isStaticChildren","debugStack","debugTask","dispatcher","children","isArrayImpl","length","validateChildKeys","Object","freeze","hasOwnProperty","keys","filter","k","join","didWarnAboutKeySpread","getter","getOwnPropertyDescriptor","get","isReactWarning","hasValidKey","warnAboutAccessingKey","specialPropKeyWarningShown","defineProperty","configurable","defineKeyPropWarningGetter","owner","refProp","_owner","enumerable","_store","writable","ReactElement","ReactSharedInternals","A","getOwner","node","isValidElement","validated","status","object","React","require$$0","__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE","prototype","Array","isArray","createTask","unknownOwnerDebugStack","react_stack_bottom_frame","callStackForError","bind","unknownOwnerDebugTask","reactJsxRuntime_development","trackActualOwner","recentlyCreatedOwnerStacks","jsxRuntimeModule","exports","require$$1","SELECT_COL_WIDTH","FooterAggregate","memo","columns","data","selectable","rowHeight","pinnedColumns","Set","aggregateValues","useMemo","result","columnsWithFooterAgg","col","footer_aggregate","forEach","values","map","row","aggValue","warn","isDateLike","s","test","includes","Number","isFinite","Date","parse","nums","v","NaN","sv","String","n","parseFloat","replace","tryDateNumbers","getTime","t","reduce","a","b","Math","min","dateNums","max","some","totalWidth","sum","width","leftOffsetByPinnedKey","Map","pinnedKeysInOrder","c","has","acc","set","find","_jsxs","className","style","minWidth","height","_jsx","rawValue","hasAggregate","undefined","displayValue","formatter","footerAggregateFormatter","toString","toFixed","isPinned","leftOffset","noPadding","align","maxWidth","left","title","header","prev","next","getRowId","i","pc","nc","extractId","idx","id","prevFirst","nextFirst","prevLastIdx","nextLastIdx","prevLast","nextLast","size","Icon","xmlns","viewBox","fill","stroke","strokeWidth","strokeLinecap","strokeLinejoin","focusable","ChevronLeft","p","points","ChevronRight","ChevronDown","ChevronsLeft","ChevronsRight","ArrowUp","x1","y1","x2","y2","ArrowDown","ArrowUpDown","d","X","Check","Copy","y","rx","ry","Edit","Trash2","Archive","Download","Menu","Filter","FilterX","Settings","cx","cy","r","Pin","PinOff","Group","Ungroup","MoreHorizontal","Eye","EyeOff","Search","Database","FileText","Table","Users","LocateFixed","Loader2","TextFilter","onChange","placeholder","textValue","setTextValue","useState","operator","setOperator","newOperator","op","trim","handleOperatorChange","target","handleTextChange","newText","NumberFilter","numberValue","setNumberValue","secondValue","setSecondValue","handleValueChange","newValue","isSecond","numValue","numSecondValue","isNaN","DatePicker","label","toYMD","getFullYear","getMonth","padStart","getDate","fromYMD","m","split","toDMY","DateFilter","toDateObj","toStored","dateValue","setDateValue","secondDateValue","setSecondDateValue","useEffect","clampDate","date","minDate","maxDate","handleDateChange","newDate","nextSecond","maxForFirst","maxDateObj","clampedDate","minDateObj","end","MultiselectFilter","options","columnKey","searchText","setSearchText","selectedValues","setSelectedValues","availableOptions","opts","isBlankValue","val","normalizedValues","processedOptions","opt","isBlank","from","sort","localeCompare","filteredOptions","searchLower","toLowerCase","option","onClick","allValues","index","isSelected","optionValue","newSelected","delete","add","handleToggleValue","BooleanFilter","booleanValue","setBooleanValue","FilterContent","column","filterConfig","filterable","sampleValues","slice","firstValue","uniqueValues","GridHeaderComponent","unpinnedColumns","hvPadLeft","hvPadRight","headerHeight","sortConfig","columnFilters","selectedRows","totalRows","onSort","onColumnFilter","onSelectAll","onColumnResize","pinnedKeySet","onColumnPin","groupable","groupedByColumn","onGroupBy","groupedByColumns","onGroupToggle","onAutosizeColumn","onAutosizeAllColumns","onResetColumns","columnOrder","onColumnOrderChange","paginationMode","allColumns","activeColumnMenu","setActiveColumnMenu","menuPosition","setMenuPosition","isResizing","setIsResizing","startX","setStartX","startWidth","setStartWidth","activeTab","setActiveTab","tempFilter","setTempFilter","isTouchDevice","setIsTouchDevice","window","navigator","maxTouchPoints","matchMedia","matches","menuReorderDraggingKey","setMenuReorderDraggingKey","menuReorderDragOver","setMenuReorderDragOver","isAllSelected","isIndeterminate","handleColumnMenuClick","event","stopPropagation","rect","currentTarget","getBoundingClientRect","containerEl","closest","containerRect","DOMRect","innerWidth","innerHeight","PADDING","clampedLeft","right","top","bottom","handleApplyFilter","hasActiveFilter","handleResizeStart","preventDefault","clientX","handleResizeMove","newWidth","handleResizeEnd","draggingKey","setDraggingKey","dragOver","setDragOver","handleDragStart","dataTransfer","effectAllowed","setData","handleDragOver","targetKey","dropEffect","position","handleDrop","sourceKey","before","base","indexOf","splice","handleDragEnd","handleMenuReorderDragStart","handleMenuReorderDragOver","clientY","handleMenuReorderDrop","handleMenuReorderDragEnd","document","addEventListener","body","cursor","userSelect","removeEventListener","handleClickOutside","_Fragment","role","checked","el","indeterminate","onKeyDown","pinnedIndex","headerJustify","headerAlign","colSortable","sortable","draggable","onDragStart","onDragOver","onDrop","onDragEnd","direction","maxHeight","isGrouped","Boolean","isPinnedItem","onMouseDown","onDoubleClick","nextPinned","GridHeader","GridRowsComponent","virtualized","virtualizedRange","isRowSelectable","onRowSelect","rowStyle","globalFilter","onContextMenu","onRowDoubleClick","onRowClick","onCellClick","isCellFocused","isCellSelected","onCellContextMenu","onCellMouseDown","onCellMouseEnter","totalHeight","widthByKey","pinnedCount","transform","offsetY","actualIndex","startIndex","customRowStyles","rowId","rowIndex","extractRowId","defaultRowColor","selectedRowColor","handleContextMenu","handleDoubleClick","handleRowClick","disabled","tabIndex","colIndex","rawCell","renderedValue","cellRenderer","searchQuery","query","containsSearchQuery","text","lowerText","parts","lastIndex","searchIndex","keyCounter","push","margin","highlightText","alignClass","justifyClass","paddingClass","extraCellClass","extraCellStyle","cellStyle","cell","handleCellClick","_isGroupHeader","_isGroupFooter","onMouseEnter","wrapCellContent","areEqual","endIndex","GridRows","GroupBar","groupedKeys","onRemove","onReorder","onDropColumnKey","onToggleExpandAll","isAnyExpanded","dragKey","setDragKey","dragOverKey","setDragOverKey","dragOverBefore","setDragOverBefore","labelFor","handleChipDragStart","handleChipDragOver","getData","order","GroupHeader","isExpanded","onToggle","viewportWidth","getHeaderLabel","getValueLabel","renderGroupActions","handleToggle","_groupKey","paddingLeft","_groupLevel","_groupColumnKey","_groupValue","_groupCount","groupKey","groupValue","rows","_groupRows","count","level","NoDataMessage","hasFilters","hasData","message","description","icon","PaginationControlsComponent","paginationConfig","currentPage","isServerLoading","selectedRowsCount","totalDataLength","filteredDataLength","onPageChange","onPageSizeChange","start","total","effectiveTotal","enabled","pageSize","getCurrentPageRange","isFiltered","toLocaleString","showPageSizeSelector","pageSizeOptions","totalPages","_","page","pages","current","maxVisible","delta","floor","isActive","PaginationControls","CustomSelect","searchable","isOpen","setIsOpen","searchTerm","setSearchTerm","highlightedIndex","setHighlightedIndex","containerRef","useRef","inputRef","listRef","selectedOption","contains","handleKeyDown","handleSelect","highlightedElement","scrollIntoView","block","behavior","setTimeout","focus","ColumnFilterSelector","filterableColumns","selectedColumn","setSelectedColumn","multiSearch","setMultiSearch","columnOptions","selectedColumnData","filterType","currentFilter","lowered","currentValues","newValues","selectOptions","parseInput","direct","asDate","primaryDate","secondDate","effectiveOperator","stored","renderFilterInput","entries","handleActiveFilterClick","formatDate","parsed","operatorLabel","equals","gt","gte","lt","lte","between","hasWindow","getNodeName","isNode","nodeName","getWindow","_node$ownerDocument","ownerDocument","defaultView","getDocumentElement","_ref","documentElement","Node","isElement","Element","isHTMLElement","HTMLElement","isShadowRoot","ShadowRoot","invalidOverflowDisplayValues","isOverflowElement","element","overflow","overflowX","overflowY","display","getComputedStyle","tableElements","isTableElement","topLayerSelectors","isTopLayer","selector","_e","transformProperties","willChangeValues","containValues","isContainingBlock","elementOrCss","webkit","isWebKit","css","containerType","backdropFilter","willChange","contain","CSS","supports","lastTraversableNodeNames","isLastTraversableNode","getNodeScroll","scrollLeft","scrollTop","scrollX","scrollY","getParentNode","assignedSlot","parentNode","host","getNearestOverflowAncestor","getOverflowAncestors","list","traverseIframes","_node$ownerDocument2","scrollableAncestor","isBody","win","frameElement","getFrameElement","concat","visualViewport","parent","getPrototypeOf","round","createCoords","oppositeSideMap","oppositeAlignmentMap","clamp","evaluate","param","getSide","placement","getAlignment","getOppositeAxis","axis","getAxisLength","yAxisSides","getSideAxis","getAlignmentAxis","getOppositeAlignmentPlacement","alignment","lrPlacement","rlPlacement","tbPlacement","btPlacement","getOppositePlacement","side","rectToClientRect","useLayoutEffect","useSafeInsertionEffect","useInsertionEffect","fn","computeCoordsFromPlacement","rtl","reference","floating","sideAxis","alignmentAxis","alignLength","isVertical","commonX","commonY","commonAlign","coords","async","detectOverflow","state","_await$platform$isEle","platform","rects","elements","strategy","boundary","rootBoundary","elementContext","altBoundary","padding","paddingObject","expandPaddingObject","getPaddingObject","clippingClientRect","getClippingRect","contextElement","offsetParent","getOffsetParent","offsetScale","getScale","elementClientRect","convertOffsetParentRelativeRectToViewportRelativeRect","originSides","getCssDimensions","getComputedStyle$1","hasOffset","offsetWidth","offsetHeight","shouldFallback","$","unwrapElement","domElement","noOffsets","getVisualOffsets","offsetLeft","offsetTop","includeScale","isFixedStrategy","clientRect","scale","visualOffsets","isFixed","floatingOffsetParent","shouldAddVisualOffsets","offsetWin","currentWin","currentIFrame","iframeScale","iframeRect","clientLeft","clientTop","paddingTop","getWindowScrollBarX","leftScroll","getHTMLOffset","scroll","htmlRect","absoluteOrFixed","getClientRectFromClippingAncestor","clippingAncestor","html","clientWidth","clientHeight","visualViewportBased","windowScrollbarX","doc","bodyStyles","bodyMarginInline","compatMode","marginLeft","marginRight","clippingStableScrollbarWidth","abs","getViewportRect","scrollWidth","scrollHeight","getDocumentRect","getInnerBoundingClientRect","hasFixedPositionAncestor","stopNode","getRectRelativeToOffsetParent","isOffsetParentAnElement","offsets","setLeftRTLScrollbarOffset","offsetRect","htmlOffset","isStaticPositioned","getTrueOffsetParent","polyfill","rawOffsetParent","svgOffsetParent","currentNode","getContainingBlock","topLayer","clippingAncestors","cache","cachedResult","currentContainingBlockComputedStyle","elementIsFixed","computedStyle","currentNodeIsContaining","ancestor","getClippingElementAncestors","_c","clippingRect","accRect","getElementRects","getOffsetParentFn","getDimensionsFn","getDimensions","floatingDimensions","getClientRects","isRTL","rectsAreEqual","autoUpdate","update","ancestorScroll","ancestorResize","elementResize","ResizeObserver","layoutShift","IntersectionObserver","animationFrame","referenceEl","ancestors","passive","cleanupIo","onMove","timeoutId","io","root","cleanup","_io","clearTimeout","disconnect","refresh","skip","threshold","elementRectForRootMargin","rootMargin","isFirstUpdate","handleObserve","ratio","intersectionRatio","observe","observeMove","frameId","reobserveFrame","resizeObserver","firstEntry","unobserve","cancelAnimationFrame","requestAnimationFrame","_resizeObserver","prevRefRect","frameLoop","nextRefRect","_resizeObserver2","offset","_middlewareData$offse","_middlewareData$arrow","middlewareData","diffCoords","mainAxisMulti","crossAxisMulti","mainAxis","crossAxis","convertValueToCoords","arrow","alignmentOffset","shift","checkMainAxis","checkCrossAxis","limiter","detectOverflowOptions","mainAxisCoord","crossAxisCoord","limitedCoords","flip","_middlewareData$flip","initialPlacement","fallbackPlacements","specifiedFallbackPlacements","fallbackStrategy","fallbackAxisSideDirection","flipAlignment","initialSideAxis","isBasePlacement","oppositePlacement","getExpandedPlacements","hasFallbackAxisSideDirection","isStart","getSideList","getOppositeAxisPlacements","placements","overflows","overflowsData","sides","mainAlignmentSide","getAlignmentSides","every","_middlewareData$flip2","_overflowsData$filter","nextIndex","nextPlacement","reset","resetPlacement","_overflowsData$filter2","currentSideAxis","_state$middlewareData","_state$middlewareData2","apply","isYAxis","heightSide","widthSide","maximumClippingHeight","maximumClippingWidth","availableHeight","availableWidth","xMin","xMax","yMin","yMax","nextDimensions","computePosition","mergedOptions","platformWithCache","middleware","validMiddleware","statefulPlacement","resetCount","_platform$detectOverf","nextX","nextY","computePosition$1","deepEqual","getDPR","devicePixelRatio","roundByDPR","dpr","useLatestRef","deps","offset$1","shift$1","size$1","SafeReact","serverHandoffComplete","genId","random","useId","setId","useModernLayoutEffect","devMessageSet","FloatingNodeContext","createContext","FloatingTreeContext","useFloating","nodeId","internalRootContext","open","onOpenChange","onOpenChangeProp","elementsProp","floatingId","dataRef","events","emit","_map$get","listener","on","off","_map$get2","createEventEmitter","nested","_React$useContext","useContext","optionDomReference","_devMessageSet3","_len2","arguments","messages","_key2","_devMessageSet4","positionReference","setPositionReference","callback","useCallback","_len","args","_key","useEffectEvent","reason","openEvent","refs","domReference","useFloatingRootContext","rootContext","computedElements","_domReference","setDomReference","_setPositionReference","domReferenceRef","tree","externalReference","externalFloating","whileElementsMounted","isPositioned","latestMiddleware","setLatestMiddleware","_reference","_setReference","_floating","_setFloating","setReference","referenceRef","setFloating","floatingRef","floatingEl","hasWhileElementsMounted","whileElementsMountedRef","platformRef","openRef","then","fullData","isMountedRef","ReactDOM","flushSync","floatingStyles","initialStyles","useFloating$1","computedPositionReference","context","floatingContext","nodesRef","Popover$1","anchorEl","onClose","sameWidth","zIndex","shouldIgnoreClose","fOffset","flip$1","createPortal","SearchToolbarComponent","showExport","showColumnToggle","showBulkActions","columnVisibility","bulkActions","exportOptions","onGlobalFilterChange","onClearFilters","onColumnVisibilityChange","onScrollToColumn","density","onDensityChange","showDensityControl","customLeftContent","customRightContent","showExportMenu","setShowExportMenu","showFilters","setShowFilters","showBulkActionsMenu","setShowBulkActionsMenu","showColumnMenu","setShowColumnMenu","columnSearch","setColumnSearch","searchInputRef","exportMenuRef","bulkActionsRef","columnMenuRef","filtersMenuRef","filtersAnchorRef","exportAnchorRef","bulkActionsAnchorRef","columnAnchorRef","getAttribute","dataset","popoverRoot","isInAnyPopover","classList","cls","isInMuiDatePicker","exportFormats","formats","hasActiveFilters","hasSelectedRows","visibleColumnsCount","filteredColumns","getExportIcon","format","getBulkActionIcon","action","getFormatLabel","handleExport","exportSelected","onExport","hasFilterableColumns","Popover","handleBulkAction","destructive","isVisible","handleColumnToggle","visible","toUpperCase","SearchToolbar","useAdvancedFiltering","globalFilterState","setGlobalFilterState","setColumnFilters","isFilterPending","startFilterTransition","useTransition","startColumnFilterTransition","setGlobalFilter","deferredGlobalFilter","useDeferredValue","applyColumnFilter","precomputed","filterText","startsWith","endsWith","filterNum","secondNum","filterTs","secondTs","raw","rowTs","normalizeBlank","rowSearchCacheRef","WeakMap","cacheSizeRef","clearCacheIfNeeded","filteredData","hasColumnFilters","hasGlobal","lowerGlobal","working","fd","sd","visibleColumns","packed","setColumnFilter","clearColumnFilter","clearAllFilters","getActiveFilterCount","workerFactory","ctx","self","processData","dir","av","bv","onmessage","msg","payload","postMessage","useDataWorker","workerRef","resolverRef","enabledRef","terminate","reject","DOMException","ensureWorkerRef","code","blob","Blob","blobUrl","URL","createObjectURL","w","Worker","revokeObjectURL","resolve","Promise","UNKNOWN","buildPath","gatherGroupPaths","colKey","str","arr","groupRows","computeAggregates","aggregate","aggVal","picked","usePagination","pagination","setCurrentPage","setPageSize","setIsServerLoading","resetPage","isEnabled","mode","serverConfig","ceil","paginatedData","handlePageChange","handlePageSizeChange","newPageSize","areSetsEqual","useSelection","selectedRowIds","setSelectedRows","rowByIdMap","needsPrune","handleRowSelect","newSet","handleSelectAll","useVirtualization","overscan","scrollRef","setScrollTop","rafIdRef","pendingScrollTopRef","containerHeight","setContainerHeight","ro","entry","h","contentRect","initial","rowsInView","dynamicOverscan","visibleCount","visibleData","handleScroll","DEFAULT_CAN_SELECT_CELL","KDGrid","forwardRef","densityProp","headerDensity","headerHeightProp","onSelectedRowsChange","showToolbar","rowHeightProp","cellFocusEnabled","onCellFocusChange","cellSelectionEnabled","canSelectCell","onCellSelectionChange","virtualizationThreshold","isLoading","onFilterChange","onColumnConfigChange","initialColumnConfig","toolbarLeft","toolbarRight","groupBarVisibility","groupFooterVariant","onCopyCells","performanceConfig","exportOptionsProp","containerWidth","setContainerWidth","focusedCell","setFocusedCell","selectionAnchor","setSelectionAnchor","selectionEnd","setSelectionEnd","isMouseDownRef","lastMousePosRef","autoScrollRafRef","dragOverlay","setDragOverlay","setDensity","densityMap","sm","md","lg","resolvedRowHeight","resolvedHeaderHeight","setSortConfig","columnWidths","setColumnWidths","initialWidths","initialWidthsRef","initialOrderRef","setColumnOrder","setPinnedColumns","setColumnVisibility","initialVisibility","handleSort","nextKey","nextDir","handleColumnResize","estimateWidthForText","autosizeColumn","headerWidth","sample","maxCell","computed","autosizeAllColumns","resetColumns","headerScrollRef","footerScrollRef","handleColumnPin","pinned","handleColumnVisibilityChange","workerProcess","sortedData","setSortedData","workerThreshold","sortWorkerThreshold","cancelled","out","loadingOverall","showLoader","setShowLoader","finishingLoader","setFinishingLoader","loaderTop","setLoaderTop","handleGlobalFilterChange","groupConfig","displayData","groupedDisplayData","handleGroupBy","addGroupKey","removeGroupKey","setGroupKeys","toggleGroupExpansion","expandAllGroups","collapseAllGroups","setGroupConfig","columnKeys","expanded","flat","recurse","pathParts","nextPath","pathStr","agg","_groupAgg","allPaths","differs","nextKeys","nextExpanded","groupPath","useGrouping","useImperativeHandle","getGroupConfig","effectivePinnedColumns","finalDisplayData","dataToDisplay","onSelectedRowsChangeRef","exportData","exportDataWithSelection","filename","getVisibleColumns","downloadFile","content","fileName","mimeType","url","link","createElement","href","download","appendChild","click","removeChild","exportToCSV","exportFilename","headers","exportToJSON","jsonData","JSON","stringify","exportToXLSX","default","ExcelJS","saveAs","all","import","workbook","Workbook","sheet","addWorksheet","sampled","coerceValue","maxLen","obj","addRow","getRow","font","bold","autoFilter","to","rowCount","buffer","xlsx","writeBuffer","canExportSelected","selectedCount","useExport","handleToolbarExport","selectedIds","exportMode","onServerExport","handleClearFilters","handleSetDensity","effectiveVirtualized","perfConfig","enableHorizontalVirtualization","horizontalVirtualizationThreshold","maxFilterCacheSize","enableAggressiveMemoization","hScrollLeft","setHScrollLeft","hScrollLeftRef","hScrollRafRef","scheduleHScrollUpdate","setViewportWidth","filterableKeys","existingKeys","fromEntries","pins","filters","filtered","remaining","timer","columnsWithWidths","orderIndex","candidate","viewportW","baseTotal","flexCols","flex","extra","totalWeight","POSITIVE_INFINITY","unpinned","groupIndex","needsHorizontalVirtualization","pinnedAll","unpinnedAll","unpinnedMeta","widths","prefix","leftPad","pinnedTotal","targetLeft","targetRight","localLeft","localRight","startIdx","lo","hi","ans","mid","firstIndexWithRightGte","endIdx","lastIndexWithLeftLte","sliced","unpinnedIndexByKey","hvPadLeftMemo","hvPadRightMemo","visibleUnpinned","firstIdx","lastIdx","hasFooterAggregate","bodyElement","isBodyScrolling","syncFromBody","footerEl","colIndexByKey","colByKey","flatRows","rowIndexById","rowById","prevSelectionSignatureRef","onCellSelectionChangeRef","onCopyCellsRef","rowObj","colObj","rMin","rMax","cMin","cMax","forwardWheelToBody","bodyEl","dx","deltaX","deltaY","scrollBy","handleCellMouseDown","rIndex","cIndex","hasAttribute","button","cols","handleCellMouseEnter","onUp","ensureAutoScrollLoop","step","mp","maxSpeed","dy","onKey","isShift","shiftKey","maxRow","maxCol","nr","headerEl","handler","currentRowIdx","currentColIdx","nextRow","nextCol","viewportH","targetTop","targetBottom","colWidth","ensureVisible","bounds","cells","sig","rowStart","rowEnd","colStart","colEnd","metaKey","ctrlKey","includeHeaders","hasRect","hasFocus","sel","getSelection","active","activeElement","tagName","isContentEditable","collectCells","escapeCell","line","clipboard","writeText","isRectangular","isFocusedCell","scrollTo","center","onScroll","headerPinned","headerUnpinned","nodes","chunk","flush","opacity","chips","rawVal","fmt","aggregateFormatter","isInteger","num","scrollbarWidth","msOverflowStyle","onWheel"],"mappings":"mYAWA,IAAIA,EAAqBC,OAAOC,IAAI,8BAClCC,EAAsBF,OAAOC,IAAI,kBACnC,SAASE,EAAQC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,EAAWM,KAC3BhrB,aAAcorB,GACdnrB,iBAAkBorB,KAInBkE,IACC7qC,EACEzK,IAAA,MAAA,CAAAqK,UAAU,6CACVC,MAAO,CAAEmQ,IAAK66B,GAAYjnC,EAAI,GAAI9C,KAAM+pC,GAAY1zC,EAAI,IAExDsB,SAAAkH,EAAAA,KAAA,MAAA,CAAKC,UAAU,wEAAuEnH,SAAA,CACnFoyC,GAAYxwB,KAAS,MAAAwwB,GAAYoO,YAM9C","x_google_ignoreList":[0,1,2,23,24,25,26,27,28,29]}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../node_modules/react/cjs/react-jsx-runtime.production.js","../node_modules/react/cjs/react-jsx-runtime.development.js","../node_modules/react/jsx-runtime.js","../src/constants.ts","../src/components/FooterAggregate.tsx","../src/icons/index.tsx","../src/components/filters/TextFilter.tsx","../src/components/filters/NumberFilter.tsx","../src/components/ui/DatePicker.tsx","../src/utils/dateUtils.ts","../src/components/filters/DateFilter.tsx","../src/components/filters/MultiselectFilter.tsx","../src/components/filters/BooleanFilter.tsx","../src/components/filters/FilterContent.tsx","../src/components/GridHeader.tsx","../src/components/RowContextMenu.tsx","../src/components/GridRows.tsx","../src/utils/highlightText.tsx","../src/components/GroupBar.tsx","../src/components/GroupHeader.tsx","../src/components/NoDataMessage.tsx","../src/components/PaginationControls.tsx","../src/components/CustomSelect.tsx","../src/components/ColumnFilterSelector.tsx","../node_modules/@floating-ui/utils/dist/floating-ui.utils.dom.mjs","../node_modules/@floating-ui/utils/dist/floating-ui.utils.mjs","../node_modules/@floating-ui/react/dist/floating-ui.react.utils.mjs","../node_modules/@floating-ui/core/dist/floating-ui.core.mjs","../node_modules/@floating-ui/dom/dist/floating-ui.dom.mjs","../node_modules/@floating-ui/react-dom/dist/floating-ui.react-dom.mjs","../node_modules/@floating-ui/react/dist/floating-ui.react.mjs","../src/components/Popover.tsx","../src/components/SearchToolbar.tsx","../src/hooks/useAdvancedFiltering.ts","../src/hooks/useDataWorker.ts","../src/hooks/useExport.ts","../src/hooks/useGrouping.ts","../src/hooks/usePagination.ts","../src/hooks/useSelection.ts","../src/hooks/useVirtualization.ts","../src/core/DataGrid.tsx"],"sourcesContent":["/**\n * @license React\n * react-jsx-runtime.production.js\n *\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n\"use strict\";\nvar REACT_ELEMENT_TYPE = Symbol.for(\"react.transitional.element\"),\n REACT_FRAGMENT_TYPE = Symbol.for(\"react.fragment\");\nfunction jsxProd(type, config, maybeKey) {\n var key = null;\n void 0 !== maybeKey && (key = \"\" + maybeKey);\n void 0 !== config.key && (key = \"\" + config.key);\n if (\"key\" in config) {\n maybeKey = {};\n for (var propName in config)\n \"key\" !== propName && (maybeKey[propName] = config[propName]);\n } else maybeKey = config;\n config = maybeKey.ref;\n return {\n $$typeof: REACT_ELEMENT_TYPE,\n type: type,\n key: key,\n ref: void 0 !== config ? config : null,\n props: maybeKey\n };\n}\nexports.Fragment = REACT_FRAGMENT_TYPE;\nexports.jsx = jsxProd;\nexports.jsxs = jsxProd;\n","/**\n * @license React\n * react-jsx-runtime.development.js\n *\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n\"use strict\";\n\"production\" !== process.env.NODE_ENV &&\n (function () {\n function getComponentNameFromType(type) {\n if (null == type) return null;\n if (\"function\" === typeof type)\n return type.$$typeof === REACT_CLIENT_REFERENCE\n ? null\n : type.displayName || type.name || null;\n if (\"string\" === typeof type) return type;\n switch (type) {\n case REACT_FRAGMENT_TYPE:\n return \"Fragment\";\n case REACT_PROFILER_TYPE:\n return \"Profiler\";\n case REACT_STRICT_MODE_TYPE:\n return \"StrictMode\";\n case REACT_SUSPENSE_TYPE:\n return \"Suspense\";\n case REACT_SUSPENSE_LIST_TYPE:\n return \"SuspenseList\";\n case REACT_ACTIVITY_TYPE:\n return \"Activity\";\n }\n if (\"object\" === typeof type)\n switch (\n (\"number\" === typeof type.tag &&\n console.error(\n \"Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue.\"\n ),\n type.$$typeof)\n ) {\n case REACT_PORTAL_TYPE:\n return \"Portal\";\n case REACT_CONTEXT_TYPE:\n return type.displayName || \"Context\";\n case REACT_CONSUMER_TYPE:\n return (type._context.displayName || \"Context\") + \".Consumer\";\n case REACT_FORWARD_REF_TYPE:\n var innerType = type.render;\n type = type.displayName;\n type ||\n ((type = innerType.displayName || innerType.name || \"\"),\n (type = \"\" !== type ? \"ForwardRef(\" + type + \")\" : \"ForwardRef\"));\n return type;\n case REACT_MEMO_TYPE:\n return (\n (innerType = type.displayName || null),\n null !== innerType\n ? innerType\n : getComponentNameFromType(type.type) || \"Memo\"\n );\n case REACT_LAZY_TYPE:\n innerType = type._payload;\n type = type._init;\n try {\n return getComponentNameFromType(type(innerType));\n } catch (x) {}\n }\n return null;\n }\n function testStringCoercion(value) {\n return \"\" + value;\n }\n function checkKeyStringCoercion(value) {\n try {\n testStringCoercion(value);\n var JSCompiler_inline_result = !1;\n } catch (e) {\n JSCompiler_inline_result = !0;\n }\n if (JSCompiler_inline_result) {\n JSCompiler_inline_result = console;\n var JSCompiler_temp_const = JSCompiler_inline_result.error;\n var JSCompiler_inline_result$jscomp$0 =\n (\"function\" === typeof Symbol &&\n Symbol.toStringTag &&\n value[Symbol.toStringTag]) ||\n value.constructor.name ||\n \"Object\";\n JSCompiler_temp_const.call(\n JSCompiler_inline_result,\n \"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.\",\n JSCompiler_inline_result$jscomp$0\n );\n return testStringCoercion(value);\n }\n }\n function getTaskName(type) {\n if (type === REACT_FRAGMENT_TYPE) return \"<>\";\n if (\n \"object\" === typeof type &&\n null !== type &&\n type.$$typeof === REACT_LAZY_TYPE\n )\n return \"<...>\";\n try {\n var name = getComponentNameFromType(type);\n return name ? \"<\" + name + \">\" : \"<...>\";\n } catch (x) {\n return \"<...>\";\n }\n }\n function getOwner() {\n var dispatcher = ReactSharedInternals.A;\n return null === dispatcher ? null : dispatcher.getOwner();\n }\n function UnknownOwner() {\n return Error(\"react-stack-top-frame\");\n }\n function hasValidKey(config) {\n if (hasOwnProperty.call(config, \"key\")) {\n var getter = Object.getOwnPropertyDescriptor(config, \"key\").get;\n if (getter && getter.isReactWarning) return !1;\n }\n return void 0 !== config.key;\n }\n function defineKeyPropWarningGetter(props, displayName) {\n function warnAboutAccessingKey() {\n specialPropKeyWarningShown ||\n ((specialPropKeyWarningShown = !0),\n console.error(\n \"%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)\",\n displayName\n ));\n }\n warnAboutAccessingKey.isReactWarning = !0;\n Object.defineProperty(props, \"key\", {\n get: warnAboutAccessingKey,\n configurable: !0\n });\n }\n function elementRefGetterWithDeprecationWarning() {\n var componentName = getComponentNameFromType(this.type);\n didWarnAboutElementRef[componentName] ||\n ((didWarnAboutElementRef[componentName] = !0),\n console.error(\n \"Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.\"\n ));\n componentName = this.props.ref;\n return void 0 !== componentName ? componentName : null;\n }\n function ReactElement(type, key, props, owner, debugStack, debugTask) {\n var refProp = props.ref;\n type = {\n $$typeof: REACT_ELEMENT_TYPE,\n type: type,\n key: key,\n props: props,\n _owner: owner\n };\n null !== (void 0 !== refProp ? refProp : null)\n ? Object.defineProperty(type, \"ref\", {\n enumerable: !1,\n get: elementRefGetterWithDeprecationWarning\n })\n : Object.defineProperty(type, \"ref\", { enumerable: !1, value: null });\n type._store = {};\n Object.defineProperty(type._store, \"validated\", {\n configurable: !1,\n enumerable: !1,\n writable: !0,\n value: 0\n });\n Object.defineProperty(type, \"_debugInfo\", {\n configurable: !1,\n enumerable: !1,\n writable: !0,\n value: null\n });\n Object.defineProperty(type, \"_debugStack\", {\n configurable: !1,\n enumerable: !1,\n writable: !0,\n value: debugStack\n });\n Object.defineProperty(type, \"_debugTask\", {\n configurable: !1,\n enumerable: !1,\n writable: !0,\n value: debugTask\n });\n Object.freeze && (Object.freeze(type.props), Object.freeze(type));\n return type;\n }\n function jsxDEVImpl(\n type,\n config,\n maybeKey,\n isStaticChildren,\n debugStack,\n debugTask\n ) {\n var children = config.children;\n if (void 0 !== children)\n if (isStaticChildren)\n if (isArrayImpl(children)) {\n for (\n isStaticChildren = 0;\n isStaticChildren < children.length;\n isStaticChildren++\n )\n validateChildKeys(children[isStaticChildren]);\n Object.freeze && Object.freeze(children);\n } else\n console.error(\n \"React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.\"\n );\n else validateChildKeys(children);\n if (hasOwnProperty.call(config, \"key\")) {\n children = getComponentNameFromType(type);\n var keys = Object.keys(config).filter(function (k) {\n return \"key\" !== k;\n });\n isStaticChildren =\n 0 < keys.length\n ? \"{key: someKey, \" + keys.join(\": ..., \") + \": ...}\"\n : \"{key: someKey}\";\n didWarnAboutKeySpread[children + isStaticChildren] ||\n ((keys =\n 0 < keys.length ? \"{\" + keys.join(\": ..., \") + \": ...}\" : \"{}\"),\n console.error(\n 'A props object containing a \"key\" prop is being spread into JSX:\\n let props = %s;\\n <%s {...props} />\\nReact keys must be passed directly to JSX without using spread:\\n let props = %s;\\n <%s key={someKey} {...props} />',\n isStaticChildren,\n children,\n keys,\n children\n ),\n (didWarnAboutKeySpread[children + isStaticChildren] = !0));\n }\n children = null;\n void 0 !== maybeKey &&\n (checkKeyStringCoercion(maybeKey), (children = \"\" + maybeKey));\n hasValidKey(config) &&\n (checkKeyStringCoercion(config.key), (children = \"\" + config.key));\n if (\"key\" in config) {\n maybeKey = {};\n for (var propName in config)\n \"key\" !== propName && (maybeKey[propName] = config[propName]);\n } else maybeKey = config;\n children &&\n defineKeyPropWarningGetter(\n maybeKey,\n \"function\" === typeof type\n ? type.displayName || type.name || \"Unknown\"\n : type\n );\n return ReactElement(\n type,\n children,\n maybeKey,\n getOwner(),\n debugStack,\n debugTask\n );\n }\n function validateChildKeys(node) {\n isValidElement(node)\n ? node._store && (node._store.validated = 1)\n : \"object\" === typeof node &&\n null !== node &&\n node.$$typeof === REACT_LAZY_TYPE &&\n (\"fulfilled\" === node._payload.status\n ? isValidElement(node._payload.value) &&\n node._payload.value._store &&\n (node._payload.value._store.validated = 1)\n : node._store && (node._store.validated = 1));\n }\n function isValidElement(object) {\n return (\n \"object\" === typeof object &&\n null !== object &&\n object.$$typeof === REACT_ELEMENT_TYPE\n );\n }\n var React = require(\"react\"),\n REACT_ELEMENT_TYPE = Symbol.for(\"react.transitional.element\"),\n REACT_PORTAL_TYPE = Symbol.for(\"react.portal\"),\n REACT_FRAGMENT_TYPE = Symbol.for(\"react.fragment\"),\n REACT_STRICT_MODE_TYPE = Symbol.for(\"react.strict_mode\"),\n REACT_PROFILER_TYPE = Symbol.for(\"react.profiler\"),\n REACT_CONSUMER_TYPE = Symbol.for(\"react.consumer\"),\n REACT_CONTEXT_TYPE = Symbol.for(\"react.context\"),\n REACT_FORWARD_REF_TYPE = Symbol.for(\"react.forward_ref\"),\n REACT_SUSPENSE_TYPE = Symbol.for(\"react.suspense\"),\n REACT_SUSPENSE_LIST_TYPE = Symbol.for(\"react.suspense_list\"),\n REACT_MEMO_TYPE = Symbol.for(\"react.memo\"),\n REACT_LAZY_TYPE = Symbol.for(\"react.lazy\"),\n REACT_ACTIVITY_TYPE = Symbol.for(\"react.activity\"),\n REACT_CLIENT_REFERENCE = Symbol.for(\"react.client.reference\"),\n ReactSharedInternals =\n React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,\n hasOwnProperty = Object.prototype.hasOwnProperty,\n isArrayImpl = Array.isArray,\n createTask = console.createTask\n ? console.createTask\n : function () {\n return null;\n };\n React = {\n react_stack_bottom_frame: function (callStackForError) {\n return callStackForError();\n }\n };\n var specialPropKeyWarningShown;\n var didWarnAboutElementRef = {};\n var unknownOwnerDebugStack = React.react_stack_bottom_frame.bind(\n React,\n UnknownOwner\n )();\n var unknownOwnerDebugTask = createTask(getTaskName(UnknownOwner));\n var didWarnAboutKeySpread = {};\n exports.Fragment = REACT_FRAGMENT_TYPE;\n exports.jsx = function (type, config, maybeKey) {\n var trackActualOwner =\n 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++;\n return jsxDEVImpl(\n type,\n config,\n maybeKey,\n !1,\n trackActualOwner\n ? Error(\"react-stack-top-frame\")\n : unknownOwnerDebugStack,\n trackActualOwner ? createTask(getTaskName(type)) : unknownOwnerDebugTask\n );\n };\n exports.jsxs = function (type, config, maybeKey) {\n var trackActualOwner =\n 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++;\n return jsxDEVImpl(\n type,\n config,\n maybeKey,\n !0,\n trackActualOwner\n ? Error(\"react-stack-top-frame\")\n : unknownOwnerDebugStack,\n trackActualOwner ? createTask(getTaskName(type)) : unknownOwnerDebugTask\n );\n };\n })();\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/react-jsx-runtime.production.js');\n} else {\n module.exports = require('./cjs/react-jsx-runtime.development.js');\n}\n","export const SELECT_COL_WIDTH = 48; // px\n","import React, { useMemo, memo } from \"react\";\nimport { GridColumn, GridRow } from \"../types\";\nimport { SELECT_COL_WIDTH } from \"../constants\";\n\ninterface FooterAggregateProps {\n columns: (GridColumn & { width: number })[];\n data: GridRow[];\n selectable: boolean;\n /** Resolved row height so footer matches density */\n rowHeight: number;\n /** Pinned columns (same semantics as grid body) */\n pinnedColumns?: Set<string>;\n getRowId?: (row: GridRow) => string | number;\n}\n\nconst FooterAggregateComponent: React.FC<FooterAggregateProps> = ({\n columns,\n data,\n selectable,\n rowHeight,\n pinnedColumns = new Set(),\n getRowId,\n}) => {\n const aggregateValues = useMemo(() => {\n const result: Record<string, any> = {};\n\n // Only compute aggregates for columns that have footerAggregate defined\n const columnsWithFooterAgg = columns.filter((col) => col.footerAggregate);\n\n if (columnsWithFooterAgg.length === 0) {\n return result;\n }\n\n columnsWithFooterAgg.forEach((col) => {\n const values = data.map((row) => row[col.key]);\n let aggValue: any = null;\n\n if (typeof col.footerAggregate === \"function\") {\n try {\n aggValue = col.footerAggregate(values);\n } catch (error) {\n console.warn(\n `Error computing custom footer aggregate for column ${col.key}:`,\n error,\n );\n aggValue = null;\n }\n } else {\n const isDateLike = (s: string) => {\n // Common date formats: YYYY-MM-DD, DD-MM-YYYY, with '/' too\n if (/^\\d{4}-\\d{2}-\\d{2}$/.test(s)) return true;\n if (/^\\d{2}-\\d{2}-\\d{4}$/.test(s)) return true;\n if (/^\\d{4}\\/\\d{2}\\/\\d{2}$/.test(s)) return true;\n if (/^\\d{2}\\/\\d{2}\\/\\d{4}$/.test(s)) return true;\n // Fallback: if Date.parse works and the string contains '-' or '/'\n if (\n (s.includes(\"-\") || s.includes(\"/\")) &&\n Number.isFinite(Date.parse(s))\n )\n return true;\n return false;\n };\n\n const nums = values\n .map((v) => {\n if (typeof v === \"number\") return v;\n if (v == null) return NaN;\n const sv = String(v);\n // Prevent treating date-like strings as numbers (e.g., \"2025-01-01\" -> 2025)\n if (isDateLike(sv)) return NaN;\n const n = parseFloat(sv.replace(/,/g, \"\"));\n return Number.isFinite(n) ? n : NaN;\n })\n .filter((n) => Number.isFinite(n)) as number[];\n\n const tryDateNumbers = () => {\n // Convert date-like values to timestamps for min/max\n const dateNums = values\n .map((v) => {\n if (v instanceof Date) return v.getTime();\n if (typeof v === \"string\" || typeof v === \"number\") {\n const t = Date.parse(String(v));\n return Number.isFinite(t) ? t : NaN;\n }\n return NaN;\n })\n .filter((t) => Number.isFinite(t)) as number[];\n return dateNums;\n };\n\n switch (col.footerAggregate) {\n case \"count\":\n aggValue = data.length;\n break;\n case \"sum\":\n if (nums.length) {\n aggValue = nums.reduce((a, b) => a + b, 0);\n }\n break;\n case \"avg\":\n if (nums.length) {\n const sum = nums.reduce((a, b) => a + b, 0);\n aggValue = sum / nums.length;\n }\n break;\n case \"min\":\n if (nums.length) {\n aggValue = Math.min(...nums);\n } else {\n const dateNums = tryDateNumbers();\n if (dateNums.length) {\n aggValue = new Date(Math.min(...dateNums));\n }\n }\n break;\n case \"max\":\n if (nums.length) {\n aggValue = Math.max(...nums);\n } else {\n const dateNums = tryDateNumbers();\n if (dateNums.length) {\n aggValue = new Date(Math.max(...dateNums));\n }\n }\n break;\n default:\n aggValue = null;\n }\n }\n\n if (aggValue !== null && aggValue !== undefined) {\n result[col.key] = aggValue;\n }\n });\n\n return result;\n }, [columns, data]);\n\n // Don't render if no columns have footer aggregates\n const hasFooterAggregates = columns.some((col) => col.footerAggregate);\n if (!hasFooterAggregates) {\n return null;\n }\n\n const totalWidth = columns.reduce((sum, col) => sum + col.width, 0);\n\n // Precompute left offsets for pinned columns (mirrors GridRows logic)\n const leftOffsetByPinnedKey = useMemo(() => {\n const map = new Map<string, number>();\n const pinnedKeysInOrder = columns\n .filter((c) => pinnedColumns.has(c.key))\n .map((c) => c.key);\n let acc = selectable ? SELECT_COL_WIDTH : 0;\n for (const key of pinnedKeysInOrder) {\n map.set(key, acc);\n const w = columns.find((c) => c.key === key)?.width || 100;\n acc += w;\n }\n return map;\n }, [columns, pinnedColumns, selectable]);\n\n return (\n <div\n className=\"flex h-full\"\n style={{\n minWidth: `${totalWidth + (selectable ? SELECT_COL_WIDTH : 0)}px`,\n height: `${rowHeight}px`,\n }}\n >\n {selectable && (\n <div\n key=\"select-footer-cell\"\n className=\"w-12 p-3 border-r border-gray-200 dark:border-gray-700 flex items-center justify-center sticky left-0 bg-white dark:bg-gray-900 z-30\"\n style={{ height: `${rowHeight}px` }}\n >\n <span className=\"text-xs font-medium text-gray-600 dark:text-gray-300\">\n Total\n </span>\n </div>\n )}\n {columns.map((col) => {\n const width = col.width;\n const rawValue = aggregateValues[col.key];\n const hasAggregate = col.footerAggregate && rawValue !== undefined;\n\n // Format value\n let displayValue = \"\";\n if (hasAggregate) {\n const formatter = col.footerAggregateFormatter || col.formatter;\n if (formatter) {\n try {\n displayValue = formatter(rawValue);\n } catch {\n displayValue = String(rawValue);\n }\n } else {\n if (typeof rawValue === \"number\") {\n displayValue =\n rawValue % 1 === 0 ? rawValue.toString() : rawValue.toFixed(2);\n } else {\n displayValue = String(rawValue?.toFixed);\n }\n }\n }\n\n const isPinned = pinnedColumns.has(col.key);\n const leftOffset = isPinned\n ? leftOffsetByPinnedKey.get(col.key) || 0\n : 0;\n const alignClass =\n col.align === \"center\"\n ? \"text-center\"\n : col.align === \"right\"\n ? \"text-right\"\n : \"text-left\";\n const justifyClass =\n col.align === \"center\"\n ? \"justify-center\"\n : col.align === \"right\"\n ? \"justify-end\"\n : \"justify-start\";\n const paddingClass = col.noPadding ? \"p-0\" : \"p-3\";\n\n return (\n <div\n key={col.key}\n className={`border-r border-gray-200 dark:border-gray-700 last:border-r-0 ${paddingClass} text-sm flex items-center font-semibold text-gray-700 dark:text-gray-200 overflow-hidden ${justifyClass} ${alignClass} ${\n isPinned ? \"sticky bg-white dark:bg-gray-900 z-20\" : \"\"\n }`}\n style={{\n width: `${width}px`,\n minWidth: `${width}px`,\n maxWidth: `${width}px`,\n left: isPinned ? `${leftOffset}px` : \"auto\",\n height: `${rowHeight}px`,\n }}\n title={hasAggregate ? `${col.header}: ${displayValue}` : undefined}\n >\n {hasAggregate && (\n <span className=\"truncate w-full\">{displayValue}</span>\n )}\n </div>\n );\n })}\n </div>\n );\n};\n\n// Memoize footer to avoid recomputing aggregates unless relevant inputs change\nexport const FooterAggregate = memo(FooterAggregateComponent, (prev, next) => {\n if (prev.selectable !== next.selectable) return false;\n if (prev.rowHeight !== next.rowHeight) return false;\n if (prev.getRowId !== next.getRowId) return false;\n if (prev.columns.length !== next.columns.length) return false;\n // Compare columns by key + width + aggregate spec reference\n for (let i = 0; i < prev.columns.length; i++) {\n const pc = prev.columns[i];\n const nc = next.columns[i];\n if (\n pc.key !== nc.key ||\n pc.width !== nc.width ||\n pc.footerAggregate !== nc.footerAggregate\n )\n return false;\n }\n // If data length changed or first/last row id changed, recompute\n if (prev.data.length !== next.data.length) return false;\n\n const extractId = (\n row: any,\n idx: number,\n getRowId?: (r: any) => string | number,\n ) => {\n if (getRowId) return getRowId(row);\n if (row.id !== undefined) return row.id;\n return idx;\n };\n\n const prevFirst =\n prev.data.length > 0\n ? extractId(prev.data[0], 0, prev.getRowId)\n : undefined;\n const nextFirst =\n next.data.length > 0\n ? extractId(next.data[0], 0, next.getRowId)\n : undefined;\n const prevLastIdx = prev.data.length - 1;\n const nextLastIdx = next.data.length - 1;\n const prevLast =\n prev.data.length > 0\n ? extractId(prev.data[prevLastIdx], prevLastIdx, prev.getRowId)\n : undefined;\n const nextLast =\n next.data.length > 0\n ? extractId(next.data[nextLastIdx], nextLastIdx, next.getRowId)\n : undefined;\n if (prevFirst !== nextFirst || prevLast !== nextLast) return false;\n if (prev.pinnedColumns?.size !== next.pinnedColumns?.size) return false;\n return true;\n});\n","/**\n * KDGrid Icon Library\n *\n * Hand-crafted inline SVG icons — zero external dependency.\n * Every icon accepts standard SVG props (className, style, etc.)\n * and defaults to currentColor so they inherit text color.\n *\n * All icons are 24×24 viewBox and stroke-based (strokeWidth=2),\n * matching Lucide's visual style exactly.\n */\nimport type { SVGProps } from \"react\";\n\ntype IconProps = SVGProps<SVGSVGElement> & { size?: number };\n\nconst Icon = ({\n size = 16,\n children,\n ...props\n}: IconProps & { children: React.ReactNode }) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n aria-hidden=\"true\"\n focusable=\"false\"\n {...props}\n >\n {children}\n </svg>\n);\n\n/* ─── Navigation ───────────────────────────────────────────────── */\n\nexport const ChevronLeft = (p: IconProps) => (\n <Icon {...p}>\n <polyline points=\"15 18 9 12 15 6\" />\n </Icon>\n);\n\nexport const ChevronRight = (p: IconProps) => (\n <Icon {...p}>\n <polyline points=\"9 18 15 12 9 6\" />\n </Icon>\n);\n\nexport const ChevronDown = (p: IconProps) => (\n <Icon {...p}>\n <polyline points=\"6 9 12 15 18 9\" />\n </Icon>\n);\n\nexport const ChevronsLeft = (p: IconProps) => (\n <Icon {...p}>\n <polyline points=\"11 17 6 12 11 7\" />\n <polyline points=\"18 17 13 12 18 7\" />\n </Icon>\n);\n\nexport const ChevronsRight = (p: IconProps) => (\n <Icon {...p}>\n <polyline points=\"13 17 18 12 13 7\" />\n <polyline points=\"6 17 11 12 6 7\" />\n </Icon>\n);\n\n/* ─── Arrows / Sort ─────────────────────────────────────────────── */\n\nexport const ArrowUp = (p: IconProps) => (\n <Icon {...p}>\n <line x1=\"12\" y1=\"19\" x2=\"12\" y2=\"5\" />\n <polyline points=\"5 12 12 5 19 12\" />\n </Icon>\n);\n\nexport const ArrowDown = (p: IconProps) => (\n <Icon {...p}>\n <line x1=\"12\" y1=\"5\" x2=\"12\" y2=\"19\" />\n <polyline points=\"19 12 12 19 5 12\" />\n </Icon>\n);\n\nexport const ArrowUpDown = (p: IconProps) => (\n <Icon {...p}>\n <path d=\"m21 16-4 4-4-4\" />\n <path d=\"M17 20V4\" />\n <path d=\"m3 8 4-4 4 4\" />\n <path d=\"M7 4v16\" />\n </Icon>\n);\n\n/* ─── Actions ───────────────────────────────────────────────────── */\n\nexport const X = (p: IconProps) => (\n <Icon {...p}>\n <line x1=\"18\" y1=\"6\" x2=\"6\" y2=\"18\" />\n <line x1=\"6\" y1=\"6\" x2=\"18\" y2=\"18\" />\n </Icon>\n);\n\nexport const Check = (p: IconProps) => (\n <Icon {...p}>\n <polyline points=\"20 6 9 17 4 12\" />\n </Icon>\n);\n\nexport const Copy = (p: IconProps) => (\n <Icon {...p}>\n <rect x=\"9\" y=\"9\" width=\"13\" height=\"13\" rx=\"2\" ry=\"2\" />\n <path d=\"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1\" />\n </Icon>\n);\n\nexport const Edit = (p: IconProps) => (\n <Icon {...p}>\n <path d=\"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7\" />\n <path d=\"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z\" />\n </Icon>\n);\n\nexport const Trash2 = (p: IconProps) => (\n <Icon {...p}>\n <polyline points=\"3 6 5 6 21 6\" />\n <path d=\"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6\" />\n <path d=\"M10 11v6\" />\n <path d=\"M14 11v6\" />\n <path d=\"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2\" />\n </Icon>\n);\n\nexport const Archive = (p: IconProps) => (\n <Icon {...p}>\n <polyline points=\"21 8 21 21 3 21 3 8\" />\n <rect x=\"1\" y=\"3\" width=\"22\" height=\"5\" />\n <line x1=\"10\" y1=\"12\" x2=\"14\" y2=\"12\" />\n </Icon>\n);\n\nexport const Download = (p: IconProps) => (\n <Icon {...p}>\n <path d=\"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4\" />\n <polyline points=\"7 10 12 15 17 10\" />\n <line x1=\"12\" y1=\"15\" x2=\"12\" y2=\"3\" />\n </Icon>\n);\n\n/* ─── Column / Grid Controls ────────────────────────────────────── */\n\nexport const Menu = (p: IconProps) => (\n <Icon {...p}>\n <line x1=\"3\" y1=\"12\" x2=\"21\" y2=\"12\" />\n <line x1=\"3\" y1=\"6\" x2=\"21\" y2=\"6\" />\n <line x1=\"3\" y1=\"18\" x2=\"21\" y2=\"18\" />\n </Icon>\n);\n\nexport const Filter = (p: IconProps) => (\n <Icon {...p}>\n <polygon points=\"22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3\" />\n </Icon>\n);\n\nexport const FilterX = (p: IconProps) => (\n <Icon {...p}>\n <path d=\"M13.013 3H2l8 9.46V19l4 2v-6.54l.9-1.055\" />\n <line x1=\"22\" y1=\"3\" x2=\"11\" y2=\"14\" />\n </Icon>\n);\n\nexport const Settings = (p: IconProps) => (\n <Icon {...p}>\n <circle cx=\"12\" cy=\"12\" r=\"3\" />\n <path d=\"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z\" />\n </Icon>\n);\n\nexport const Pin = (p: IconProps) => (\n <Icon {...p}>\n <line x1=\"12\" y1=\"17\" x2=\"12\" y2=\"22\" />\n <path d=\"M5 17h14v-1.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V6h1a2 2 0 0 0 0-4H8a2 2 0 0 0 0 4h1v4.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24Z\" />\n </Icon>\n);\n\nexport const PinOff = (p: IconProps) => (\n <Icon {...p}>\n <line x1=\"2\" y1=\"2\" x2=\"22\" y2=\"22\" />\n <line x1=\"12\" y1=\"17\" x2=\"12\" y2=\"22\" />\n <path d=\"M9 9v1.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V17h12\" />\n <path d=\"M15 9.34V6h1a2 2 0 0 0 0-4H7.89\" />\n </Icon>\n);\n\nexport const Group = (p: IconProps) => (\n <Icon {...p}>\n <path d=\"M3 7V5c0-1.1.9-2 2-2h2\" />\n <path d=\"M17 3h2c1.1 0 2 .9 2 2v2\" />\n <path d=\"M21 17v2c0 1.1-.9 2-2 2h-2\" />\n <path d=\"M7 21H5c-1.1 0-2-.9-2-2v-2\" />\n <rect x=\"7\" y=\"7\" width=\"10\" height=\"10\" rx=\"1\" />\n </Icon>\n);\n\nexport const Ungroup = (p: IconProps) => (\n <Icon {...p}>\n <path d=\"M3 7V5c0-1.1.9-2 2-2h2\" />\n <path d=\"M17 3h2c1.1 0 2 .9 2 2v2\" />\n <path d=\"M21 17v2c0 1.1-.9 2-2 2h-2\" />\n <path d=\"M7 21H5c-1.1 0-2-.9-2-2v-2\" />\n <rect x=\"7\" y=\"7\" width=\"4\" height=\"4\" rx=\"1\" />\n <rect x=\"13\" y=\"13\" width=\"4\" height=\"4\" rx=\"1\" />\n </Icon>\n);\n\nexport const MoreHorizontal = (p: IconProps) => (\n <Icon {...p}>\n <circle cx=\"12\" cy=\"12\" r=\"1\" />\n <circle cx=\"19\" cy=\"12\" r=\"1\" />\n <circle cx=\"5\" cy=\"12\" r=\"1\" />\n </Icon>\n);\n\n/* ─── Visibility ────────────────────────────────────────────────── */\n\nexport const Eye = (p: IconProps) => (\n <Icon {...p}>\n <path d=\"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z\" />\n <circle cx=\"12\" cy=\"12\" r=\"3\" />\n </Icon>\n);\n\nexport const EyeOff = (p: IconProps) => (\n <Icon {...p}>\n <path d=\"M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94\" />\n <path d=\"M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19\" />\n <line x1=\"1\" y1=\"1\" x2=\"23\" y2=\"23\" />\n </Icon>\n);\n\n/* ─── Data / Files ──────────────────────────────────────────────── */\n\nexport const Search = (p: IconProps) => (\n <Icon {...p}>\n <circle cx=\"11\" cy=\"11\" r=\"8\" />\n <line x1=\"21\" y1=\"21\" x2=\"16.65\" y2=\"16.65\" />\n </Icon>\n);\n\nexport const Database = (p: IconProps) => (\n <Icon {...p}>\n <ellipse cx=\"12\" cy=\"5\" rx=\"9\" ry=\"3\" />\n <path d=\"M3 5v14c0 1.66 4.03 3 9 3s9-1.34 9-3V5\" />\n <path d=\"M3 12c0 1.66 4.03 3 9 3s9-1.34 9-3\" />\n </Icon>\n);\n\nexport const FileText = (p: IconProps) => (\n <Icon {...p}>\n <path d=\"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z\" />\n <polyline points=\"14 2 14 8 20 8\" />\n <line x1=\"16\" y1=\"13\" x2=\"8\" y2=\"13\" />\n <line x1=\"16\" y1=\"17\" x2=\"8\" y2=\"17\" />\n <polyline points=\"10 9 9 9 8 9\" />\n </Icon>\n);\n\nexport const Table = (p: IconProps) => (\n <Icon {...p}>\n <rect x=\"3\" y=\"3\" width=\"18\" height=\"18\" rx=\"2\" />\n <path d=\"M3 9h18\" />\n <path d=\"M3 15h18\" />\n <path d=\"M9 3v18\" />\n </Icon>\n);\n\nexport const Users = (p: IconProps) => (\n <Icon {...p}>\n <path d=\"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2\" />\n <circle cx=\"9\" cy=\"7\" r=\"4\" />\n <path d=\"M23 21v-2a4 4 0 0 0-3-3.87\" />\n <path d=\"M16 3.13a4 4 0 0 1 0 7.75\" />\n </Icon>\n);\n\n/* ─── Misc ──────────────────────────────────────────────────────── */\n\nexport const LocateFixed = (p: IconProps) => (\n <Icon {...p}>\n <line x1=\"2\" y1=\"12\" x2=\"6\" y2=\"12\" />\n <line x1=\"18\" y1=\"12\" x2=\"22\" y2=\"12\" />\n <line x1=\"12\" y1=\"2\" x2=\"12\" y2=\"6\" />\n <line x1=\"12\" y1=\"18\" x2=\"12\" y2=\"22\" />\n <circle cx=\"12\" cy=\"12\" r=\"4\" />\n <circle cx=\"12\" cy=\"12\" r=\"1\" fill=\"currentColor\" />\n </Icon>\n);\n\nexport const Loader2 = (p: IconProps) => (\n <Icon {...p}>\n <path d=\"M21 12a9 9 0 1 1-6.219-8.56\" />\n </Icon>\n);\n","import { useState } from \"react\";\nimport { ColumnFilterValue } from \"../../types\";\n\ninterface TextFilterProps {\n value: ColumnFilterValue | null;\n onChange: (value: ColumnFilterValue | null) => void;\n placeholder?: string;\n}\n\nexport const TextFilter = ({\n value,\n onChange,\n placeholder = \"Enter text to filter...\",\n}: TextFilterProps) => {\n const [textValue, setTextValue] = useState<string>(String(value?.value ?? \"\"));\n const [operator, setOperator] = useState<\n \"contains\" | \"equals\" | \"startsWith\" | \"endsWith\"\n >((value?.operator as any) || \"contains\");\n\n const handleTextChange = (newText: string) => {\n setTextValue(newText);\n if (newText.trim()) {\n onChange({\n type: \"text\",\n value: newText,\n operator: operator as any,\n });\n } else {\n onChange(null);\n }\n };\n\n const handleOperatorChange = (newOperator: string) => {\n const op = newOperator as \"contains\" | \"equals\" | \"startsWith\" | \"endsWith\";\n setOperator(op);\n if (textValue.trim()) {\n onChange({\n type: \"text\",\n value: textValue,\n operator: op,\n });\n }\n };\n\n return (\n <div className=\"space-y-3\">\n <div>\n <label className=\"block text-sm font-medium text-gray-700 mb-1\">\n Filter Type\n </label>\n <select\n value={operator}\n onChange={(e) => handleOperatorChange(e.target.value)}\n className=\"w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500\"\n >\n <option value=\"contains\">Contains</option>\n <option value=\"equals\">Equals</option>\n <option value=\"startsWith\">Starts with</option>\n <option value=\"endsWith\">Ends with</option>\n </select>\n </div>\n\n <div>\n <label className=\"block text-sm font-medium text-gray-700 mb-1\">\n Text Value\n </label>\n <input\n type=\"text\"\n value={textValue as string}\n onChange={(e) => handleTextChange(e.target.value)}\n placeholder={placeholder}\n className=\"w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500\"\n />\n </div>\n </div>\n );\n};\n","import { useState } from \"react\";\nimport { ColumnFilterValue } from \"../../types\";\n\ninterface NumberFilterProps {\n value: ColumnFilterValue | null;\n onChange: (value: ColumnFilterValue | null) => void;\n min?: number;\n max?: number;\n}\n\nexport const NumberFilter = ({\n value,\n onChange,\n min,\n max,\n}: NumberFilterProps) => {\n const [numberValue, setNumberValue] = useState<string>(String(value?.value ?? \"\"));\n const [secondValue, setSecondValue] = useState<string>(String(value?.secondValue ?? \"\"));\n const [operator, setOperator] = useState<\n \"equals\" | \"gt\" | \"gte\" | \"lt\" | \"lte\" | \"between\"\n >((value?.operator as any) || \"equals\");\n\n const handleValueChange = (newValue: string, isSecond = false) => {\n if (isSecond) {\n setSecondValue(newValue);\n } else {\n setNumberValue(newValue);\n }\n\n const numValue = parseFloat(newValue);\n const numSecondValue = parseFloat(secondValue);\n\n if (operator === \"between\") {\n if (!isNaN(numValue) && !isNaN(numSecondValue)) {\n onChange({\n type: \"number\",\n value: Math.min(numValue, numSecondValue),\n secondValue: Math.max(numValue, numSecondValue),\n operator: \"between\",\n });\n } else {\n onChange(null);\n }\n } else {\n if (!isNaN(numValue)) {\n onChange({\n type: \"number\",\n value: numValue,\n operator: operator as any,\n });\n } else {\n onChange(null);\n }\n }\n };\n\n const handleOperatorChange = (newOperator: string) => {\n const op = newOperator as\n | \"equals\"\n | \"gt\"\n | \"gte\"\n | \"lt\"\n | \"lte\"\n | \"between\";\n setOperator(op);\n\n if (op === \"between\") {\n const numValue = parseFloat(numberValue);\n const numSecondValue = parseFloat(secondValue);\n if (!isNaN(numValue) && !isNaN(numSecondValue)) {\n onChange({\n type: \"number\",\n value: Math.min(numValue, numSecondValue),\n secondValue: Math.max(numValue, numSecondValue),\n operator: \"between\",\n });\n }\n } else {\n const numValue = parseFloat(numberValue);\n if (!isNaN(numValue)) {\n onChange({\n type: \"number\",\n value: numValue,\n operator: op,\n });\n }\n }\n };\n\n return (\n <div className=\"space-y-3\">\n <div>\n <label className=\"block text-sm font-medium text-gray-700 mb-1\">\n Filter Type\n </label>\n <select\n value={operator}\n onChange={(e) => handleOperatorChange(e.target.value)}\n className=\"w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500\"\n >\n <option value=\"equals\">Equals</option>\n <option value=\"gt\">Greater than</option>\n <option value=\"gte\">Greater than or equal</option>\n <option value=\"lt\">Less than</option>\n <option value=\"lte\">Less than or equal</option>\n <option value=\"between\">Between</option>\n </select>\n </div>\n\n <div>\n <label className=\"block text-sm font-medium text-gray-700 mb-1\">\n {operator === \"between\" ? \"From Value\" : \"Number Value\"}\n </label>\n <input\n type=\"number\"\n value={numberValue as string}\n onChange={(e) => handleValueChange(e.target.value)}\n min={min}\n max={max}\n className=\"w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500\"\n />\n </div>\n\n {operator === \"between\" && (\n <div>\n <label className=\"block text-sm font-medium text-gray-700 mb-1\">\n To Value\n </label>\n <input\n type=\"number\"\n value={secondValue as string}\n onChange={(e) => handleValueChange(e.target.value, true)}\n min={min}\n max={max}\n className=\"w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500\"\n />\n </div>\n )}\n </div>\n );\n};\n","import React from 'react';\n\ninterface DatePickerProps {\n name?: string;\n label?: string;\n value: string | null;\n onChange: (value: string | null) => void;\n className?: string;\n}\n\nexport const DatePicker: React.FC<DatePickerProps> = ({\n name,\n label,\n value,\n onChange,\n className = '',\n}) => {\n return (\n <div className={`space-y-1 ${className}`}>\n {label && (\n <label className=\"text-sm font-medium text-gray-700\">\n {label}\n </label>\n )}\n <input\n type=\"date\"\n name={name}\n value={value || ''}\n onChange={(e) => onChange(e.target.value || null)}\n className=\"w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500\"\n />\n </div>\n );\n};","/**\n * Minimal inline date utilities — replaces the date-fns dependency so\n * consumers don't need to install date-fns to use KDGrid.\n *\n * We only use two operations from date-fns across the entire library:\n * format(date, \"yyyy-MM-dd\") → toYMD(date)\n * parse(str, \"yyyy-MM-dd\", referenceDate) → fromYMD(str)\n *\n * These ~20 lines are far cheaper than shipping a 30 KB peer dependency.\n */\n\n/** Format a Date to \"yyyy-MM-dd\" (ISO date portion only). */\nexport const toYMD = (d: Date): string => {\n const y = d.getFullYear();\n const m = String(d.getMonth() + 1).padStart(2, \"0\");\n const day = String(d.getDate()).padStart(2, \"0\");\n return `${y}-${m}-${day}`;\n};\n\n/** Parse a \"yyyy-MM-dd\" string into a Date (local midnight). Returns Invalid Date on failure. */\nexport const fromYMD = (s: string): Date => {\n // Avoid UTC-shift that `new Date(\"yyyy-MM-dd\")` causes in all browsers.\n const [y, m, d] = s.split(\"-\").map(Number);\n if (!y || !m || !d) return new Date(NaN);\n return new Date(y, m - 1, d);\n};\n\n/** Format a Date to human-readable \"dd-MM-yyyy\" for display. */\nexport const toDMY = (d: Date): string => {\n const day = String(d.getDate()).padStart(2, \"0\");\n const m = String(d.getMonth() + 1).padStart(2, \"0\");\n const y = d.getFullYear();\n return `${day}-${m}-${y}`;\n};\n","import { useState, useEffect, useMemo } from \"react\";\nimport { ColumnFilterValue } from \"../../types\";\nimport { DatePicker } from \"../ui/DatePicker\";\nimport { toYMD, fromYMD } from \"../../utils/dateUtils\";\n\ninterface DateFilterProps {\n value: ColumnFilterValue | null;\n onChange: (value: ColumnFilterValue | null) => void;\n min?: number;\n max?: number;\n}\n\nexport const DateFilter = ({ value, onChange, min, max }: DateFilterProps) => {\n // Local UI state uses Date objects; stored values use \"yyyy-MM-dd\"\n const toDateObj = (v?: string | Date | null): Date | null => {\n if (!v) return null;\n if (v instanceof Date) return isNaN(v.getTime()) ? null : v;\n // Try parse yyyy-MM-dd first\n try {\n const d = fromYMD(String(v));\n return isNaN(d.getTime()) ? null : d;\n } catch (e) {\n const d = new Date(v);\n return isNaN(d.getTime()) ? null : d;\n }\n };\n const toStored = (d: Date | null): string => (d ? toYMD(d) : \"\");\n\n const [dateValue, setDateValue] = useState<Date | null>(\n toDateObj(value?.value as any),\n );\n const [secondDateValue, setSecondDateValue] = useState<Date | null>(\n value?.operator === \"between\"\n ? toDateObj((value?.secondValue as any) ?? (value?.value as any))\n : null,\n );\n const [operator, setOperator] = useState<\n \"equals\" | \"gt\" | \"gte\" | \"lt\" | \"lte\" | \"between\"\n >((value?.operator as any) || \"between\");\n\n // Sync local state when parent value changes (e.g., clear/apply from outside)\n useEffect(() => {\n setOperator((value?.operator as any) || \"between\");\n setDateValue(toDateObj(value?.value as any));\n setSecondDateValue(\n value?.operator === \"between\"\n ? toDateObj((value?.secondValue as any) ?? (value?.value as any))\n : null,\n );\n }, [value?.value, value?.secondValue, value?.operator]);\n\n // Handle operator changes\n useEffect(() => {\n if (operator === \"between\" && !secondDateValue && dateValue) {\n // If switching to between mode and second date is not set, initialize it with first date\n setSecondDateValue(dateValue);\n }\n }, [operator, dateValue, secondDateValue]);\n\n const clampDate = (date: Date | null, minDate?: Date, maxDate?: Date) => {\n if (!date) return null;\n if (minDate && date < minDate) return null;\n if (maxDate && date > maxDate) return null;\n return date;\n };\n\n const handleDateChange = (newDate: Date | null, isSecond = false) => {\n const nextFirst = isSecond ? dateValue : newDate;\n const nextSecond = isSecond ? newDate : secondDateValue;\n\n const maxForFirst =\n operator === \"between\" && secondDateValue ? secondDateValue : maxDateObj;\n const minForSecond = dateValue ?? minDateObj ?? undefined;\n\n const clampedDate = isSecond\n ? clampDate(newDate, minForSecond, maxDateObj)\n : clampDate(newDate, minDateObj, maxForFirst);\n\n if (isSecond) setSecondDateValue(clampedDate);\n else setDateValue(clampedDate);\n\n if (operator === \"between\") {\n if (nextFirst && nextSecond) {\n const start = nextFirst <= nextSecond ? nextFirst : nextSecond;\n const end = nextFirst >= nextSecond ? nextFirst : nextSecond;\n onChange({\n type: \"date\",\n value: toStored(start),\n secondValue: toStored(end),\n operator: \"between\",\n });\n } else {\n onChange(null);\n }\n } else {\n if (clampedDate) {\n onChange({\n type: \"date\",\n value: toStored(clampedDate),\n operator: operator as any,\n });\n } else {\n onChange(null);\n }\n }\n };\n\n const handleOperatorChange = (newOperator: string) => {\n const op = newOperator as\n | \"equals\"\n | \"gt\"\n | \"gte\"\n | \"lt\"\n | \"lte\"\n | \"between\";\n setOperator(op);\n\n if (op === \"between\") {\n if (dateValue && secondDateValue) {\n const start =\n dateValue <= secondDateValue ? dateValue : secondDateValue;\n const end = dateValue >= secondDateValue ? dateValue : secondDateValue;\n onChange({\n type: \"date\",\n value: start,\n secondValue: end,\n operator: \"between\",\n });\n }\n } else {\n if (dateValue) {\n onChange({\n type: \"date\",\n value: dateValue,\n operator: op,\n });\n }\n }\n };\n\n const minDateObj = useMemo(() => (min ? new Date(min) : undefined), [min]);\n const maxDateObj = useMemo(() => (max ? new Date(max) : undefined), [max]);\n\n return (\n <div className=\"space-y-3\">\n <div>\n <label className=\"block text-sm font-medium text-gray-700 mb-1\">\n Filter Type\n </label>\n <select\n value={operator}\n onChange={(e) => handleOperatorChange(e.target.value)}\n className=\"w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500\"\n >\n <option value=\"equals\">On Date</option>\n <option value=\"gt\">After</option>\n <option value=\"gte\">On or After</option>\n <option value=\"lt\">Before</option>\n <option value=\"lte\">On or Before</option>\n <option value=\"between\">Between Dates</option>\n </select>\n </div>\n\n <div>\n <label className=\"block text-sm font-medium text-gray-700 mb-1\">\n {operator === \"between\" ? \"From Date\" : \"Date\"}\n </label>\n <DatePicker\n name=\"date_filter_start\"\n value={dateValue ? toYMD(dateValue) : null}\n onChange={(d) => handleDateChange(d ? fromYMD(d) : null, false)}\n className=\"w-full\"\n />\n </div>\n\n {operator === \"between\" && (\n <div>\n <label className=\"block text-sm font-medium text-gray-700 mb-1\">\n To Date\n </label>\n <DatePicker\n name=\"date_filter_end\"\n value={secondDateValue ? toYMD(secondDateValue) : null}\n onChange={(d) => handleDateChange(d ? fromYMD(d) : null, true)}\n className=\"w-full\"\n />\n </div>\n )}\n </div>\n );\n};\n","import { useState, useMemo, useEffect } from \"react\";\nimport { Search, Check } from \"../../icons\";\nimport { ColumnFilterValue, FilterOption, GridRow } from \"../../types\";\n\ninterface MultiselectFilterProps {\n value: ColumnFilterValue | null;\n onChange: (value: ColumnFilterValue | null) => void;\n options?: FilterOption[];\n data: GridRow[];\n columnKey: string;\n}\n\nexport const MultiselectFilter = ({\n value,\n onChange,\n options,\n data,\n columnKey,\n}: MultiselectFilterProps) => {\n const [searchText, setSearchText] = useState(\"\");\n const [selectedValues, setSelectedValues] = useState<Set<any>>(\n new Set(Array.isArray(value?.value) ? value.value : []),\n );\n\n // Sync selectedValues when value prop changes\n useEffect(() => {\n setSelectedValues(new Set(Array.isArray(value?.value) ? value.value : []));\n }, [value]);\n\n // Generate options from data if not provided\n const availableOptions = useMemo(() => {\n let opts: FilterOption[] = [];\n\n // Helper to check if a value is blank\n const isBlankValue = (val: any): boolean => {\n return (\n val === null ||\n val === undefined ||\n val === \"\" ||\n (typeof val === \"string\" && val.trim() === \"\")\n );\n };\n\n if (options && options.length > 0) {\n opts = options;\n } else {\n // Normalize blank values to null and collect unique values\n const normalizedValues = data.map((row) => {\n const val = row[columnKey];\n return isBlankValue(val) ? null : val;\n });\n\n const uniqueValues = [...new Set(normalizedValues)];\n\n opts = uniqueValues.map((val) => ({\n label: val === null ? \"Blank\" : String(val),\n value: val,\n }));\n }\n\n // Transform blank/null/empty values to display as \"Blank\"\n // and sort them to the end of the list\n const processedOptions = opts.map((opt) => {\n const isBlank = isBlankValue(opt.value);\n\n return {\n ...opt,\n label: isBlank ? \"Blank\" : opt.label,\n value: isBlank ? null : opt.value, // Normalize all blank values to null\n isBlank,\n };\n });\n\n // Remove duplicates after normalization (in case options had multiple blank types)\n const uniqueProcessed = Array.from(\n new Map(\n processedOptions.map((opt) => [\n opt.isBlank ? \"__blank__\" : opt.value,\n opt,\n ]),\n ).values(),\n );\n\n // Sort: non-blank items first (alphabetically), then blank items at the end\n return uniqueProcessed.sort((a, b) => {\n if (a.isBlank && !b.isBlank) return 1;\n if (!a.isBlank && b.isBlank) return -1;\n return String(a.label).localeCompare(String(b.label));\n });\n }, [options, data, columnKey]);\n\n // Filter options based on search\n const filteredOptions = useMemo(() => {\n if (!searchText) return availableOptions;\n const searchLower = searchText.toLowerCase();\n return availableOptions.filter(\n (option) =>\n option.label.toLowerCase().includes(searchLower) ||\n String(option.value).toLowerCase().includes(searchLower) ||\n (searchLower === \"blank\" && (option as any).isBlank),\n );\n }, [availableOptions, searchText]);\n\n const handleToggleValue = (optionValue: any) => {\n const newSelected = new Set(selectedValues);\n\n if (newSelected.has(optionValue)) {\n newSelected.delete(optionValue);\n } else {\n newSelected.add(optionValue);\n }\n\n setSelectedValues(newSelected);\n\n // Update the temp filter state but don't apply immediately\n if (newSelected.size > 0) {\n onChange({\n type: \"multiselect\",\n value: Array.from(newSelected) as any,\n operator: \"equals\",\n });\n } else {\n onChange(null);\n }\n };\n\n const handleSelectAll = () => {\n const allValues = new Set(filteredOptions.map((opt) => opt.value));\n setSelectedValues(allValues);\n onChange({\n type: \"multiselect\",\n value: Array.from(allValues) as any,\n operator: \"equals\",\n });\n };\n\n const handleClearAll = () => {\n setSelectedValues(new Set());\n onChange(null);\n };\n\n return (\n <div className=\"space-y-3\">\n {/* Search */}\n <div className=\"relative\">\n <Search className=\"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4\" />\n <input\n type=\"text\"\n value={searchText}\n onChange={(e) => setSearchText(e.target.value)}\n placeholder=\"Search options...\"\n className=\"w-full pl-10 pr-4 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500\"\n />\n </div>\n\n {/* Actions */}\n <div className=\"flex justify-between items-center text-sm\">\n <span className=\"text-gray-600\">\n {selectedValues.size} of {availableOptions.length} selected\n </span>\n <div className=\"flex gap-2\">\n <button\n onClick={handleSelectAll}\n className=\"text-blue-600 hover:text-blue-800 transition-colors\"\n >\n Select All\n </button>\n <button\n onClick={handleClearAll}\n className=\"text-gray-600 hover:text-gray-800 transition-colors\"\n >\n Clear All\n </button>\n </div>\n </div>\n\n {/* Options List */}\n <div className=\"max-h-48 overflow-y-auto border border-gray-200 rounded-md\">\n {filteredOptions.length === 0 ? (\n <div className=\"p-3 text-sm text-gray-500 text-center\">\n No options found\n </div>\n ) : (\n filteredOptions.map((option, index) => {\n const isSelected = selectedValues.has(option.value);\n return (\n <div\n key={index}\n onClick={() => handleToggleValue(option.value)}\n className={`flex items-center gap-3 p-2 cursor-pointer hover:bg-gray-50 transition-colors ${\n isSelected ? \"bg-blue-50\" : \"\"\n }`}\n >\n <div\n className={`w-4 h-4 border-2 rounded flex items-center justify-center ${\n isSelected\n ? \"bg-blue-600 border-blue-600 text-white\"\n : \"border-gray-300\"\n }`}\n >\n {isSelected && <Check className=\"w-3 h-3\" />}\n </div>\n <span\n className={`text-sm ${\n isSelected ? \"text-blue-900 font-medium\" : \"text-gray-700\"\n } ${(option as any).isBlank ? \"italic text-gray-500\" : \"\"}`}\n >\n {option.label}\n </span>\n </div>\n );\n })\n )}\n </div>\n </div>\n );\n};\n","import { useState } from \"react\";\nimport { ColumnFilterValue } from \"../../types\";\n\ninterface BooleanFilterProps {\n value: ColumnFilterValue | null;\n onChange: (value: ColumnFilterValue | null) => void;\n}\n\nexport const BooleanFilter = ({ value, onChange }: BooleanFilterProps) => {\n const [booleanValue, setBooleanValue] = useState<string>(\n value?.value !== undefined ? String(value.value) : \"\"\n );\n\n const handleValueChange = (newValue: string) => {\n setBooleanValue(newValue);\n\n if (newValue === \"\") {\n onChange(null);\n } else {\n onChange({\n type: \"boolean\",\n value: newValue === \"true\",\n operator: \"equals\",\n });\n }\n };\n\n return (\n <div className=\"space-y-3\">\n <div>\n <label className=\"block text-sm font-medium text-gray-700 mb-1\">\n Boolean Value\n </label>\n <select\n value={booleanValue}\n onChange={(e) => handleValueChange(e.target.value)}\n className=\"w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500\"\n >\n <option value=\"\">All values</option>\n <option value=\"true\">True</option>\n <option value=\"false\">False</option>\n </select>\n </div>\n </div>\n );\n};\n","import { useMemo } from \"react\";\nimport { ColumnFilterValue, ColumnFilter, GridColumn, GridRow } from \"../../types\";\nimport { TextFilter } from \"./TextFilter\";\nimport { NumberFilter } from \"./NumberFilter\";\nimport { DateFilter } from \"./DateFilter\";\nimport { MultiselectFilter } from \"./MultiselectFilter\";\nimport { BooleanFilter } from \"./BooleanFilter\";\n\ninterface FilterContentProps {\n column: GridColumn;\n data: GridRow[];\n value: ColumnFilterValue | null;\n onChange: (val: ColumnFilterValue | null) => void;\n}\n\nexport const FilterContent = ({ column, data, value, onChange }: FilterContentProps) => {\n const filterConfig: ColumnFilter = useMemo(() => {\n if (typeof column.filterable === \"object\") return column.filterable;\n\n // Auto-detect filter type based on data\n const sampleValues = data\n .slice(0, 100)\n .map((row) => row[column.key])\n .filter((val) => val != null);\n\n if (sampleValues.length === 0) return { type: \"text\" };\n\n const firstValue = sampleValues[0];\n if (typeof firstValue === \"boolean\") return { type: \"boolean\" };\n if (typeof firstValue === \"number\") return { type: \"number\" };\n if (\n firstValue instanceof Date ||\n (typeof firstValue === \"string\" && !isNaN(Date.parse(firstValue)))\n ) {\n return { type: \"date\" };\n }\n\n const uniqueValues = [...new Set(sampleValues)];\n if (uniqueValues.length <= 20) {\n return {\n type: \"multiselect\",\n options: uniqueValues.map((val) => ({ label: String(val), value: val })),\n };\n }\n\n return { type: \"text\" };\n }, [column.filterable, column.key, data]);\n\n switch (filterConfig.type) {\n case \"text\":\n return (\n <TextFilter value={value} onChange={onChange} placeholder={filterConfig.placeholder} />\n );\n case \"number\":\n return (\n <NumberFilter value={value} onChange={onChange} min={filterConfig.min} max={filterConfig.max} />\n );\n case \"date\":\n return (\n <DateFilter value={value} onChange={onChange} min={filterConfig.min} max={filterConfig.max} />\n );\n case \"multiselect\":\n return (\n <MultiselectFilter\n value={value}\n onChange={onChange}\n options={filterConfig.options || []}\n data={data}\n columnKey={column.key}\n />\n );\n case \"boolean\":\n return <BooleanFilter value={value} onChange={onChange} />;\n default:\n return null;\n }\n};\n","import React, { memo, useEffect, useState } from \"react\";\nimport type { MouseEvent as ReactMouseEvent } from \"react\";\nimport {\n Filter,\n FilterX,\n Menu,\n Pin,\n PinOff,\n Group,\n Ungroup,\n ArrowUp,\n ArrowDown,\n ArrowUpDown,\n} from \"../icons\";\nimport {\n GridColumn,\n SortConfig,\n ActiveFilters,\n ColumnFilterValue,\n GridRow,\n} from \"../types\";\nimport { SELECT_COL_WIDTH } from \"../constants\";\nimport { FilterContent } from \"./filters/FilterContent\";\n\ninterface GridHeaderProps {\n pinnedColumns: GridColumn[];\n unpinnedColumns: GridColumn[];\n hvPadLeft?: number;\n hvPadRight?: number;\n // Fixed header height in px (use density-controlled row height)\n headerHeight: number;\n sortConfig: SortConfig;\n columnFilters: ActiveFilters;\n selectable: boolean;\n selectedRows: Set<string | number>;\n totalRows: number;\n data: GridRow[];\n onSort: (key: string) => void;\n onColumnFilter: (key: string, filter: ColumnFilterValue | null) => void;\n onSelectAll: () => void;\n onColumnResize?: (columnKey: string, width: number) => void;\n pinnedKeySet?: Set<string>;\n onColumnPin?: (columnKey: string, pinned: boolean) => void;\n groupable?: boolean;\n // Back-compat single grouped column\n groupedByColumn?: string | null;\n onGroupBy?: (columnKey: string | null) => void;\n // New multi-group API\n groupedByColumns?: string[];\n onGroupToggle?: (columnKey: string, nextGrouped: boolean) => void;\n onAutosizeColumn?: (columnKey: string) => void;\n onAutosizeAllColumns?: () => void;\n onResetColumns?: () => void;\n // Reorder props\n columnOrder: string[];\n onColumnOrderChange: (order: string[]) => void;\n // Pagination mode for auto-apply filtering\n paginationMode?: \"client\" | \"server\" | null;\n}\n\nconst GridHeaderComponent = ({\n pinnedColumns,\n unpinnedColumns,\n hvPadLeft = 0,\n hvPadRight = 0,\n headerHeight,\n sortConfig,\n columnFilters,\n selectable,\n selectedRows,\n totalRows,\n data,\n onSort,\n onColumnFilter,\n onSelectAll,\n onColumnResize,\n pinnedKeySet = new Set<string>(),\n onColumnPin,\n groupable = false,\n groupedByColumn,\n onGroupBy,\n groupedByColumns = [],\n onGroupToggle,\n onAutosizeColumn,\n onAutosizeAllColumns,\n onResetColumns,\n columnOrder,\n onColumnOrderChange,\n paginationMode = \"client\",\n}: GridHeaderProps) => {\n // Memoize so that re-renders don't allocate a new array every cycle\n const allColumns = React.useMemo(\n () => [...pinnedColumns, ...unpinnedColumns],\n [pinnedColumns, unpinnedColumns],\n );\n const [activeColumnMenu, setActiveColumnMenu] = useState<string | null>(null);\n const [menuPosition, setMenuPosition] = useState<{\n top: number;\n left: number;\n containerRect: DOMRect;\n } | null>(null);\n const [isResizing, setIsResizing] = useState<string | null>(null);\n const [startX, setStartX] = useState<number>(0);\n const [startWidth, setStartWidth] = useState<number>(0);\n const [activeTab, setActiveTab] = useState<\"menu\" | \"filter\" | \"reorder\">(\n \"menu\",\n );\n const [tempFilter, setTempFilter] = useState<ColumnFilterValue | null>(null);\n const [isTouchDevice, setIsTouchDevice] = useState(false);\n\n useEffect(() => {\n setIsTouchDevice(\n \"ontouchstart\" in window ||\n navigator.maxTouchPoints > 0 ||\n window.matchMedia(\"(pointer: coarse)\").matches,\n );\n }, []);\n\n // Reorder-in-menu state\n const [menuReorderDraggingKey, setMenuReorderDraggingKey] = useState<\n string | null\n >(null);\n const [menuReorderDragOver, setMenuReorderDragOver] = useState<{\n key: string;\n position: \"before\" | \"after\";\n } | null>(null);\n\n const isAllSelected = selectedRows.size === totalRows && totalRows > 0;\n const isIndeterminate =\n selectedRows.size > 0 && selectedRows.size < totalRows;\n\n const handleColumnMenuClick = (\n columnKey: string,\n event: ReactMouseEvent<HTMLButtonElement>,\n ) => {\n event.stopPropagation();\n if (activeColumnMenu === columnKey) {\n setActiveColumnMenu(null);\n } else {\n setActiveColumnMenu(columnKey);\n setActiveTab(\"menu\");\n setTempFilter(columnFilters[columnKey] || null);\n\n // Store button position and clamp to grid container bounds\n const rect = event.currentTarget.getBoundingClientRect();\n // Find the nearest grid container for boundary clamping\n const containerEl = event.currentTarget.closest(\n \"[data-grid-container]\",\n ) as HTMLElement | null;\n const containerRect = containerEl\n ? containerEl.getBoundingClientRect()\n : new DOMRect(0, 0, window.innerWidth, window.innerHeight);\n\n const MENU_WIDTH = 320; // matches dropdown width below\n const PADDING = 10;\n\n // Clamp left so the menu stays inside the grid container horizontally\n const minLeft = containerRect.left + PADDING;\n const maxLeft = containerRect.right - MENU_WIDTH - PADDING;\n const clampedLeft = Math.max(minLeft, Math.min(rect.left, maxLeft));\n\n setMenuPosition({\n top: rect.bottom + 4,\n left: clampedLeft,\n containerRect,\n });\n }\n };\n\n const handleApplyFilter = (columnKey: string) => {\n onColumnFilter(columnKey, tempFilter || null);\n setActiveColumnMenu(null);\n };\n\n const hasActiveFilter = (columnKey: string) => {\n return columnFilters[columnKey] != null;\n };\n\n const handleResizeStart = (columnKey: string, event: ReactMouseEvent) => {\n event.preventDefault();\n setIsResizing(columnKey);\n setStartX(event.clientX);\n const column = [...pinnedColumns, ...unpinnedColumns].find(\n (col) => col.key === columnKey,\n );\n setStartWidth(column?.width || 100);\n };\n\n const handleResizeMove = (event: globalThis.MouseEvent) => {\n if (!isResizing || !onColumnResize) return;\n\n const deltaX = event.clientX - startX;\n const newWidth = Math.max(50, startWidth + deltaX); // Minimum width of 50px\n onColumnResize(isResizing, newWidth);\n };\n\n const handleResizeEnd = () => {\n setIsResizing(null);\n setStartX(0);\n setStartWidth(0);\n };\n\n // Drag & Drop state for reordering\n const [draggingKey, setDraggingKey] = useState<string | null>(null);\n const [dragOver, setDragOver] = useState<{\n key: string;\n position: \"before\" | \"after\";\n } | null>(null);\n\n // (no-op helper removed; ordering is computed inline in handleDrop)\n\n const handleDragStart = (\n columnKey: string,\n e: React.DragEvent<HTMLDivElement>,\n ) => {\n setDraggingKey(columnKey);\n e.dataTransfer.effectAllowed = \"move\";\n e.dataTransfer.setData(\"text/plain\", columnKey);\n };\n\n const handleDragOver = (\n targetKey: string,\n e: React.DragEvent<HTMLDivElement>,\n ) => {\n // Allow drop\n e.preventDefault();\n e.dataTransfer.dropEffect = \"move\";\n const rect = (e.currentTarget as HTMLDivElement).getBoundingClientRect();\n const midpoint = rect.left + rect.width / 2;\n const position = e.clientX < midpoint ? \"before\" : \"after\";\n setDragOver({ key: targetKey, position });\n };\n\n const handleDrop = (targetKey: string) => {\n const sourceKey = draggingKey;\n if (!sourceKey || sourceKey === targetKey) return;\n\n // Prevent cross pinned/unpinned moves for clearer UX\n const sourcePinned = pinnedKeySet.has(sourceKey);\n const targetPinned = pinnedKeySet.has(targetKey);\n if (sourcePinned !== targetPinned) {\n setDraggingKey(null);\n setDragOver(null);\n return;\n }\n\n const before =\n dragOver?.key === targetKey ? dragOver?.position === \"before\" : true;\n const base = columnOrder.filter((k) => k !== sourceKey);\n let idx = base.indexOf(targetKey);\n if (idx === -1) {\n onColumnOrderChange(base);\n setDraggingKey(null);\n setDragOver(null);\n return;\n }\n if (!before) idx += 1;\n base.splice(idx, 0, sourceKey);\n const next = base;\n onColumnOrderChange(next);\n setDraggingKey(null);\n setDragOver(null);\n };\n\n const handleDragEnd = () => {\n setDraggingKey(null);\n setDragOver(null);\n };\n\n // --- Reorder handlers for the popup list ---\n const handleMenuReorderDragStart = (\n columnKey: string,\n e: React.DragEvent<HTMLDivElement>,\n ) => {\n setMenuReorderDraggingKey(columnKey);\n e.dataTransfer.effectAllowed = \"move\";\n e.dataTransfer.setData(\"text/plain\", columnKey);\n };\n\n const handleMenuReorderDragOver = (\n targetKey: string,\n e: React.DragEvent<HTMLDivElement>,\n ) => {\n e.preventDefault();\n e.dataTransfer.dropEffect = \"move\";\n const rect = (e.currentTarget as HTMLDivElement).getBoundingClientRect();\n const midpoint = rect.top + rect.height / 2;\n const position = e.clientY < midpoint ? \"before\" : \"after\";\n setMenuReorderDragOver({ key: targetKey, position });\n };\n\n const handleMenuReorderDrop = (targetKey: string) => {\n const sourceKey = menuReorderDraggingKey;\n if (!sourceKey || sourceKey === targetKey) return;\n\n // Prevent cross pinned/unpinned moves\n const sourcePinned = pinnedKeySet.has(sourceKey);\n const targetPinned = pinnedKeySet.has(targetKey);\n if (sourcePinned !== targetPinned) {\n setMenuReorderDraggingKey(null);\n setMenuReorderDragOver(null);\n return;\n }\n\n const before =\n menuReorderDragOver?.key === targetKey\n ? menuReorderDragOver?.position === \"before\"\n : true;\n const base = columnOrder.filter((k) => k !== sourceKey);\n let idx = base.indexOf(targetKey);\n if (idx === -1) {\n onColumnOrderChange(base);\n setMenuReorderDraggingKey(null);\n setMenuReorderDragOver(null);\n return;\n }\n if (!before) idx += 1;\n base.splice(idx, 0, sourceKey);\n onColumnOrderChange(base);\n setMenuReorderDraggingKey(null);\n setMenuReorderDragOver(null);\n };\n\n const handleMenuReorderDragEnd = () => {\n setMenuReorderDraggingKey(null);\n setMenuReorderDragOver(null);\n };\n\n // Add global mouse event listeners for resizing\n useEffect(() => {\n if (isResizing) {\n document.addEventListener(\"mousemove\", handleResizeMove);\n document.addEventListener(\"mouseup\", handleResizeEnd);\n document.body.style.cursor = \"col-resize\";\n document.body.style.userSelect = \"none\";\n\n return () => {\n document.removeEventListener(\"mousemove\", handleResizeMove);\n document.removeEventListener(\"mouseup\", handleResizeEnd);\n document.body.style.cursor = \"\";\n document.body.style.userSelect = \"\";\n };\n }\n }, [isResizing, startX, startWidth, onColumnResize]);\n\n // Close menu on outside click\n useEffect(() => {\n const handleClickOutside = (event: MouseEvent) => {\n const target = event.target as Element;\n if (activeColumnMenu && !target.closest(\"[data-column-menu]\")) {\n setActiveColumnMenu(null);\n }\n };\n\n if (activeColumnMenu) {\n document.addEventListener(\"mousedown\", handleClickOutside);\n return () =>\n document.removeEventListener(\"mousedown\", handleClickOutside);\n }\n }, [activeColumnMenu]);\n\n return (\n <>\n <div\n className=\"bg-blue-50 dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700\"\n style={{ height: headerHeight }}\n role=\"row\"\n aria-label=\"Column headers\"\n >\n <div className=\"flex h-full\">\n {selectable && (\n <div\n className=\"px-3 border-r border-gray-200 dark:border-gray-700 flex items-center justify-center bg-blue-50 dark:bg-gray-800 sticky left-0 z-3 h-full\"\n style={{ width: SELECT_COL_WIDTH, height: headerHeight }}\n role=\"columnheader\"\n aria-label=\"Select all rows\"\n >\n <input\n type=\"checkbox\"\n checked={isAllSelected}\n ref={(el) => {\n if (el) el.indeterminate = isIndeterminate;\n }}\n onChange={onSelectAll}\n onKeyDown={(e) => {\n if (e.key === \" \" || e.key === \"Enter\") {\n e.preventDefault();\n onSelectAll();\n }\n }}\n className=\"rounded border-gray-300 dark:border-gray-600 text-blue-600 cursor-pointer disabled:cursor-not-allowed disabled:opacity-50 h-4 w-4 transition-all duration-150\"\n aria-label={\n isAllSelected\n ? \"Deselect all rows\"\n : isIndeterminate\n ? `${selectedRows.size} rows selected. Click to select all`\n : \"Select all rows\"\n }\n title={\n isAllSelected\n ? `Deselect all ${totalRows} rows`\n : isIndeterminate\n ? `${selectedRows.size} of ${totalRows} rows selected`\n : `Select all ${totalRows} rows`\n }\n />\n </div>\n )}\n\n {/* Pinned columns */}\n {pinnedColumns.map((column, index) => {\n const isPinned = pinnedKeySet.has(column.key);\n const pinnedKeysInOrder = pinnedColumns\n .filter((c) => pinnedKeySet.has(c.key))\n .map((c) => c.key);\n const pinnedIndex = pinnedKeysInOrder.indexOf(column.key);\n const leftOffset = isPinned\n ? pinnedKeysInOrder.slice(0, pinnedIndex).reduce(\n (sum, key) => {\n const col = pinnedColumns.find((c) => c.key === key);\n return sum + (col?.width || 100);\n },\n selectable ? SELECT_COL_WIDTH : 0,\n )\n : 0;\n\n const headerJustify =\n column.headerAlign === \"center\"\n ? \"justify-center\"\n : column.headerAlign === \"right\"\n ? \"justify-end\"\n : \"justify-start\";\n\n // Determine effective sortable (default true unless explicitly false)\n const colSortable = column.sortable !== false;\n return (\n <div\n key={column.key + index}\n className={`flex-none border-r border-gray-200 dark:border-gray-700 last:border-r-0 relative ${\n isPinned\n ? \"bg-blue-50 dark:bg-blue-900/20 border-blue-200 dark:border-blue-700 sticky z-2\"\n : \"\"\n } `}\n style={{\n width: column.width || 100,\n left: isPinned ? `${leftOffset}px` : \"auto\",\n height: headerHeight,\n }}\n data-column-key={column.key}\n draggable\n onDragStart={(e) => handleDragStart(column.key, e)}\n onDragOver={(e) => handleDragOver(column.key, e)}\n onDrop={() => handleDrop(column.key)}\n onDragEnd={handleDragEnd}\n >\n {/* Drop indicator */}\n {dragOver?.key === column.key && (\n <div\n className=\"absolute top-0 bottom-0 w-0.5 bg-blue-600 z-4\"\n style={{\n left: dragOver?.position === \"before\" ? 0 : undefined,\n right: dragOver?.position === \"after\" ? 0 : undefined,\n }}\n />\n )}\n <div className=\"px-3 h-full\">\n {/* Header with sort */}\n <div className=\"flex items-center justify-between gap-1 group h-full\">\n <div\n className={`flex items-center min-w-0 flex-1 ${headerJustify} ${\n colSortable ? \"cursor-pointer hover:text-blue-600\" : \"\"\n }`}\n onClick={() => colSortable && onSort(column.key)}\n >\n <div className=\"flex items-center gap-2 min-w-0\">\n {/* Filter indicator */}\n {hasActiveFilter(column.key) && (\n <div\n className=\"w-2 h-2 bg-red-500 rounded-full shrink-0\"\n title=\"Filter applied\"\n />\n )}\n <span className=\"font-medium text-gray-900 dark:text-gray-100 text-sm truncate min-w-0\">\n {column.header}\n </span>\n </div>\n {colSortable && sortConfig.key === column.key && (\n <div className=\"ml-1 shrink-0 pointer-events-none select-none\">\n {sortConfig.direction === \"asc\" ? (\n <ArrowUp className=\"w-3 h-3 text-blue-600 dark:text-blue-400\" />\n ) : (\n <ArrowDown className=\"w-3 h-3 text-blue-600 dark:text-blue-400\" />\n )}\n </div>\n )}\n </div>\n\n {/* Three-dot menu */}\n {(column.filterable || onColumnPin || groupable) && (\n <div\n className={`relative ${\n activeColumnMenu === column.key || isTouchDevice\n ? \"block\"\n : \"hidden group-hover:block\"\n }`}\n data-column-menu\n >\n <button\n className=\"p-1 hover:bg-gray-200 dark:hover:bg-gray-700 rounded shrink-0\"\n onClick={(e) => handleColumnMenuClick(column.key, e)}\n data-menu-trigger\n >\n <Menu className=\"w-4 h-4 text-gray-500 dark:text-gray-400\" />\n </button>\n\n {/* Dropdown Menu with Tabs */}\n {activeColumnMenu === column.key && menuPosition && (\n <div\n className=\"fixed bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-md shadow-lg z-1000 w-[320px] overflow-auto\"\n style={{\n top: `${menuPosition.top}px`,\n left: `${menuPosition.left}px`,\n // Ensure the menu height never exceeds available space within the grid container\n maxHeight: `${Math.max(\n 160,\n menuPosition.containerRect.bottom -\n 12 -\n menuPosition.top,\n )}px`,\n }}\n data-column-menu\n >\n {/* Tabs */}\n <div className=\"flex items-center border-b border-gray-200 dark:border-gray-700\">\n <button\n className={`px-3 py-2 text-sm flex items-center gap-2 ${\n activeTab === \"menu\"\n ? \"border-b-2 border-blue-600 text-blue-600\"\n : \"text-gray-600\"\n }`}\n onClick={() => setActiveTab(\"menu\")}\n >\n <Menu className=\"w-4 h-4\" />\n </button>\n {column.filterable && (\n <button\n className={`px-3 py-2 text-sm flex items-center gap-2 ${\n activeTab === \"filter\"\n ? \"border-b-2 border-blue-600 text-blue-600\"\n : \"text-gray-600\"\n }`}\n onClick={() => setActiveTab(\"filter\")}\n >\n <Filter className=\"w-4 h-4\" />\n </button>\n )}\n <button\n className={`px-3 py-2 text-sm flex items-center gap-2 ${\n activeTab === \"reorder\"\n ? \"border-b-2 border-blue-600 text-blue-600\"\n : \"text-gray-600\"\n }`}\n onClick={() => setActiveTab(\"reorder\")}\n >\n <ArrowUpDown className=\"w-4 h-4\" />\n </button>\n </div>\n {/* Tab Content */}\n {activeTab === \"menu\" && (\n <div className=\"py-1\">\n {onColumnPin &&\n (groupedByColumn === column.key ? (\n <div className=\"w-full px-3 py-2 text-left text-sm flex items-center gap-2 text-blue-600\">\n <Pin className=\"w-4 h-4\" />\n Pinned by grouping\n </div>\n ) : (\n <button\n className=\"w-full px-3 py-2 text-left text-sm hover:bg-gray-50 flex items-center gap-2\"\n onClick={(e) => {\n e.stopPropagation();\n setActiveColumnMenu(null);\n onColumnPin?.(\n column.key,\n !pinnedKeySet.has(column.key),\n );\n }}\n >\n {pinnedKeySet.has(column.key) ? (\n <>\n <PinOff className=\"w-4 h-4\" />\n Unpin Column\n </>\n ) : (\n <>\n <Pin className=\"w-4 h-4\" />\n Pin Column\n </>\n )}\n </button>\n ))}\n\n {onAutosizeColumn && (\n <button\n className=\"w-full px-3 py-2 text-left text-sm hover:bg-gray-50\"\n onClick={() => {\n onAutosizeColumn?.(column.key);\n setActiveColumnMenu(null);\n }}\n >\n Autosize This Column\n </button>\n )}\n {onAutosizeAllColumns && (\n <button\n className=\"w-full px-3 py-2 text-left text-sm hover:bg-gray-50\"\n onClick={() => {\n onAutosizeAllColumns?.();\n setActiveColumnMenu(null);\n }}\n >\n Autosize All Columns\n </button>\n )}\n\n {groupable && (\n <button\n className=\"w-full px-3 py-2 text-left text-sm hover:bg-gray-50 flex items-center gap-2\"\n onClick={(e) => {\n e.stopPropagation();\n setActiveColumnMenu(null);\n const isGrouped =\n groupedByColumns?.includes(\n column.key,\n ) || groupedByColumn === column.key;\n if (onGroupToggle)\n onGroupToggle(column.key, !isGrouped);\n else\n onGroupBy?.(\n isGrouped ? null : column.key,\n );\n }}\n >\n {groupedByColumn === column.key ||\n groupedByColumns?.includes(column.key) ? (\n <>\n <Ungroup className=\"w-4 h-4\" />\n Ungroup\n </>\n ) : (\n <>\n <Group className=\"w-4 h-4\" />\n Group by {column.header}\n </>\n )}\n </button>\n )}\n\n {onResetColumns && (\n <button\n className=\"w-full px-3 py-2 text-left text-sm hover:bg-gray-50\"\n onClick={() => {\n onResetColumns?.();\n setActiveColumnMenu(null);\n }}\n >\n Reset Columns\n </button>\n )}\n </div>\n )}\n {activeTab === \"filter\" && (\n <div className=\"p-3 w-full\">\n {/* Filter Tab */}\n {hasActiveFilter(column.key) && (\n <button\n className=\"mb-2 text-xs text-red-600 hover:underline flex items-center gap-1\"\n onClick={() => {\n setTempFilter(null);\n onColumnFilter(column.key, null);\n setActiveColumnMenu(null);\n }}\n >\n <FilterX className=\"w-3 h-3\" /> Clear Filter\n </button>\n )}\n <div className=\"max-h-75 overflow-auto pr-1\">\n <FilterContent\n column={column}\n data={data}\n value={tempFilter}\n onChange={(val) => {\n setTempFilter(val);\n // Auto-apply for client-side or no pagination\n if (paginationMode !== \"server\") {\n onColumnFilter(column.key, val);\n }\n }}\n />\n </div>\n {paginationMode === \"server\" ? (\n <div className=\"flex justify-end gap-2 mt-3\">\n <button\n className=\"px-3 py-1.5 text-sm bg-gray-100 text-gray-700 rounded-md hover:bg-gray-200\"\n onClick={() => setActiveColumnMenu(null)}\n >\n Cancel\n </button>\n <button\n className=\"px-3 py-1.5 text-sm bg-blue-600 text-white rounded-md hover:bg-blue-700\"\n onClick={() =>\n handleApplyFilter(column.key)\n }\n >\n Apply\n </button>\n </div>\n ) : (\n <div className=\"flex justify-end mt-3\">\n <button\n className=\"px-3 py-1.5 text-sm bg-blue-600 text-white rounded-md hover:bg-blue-700\"\n onClick={() => setActiveColumnMenu(null)}\n >\n Close\n </button>\n </div>\n )}\n </div>\n )}\n {activeTab === \"reorder\" && (\n <div className=\"px-3 py-2\">\n <div className=\"text-xs font-medium text-gray-500 mb-1\">\n Reorder Columns\n </div>\n <div className=\"max-h-60 overflow-auto border border-gray-200 rounded-md\">\n {(() => {\n // Build ordered array by columnOrder using allColumns\n const ordered = [\n ...columnOrder\n .map((k) =>\n allColumns.find((c) => c.key === k),\n )\n .filter(Boolean),\n // add any missing\n ...allColumns.filter(\n (c) => !columnOrder.includes(c.key),\n ),\n ] as GridColumn[];\n\n return ordered.map((c) => {\n const isPinnedItem = pinnedKeySet.has(\n c.key,\n );\n return (\n <div\n key={c.key}\n className={`flex items-center justify-between px-2 py-1 text-sm bg-white hover:bg-gray-50 border-b last:border-b-0 relative ${\n menuReorderDraggingKey === c.key\n ? \"opacity-60\"\n : \"\"\n } ${\n isPinnedItem ? \"bg-blue-50/40\" : \"\"\n }`}\n draggable\n onDragStart={(e) =>\n handleMenuReorderDragStart(c.key, e)\n }\n onDragOver={(e) =>\n handleMenuReorderDragOver(c.key, e)\n }\n onDrop={() =>\n handleMenuReorderDrop(c.key)\n }\n onDragEnd={handleMenuReorderDragEnd}\n >\n {/* drop indicator */}\n {menuReorderDragOver?.key ===\n c.key && (\n <div\n className=\"absolute left-0 right-0 h-0.5 bg-blue-600\"\n style={{\n top:\n menuReorderDragOver?.position ===\n \"before\"\n ? 0\n : undefined,\n bottom:\n menuReorderDragOver?.position ===\n \"after\"\n ? 0\n : undefined,\n }}\n />\n )}\n <div className=\"flex items-center gap-2\">\n <span className=\"text-gray-400 select-none\">\n ⋮⋮\n </span>\n <span className=\"text-gray-800 truncate max-w-45\">\n {c.header}\n {isPinnedItem && (\n <span className=\"ml-1 text-[10px] text-blue-600\">\n (pinned)\n </span>\n )}\n </span>\n </div>\n </div>\n );\n });\n })()}\n </div>\n <div className=\"text-[10px] text-gray-400 mt-1\">\n Tip: You can only reorder within pinned or\n unpinned groups.\n </div>\n </div>\n )}\n </div>\n )}\n </div>\n )}\n </div>\n </div>\n\n {/* Resize handle */}\n {index < pinnedColumns.length - 1 && onColumnResize && (\n <div\n className=\"absolute top-0 right-0 w-1 h-full cursor-col-resize hover:bg-blue-300 transition-colors group\"\n onMouseDown={(e) => handleResizeStart(column.key, e)}\n onDoubleClick={(e) => {\n e.preventDefault();\n e.stopPropagation();\n onAutosizeColumn?.(column.key);\n }}\n title=\"Drag to resize • Double‑click to autosize\"\n >\n <div className=\"w-full h-full group-hover:bg-blue-400\" />\n </div>\n )}\n </div>\n );\n })}\n\n {/* Spacer before first visible unpinned col */}\n {hvPadLeft > 0 && (\n <div\n style={{ width: hvPadLeft, height: headerHeight }}\n className=\"flex-none\"\n />\n )}\n\n {/* Unpinned visible columns */}\n {unpinnedColumns.map((column, index) => {\n // unpinned visible segment\n const headerJustify =\n column.headerAlign === \"center\"\n ? \"justify-center\"\n : column.headerAlign === \"right\"\n ? \"justify-end\"\n : \"justify-start\";\n\n const colSortable = column.sortable !== false;\n return (\n <div\n key={column.key + index}\n className={`flex-none border-r border-gray-200 dark:border-gray-700 last:border-r-0 relative`}\n style={{ width: column.width || 100, height: headerHeight }}\n data-column-key={column.key}\n draggable\n onDragStart={(e) => handleDragStart(column.key, e)}\n onDragOver={(e) => handleDragOver(column.key, e)}\n onDrop={() => handleDrop(column.key)}\n onDragEnd={handleDragEnd}\n >\n {/* Drop indicator */}\n {dragOver?.key === column.key && (\n <div\n className=\"absolute top-0 bottom-0 w-0.5 bg-blue-600 z-4\"\n style={{\n left: dragOver?.position === \"before\" ? 0 : undefined,\n right: dragOver?.position === \"after\" ? 0 : undefined,\n }}\n />\n )}\n <div className=\"px-3 h-full\">\n {/* Header with sort */}\n <div className=\"flex items-center justify-between gap-1 group h-full\">\n <div\n className={`flex items-center min-w-0 flex-1 ${headerJustify} ${\n colSortable ? \"cursor-pointer hover:text-blue-600\" : \"\"\n }`}\n onClick={() => colSortable && onSort(column.key)}\n >\n <div className=\"flex items-center gap-2 min-w-0\">\n {/* Filter indicator */}\n {hasActiveFilter(column.key) && (\n <div\n className=\"w-2 h-2 bg-red-500 rounded-full shrink-0\"\n title=\"Filter applied\"\n />\n )}\n <span className=\"font-medium text-gray-900 dark:text-gray-100 text-sm truncate min-w-0\">\n {column.header}\n </span>\n </div>\n {colSortable && sortConfig.key === column.key && (\n <div className=\"ml-1 shrink-0 pointer-events-none select-none\">\n {sortConfig.direction === \"asc\" ? (\n <ArrowUp className=\"w-3 h-3 text-blue-600 dark:text-blue-400\" />\n ) : (\n <ArrowDown className=\"w-3 h-3 text-blue-600 dark:text-blue-400\" />\n )}\n </div>\n )}\n </div>\n\n {/* Three-dot menu */}\n {(column.filterable || onColumnPin || groupable) && (\n <div\n className={`relative ${\n activeColumnMenu === column.key || isTouchDevice\n ? \"block\"\n : \"hidden group-hover:block\"\n }`}\n data-column-menu\n >\n <button\n className=\"p-1 hover:bg-gray-200 dark:hover:bg-gray-700 rounded shrink-0\"\n onClick={(e) => handleColumnMenuClick(column.key, e)}\n data-menu-trigger\n >\n <Menu className=\"w-4 h-4 text-gray-500 dark:text-gray-400\" />\n </button>\n\n {/* Dropdown Menu with Tabs */}\n {activeColumnMenu === column.key && menuPosition && (\n <div\n className=\"fixed bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-md shadow-lg z-10 w-[320px] overflow-auto\"\n style={{\n top: `${menuPosition.top}px`,\n left: `${menuPosition.left}px`,\n // Ensure the menu height never exceeds available space within the grid container\n maxHeight: `${Math.max(\n 160,\n menuPosition.containerRect.bottom -\n 12 -\n menuPosition.top,\n )}px`,\n }}\n data-column-menu\n >\n {/* Tabs */}\n <div className=\"flex items-center border-b border-gray-200 dark:border-gray-700\">\n <button\n className={`px-3 py-2 text-sm flex items-center gap-2 ${\n activeTab === \"menu\"\n ? \"border-b-2 border-blue-600 text-blue-600\"\n : \"text-gray-600\"\n }`}\n onClick={() => setActiveTab(\"menu\")}\n >\n <Menu className=\"w-4 h-4\" />\n </button>\n {column.filterable && (\n <button\n className={`px-3 py-2 text-sm flex items-center gap-2 ${\n activeTab === \"filter\"\n ? \"border-b-2 border-blue-600 text-blue-600\"\n : \"text-gray-600\"\n }`}\n onClick={() => setActiveTab(\"filter\")}\n >\n <Filter className=\"w-4 h-4\" />\n </button>\n )}\n <button\n className={`px-3 py-2 text-sm flex items-center gap-2 ${\n activeTab === \"reorder\"\n ? \"border-b-2 border-blue-600 text-blue-600\"\n : \"text-gray-600\"\n }`}\n onClick={() => setActiveTab(\"reorder\")}\n >\n <ArrowUpDown className=\"w-4 h-4\" />\n </button>\n </div>\n {/* Tab Content (reusing existing code paths) */}\n {activeTab === \"menu\" && (\n <div className=\"py-1\">\n {onColumnPin && (\n <button\n className=\"w-full px-3 py-2 text-left text-sm hover:bg-gray-50 flex items-center gap-2\"\n onClick={(e) => {\n e.stopPropagation();\n setActiveColumnMenu(null);\n const nextPinned = !pinnedKeySet.has(\n column.key,\n );\n onColumnPin?.(column.key, nextPinned);\n }}\n >\n {pinnedKeySet.has(column.key) ? (\n <>\n <PinOff className=\"w-4 h-4\" />\n Unpin Column\n </>\n ) : (\n <>\n <Pin className=\"w-4 h-4\" />\n Pin Column\n </>\n )}\n </button>\n )}\n {onAutosizeColumn && (\n <button\n className=\"w-full px-3 py-2 text-left text-sm hover:bg-gray-50\"\n onClick={() => {\n onAutosizeColumn?.(column.key);\n setActiveColumnMenu(null);\n }}\n >\n Autosize This Column\n </button>\n )}\n {onAutosizeAllColumns && (\n <button\n className=\"w-full px-3 py-2 text-left text-sm hover:bg-gray-50\"\n onClick={() => {\n onAutosizeAllColumns?.();\n setActiveColumnMenu(null);\n }}\n >\n Autosize All Columns\n </button>\n )}\n\n {groupable && (\n <button\n className=\"w-full px-3 py-2 text-left text-sm hover:bg-gray-50 flex items-center gap-2\"\n onClick={(e) => {\n e.stopPropagation();\n setActiveColumnMenu(null);\n const isGrouped =\n groupedByColumns?.includes(\n column.key,\n ) || groupedByColumn === column.key;\n if (onGroupToggle)\n onGroupToggle(column.key, !isGrouped);\n else\n onGroupBy?.(\n isGrouped ? null : column.key,\n );\n }}\n >\n {groupedByColumn === column.key ||\n groupedByColumns?.includes(column.key) ? (\n <>\n <Ungroup className=\"w-4 h-4\" />\n Ungroup\n </>\n ) : (\n <>\n <Group className=\"w-4 h-4\" />\n Group by {column.header}\n </>\n )}\n </button>\n )}\n\n {onResetColumns && (\n <button\n className=\"w-full px-3 py-2 text-left text-sm hover:bg-gray-50\"\n onClick={() => {\n onResetColumns?.();\n setActiveColumnMenu(null);\n }}\n >\n Reset Columns\n </button>\n )}\n </div>\n )}\n {activeTab === \"filter\" && (\n <div className=\"p-3 w-full\">\n <div className=\"max-h-75 overflow-auto pr-1\">\n <FilterContent\n column={column}\n data={data}\n value={tempFilter}\n onChange={(val) => {\n setTempFilter(val);\n // Auto-apply for client-side or no pagination\n if (paginationMode !== \"server\") {\n onColumnFilter(column.key, val);\n }\n }}\n />\n </div>\n <div className=\"flex justify-end gap-2 mt-3\">\n {hasActiveFilter(column.key) && (\n <button\n className=\"px-3 py-1.5 text-sm bg-red-500 text-white rounded-md hover:bg-red-600 flex items-center gap-2 cursor-pointer\"\n onClick={() => {\n setTempFilter(null);\n onColumnFilter(column.key, null);\n setActiveColumnMenu(null);\n }}\n >\n <FilterX className=\"w-3 h-3\" /> Clear\n Filter\n </button>\n )}\n <button\n className=\"px-3 py-1.5 text-sm bg-green-100 text-green-700 rounded-md hover:bg-green-200 cursor-pointer\"\n onClick={() => setActiveColumnMenu(null)}\n >\n Apply\n </button>\n {paginationMode === \"server\" && (\n <button\n className=\"px-3 py-1.5 text-sm bg-blue-600 text-white rounded-md hover:bg-blue-700\"\n onClick={() =>\n handleApplyFilter(column.key)\n }\n >\n Apply\n </button>\n )}\n </div>\n </div>\n )}\n {activeTab === \"reorder\" && (\n <div className=\"px-3 py-2\">\n <div className=\"text-xs font-medium text-gray-500 mb-1\">\n Reorder Columns\n </div>\n <div className=\"max-h-60 overflow-auto border border-gray-200 rounded-md\">\n {(() => {\n const ordered = [\n ...columnOrder\n .map((k) =>\n allColumns.find((c) => c.key === k),\n )\n .filter(Boolean),\n ...allColumns.filter(\n (c) => !columnOrder.includes(c.key),\n ),\n ] as GridColumn[];\n\n return ordered.map((c) => {\n const isPinnedItem = pinnedKeySet.has(\n c.key,\n );\n return (\n <div\n key={c.key}\n className={`flex items-center justify-between px-2 py-1 text-sm bg-white hover:bg-gray-50 border-b last:border-b-0 relative ${\n menuReorderDraggingKey === c.key\n ? \"opacity-60\"\n : \"\"\n } ${\n isPinnedItem ? \"bg-blue-50/40\" : \"\"\n }`}\n draggable\n onDragStart={(e) =>\n handleMenuReorderDragStart(c.key, e)\n }\n onDragOver={(e) =>\n handleMenuReorderDragOver(c.key, e)\n }\n onDrop={() =>\n handleMenuReorderDrop(c.key)\n }\n onDragEnd={handleMenuReorderDragEnd}\n >\n {menuReorderDragOver?.key ===\n c.key && (\n <div\n className=\"absolute left-0 right-0 h-0.5 bg-blue-600\"\n style={{\n top:\n menuReorderDragOver?.position ===\n \"before\"\n ? 0\n : undefined,\n bottom:\n menuReorderDragOver?.position ===\n \"after\"\n ? 0\n : undefined,\n }}\n />\n )}\n <div className=\"flex items-center gap-2\">\n <span className=\"text-gray-400 select-none\">\n ⋮⋮\n </span>\n <span className=\"text-gray-800 truncate max-w-45\">\n {c.header}\n {isPinnedItem && (\n <span className=\"ml-1 text-[10px] text-blue-600\">\n (pinned)\n </span>\n )}\n </span>\n </div>\n </div>\n );\n });\n })()}\n </div>\n <div className=\"text-[10px] text-gray-400 mt-1\">\n Tip: You can only reorder within pinned or\n unpinned groups.\n </div>\n </div>\n )}\n </div>\n )}\n </div>\n )}\n </div>\n </div>\n\n {/* Resize handle */}\n {index < unpinnedColumns.length - 1 && onColumnResize && (\n <div\n className=\"absolute top-0 right-0 w-1 h-full cursor-col-resize hover:bg-blue-300 transition-colors group\"\n onMouseDown={(e) => handleResizeStart(column.key, e)}\n onDoubleClick={(e) => {\n e.preventDefault();\n e.stopPropagation();\n onAutosizeColumn?.(column.key);\n }}\n title=\"Drag to resize • Double‑click to autosize\"\n >\n <div className=\"w-full h-full group-hover:bg-blue-400\" />\n </div>\n )}\n </div>\n );\n })}\n\n {/* Spacer after last visible unpinned col */}\n {hvPadRight > 0 && (\n <div\n style={{ width: hvPadRight, height: headerHeight }}\n className=\"flex-none\"\n />\n )}\n </div>\n </div>\n\n {/* Inline filter handled in dropdown tabs */}\n </>\n );\n};\n\nGridHeaderComponent.displayName = \"GridHeader\";\nexport const GridHeader = /*#__PURE__*/ memo(GridHeaderComponent);\n","import { ReactNode, useEffect, useMemo, useRef, useState } from \"react\";\nimport { Copy, Trash2, Eye } from \"../icons\";\nimport { GridRow, ContextMenuItem } from \"../types\";\n\n// ---------------------------------------------------------------------------\n// Empty default — consumers must wire their own items via `contextMenuItems`.\n// No default items ship to production to avoid console.log noise.\n//\n// If you want a quick starter set, import `defaultContextMenuItems` from this\n// module and pass it to contextMenuItems + handle each action yourself.\n// ---------------------------------------------------------------------------\n\n/** Ready-made starter items — ONLY for development / demos.\n * All items are no-ops in dev environments (they log in DEV only).\n * Do NOT rely on these in production; wire your own `contextMenuItems`. */\nexport const defaultContextMenuItems: ContextMenuItem[] = [\n {\n id: \"view\",\n label: \"View Details\",\n icon: <Eye className=\"w-4 h-4\" />,\n onClick: (row) => {\n if (process.env.NODE_ENV === \"development\") {\n // eslint-disable-next-line no-console\n console.info(\n \"[KDGrid] Default 'View' action — provide your own contextMenuItems handler.\",\n row,\n );\n }\n },\n },\n {\n id: \"copy\",\n label: \"Copy Row\",\n icon: <Copy className=\"w-4 h-4\" />,\n onClick: (row) => {\n navigator.clipboard.writeText(JSON.stringify(row, null, 2)).catch(() => {\n /* ignore clipboard errors */\n });\n },\n },\n {\n id: \"_sep1\",\n label: \"\",\n separator: true,\n onClick: () => {},\n },\n {\n id: \"delete\",\n label: \"Delete\",\n icon: <Trash2 className=\"w-4 h-4\" />,\n onClick: (row) => {\n if (process.env.NODE_ENV === \"development\") {\n // eslint-disable-next-line no-console\n console.info(\n \"[KDGrid] Default 'Delete' action — provide your own contextMenuItems handler.\",\n row,\n );\n }\n },\n },\n];\n\ninterface RowContextMenuProps {\n row: GridRow;\n position: { x: number; y: number };\n isVisible: boolean;\n onClose: () => void;\n /** Custom menu items. If not provided the menu will not render. */\n menuItems?: ContextMenuItem[];\n}\n\nexport const RowContextMenu = ({\n row,\n position,\n isVisible,\n onClose,\n menuItems,\n}: RowContextMenuProps) => {\n const menuRef = useRef<HTMLDivElement>(null);\n\n useEffect(() => {\n if (!isVisible) return;\n\n const handleClickOutside = (event: MouseEvent) => {\n if (menuRef.current && !menuRef.current.contains(event.target as Node)) {\n onClose();\n }\n };\n const handleEscape = (event: KeyboardEvent) => {\n if (event.key === \"Escape\") onClose();\n };\n\n document.addEventListener(\"mousedown\", handleClickOutside);\n document.addEventListener(\"keydown\", handleEscape);\n return () => {\n document.removeEventListener(\"mousedown\", handleClickOutside);\n document.removeEventListener(\"keydown\", handleEscape);\n };\n }, [isVisible, onClose]);\n\n // Adjust position to keep menu within viewport\n const adjustedPosition = useMemo(() => {\n if (!isVisible || !menuItems?.length) return position;\n\n const menuWidth = 200;\n const menuHeight =\n menuItems.filter((item) => !item.separator).length * 40 +\n menuItems.filter((item) => item.separator).length * 10;\n const viewportWidth = window.innerWidth;\n const viewportHeight = window.innerHeight;\n\n let x = position.x;\n let y = position.y;\n\n if (x + menuWidth / 2 > viewportWidth)\n x = viewportWidth - menuWidth / 2 - 10;\n if (x - menuWidth / 2 < 0) x = menuWidth / 2 + 10;\n if (y + menuHeight > viewportHeight) y = y - menuHeight - 10;\n\n return { x, y };\n }, [position, isVisible, menuItems]);\n\n // Don't render if no items or not visible\n if (!isVisible || !menuItems?.length) return null;\n\n const handleItemClick = (item: ContextMenuItem) => {\n if (!item.disabled && !item.separator) {\n item.onClick(row);\n onClose();\n }\n };\n\n return (\n <>\n {/* Backdrop */}\n <div className=\"fixed inset-0 z-40\" onClick={onClose} />\n\n {/* Context Menu */}\n <div\n ref={menuRef}\n role=\"menu\"\n aria-label=\"Row actions\"\n className=\"fixed z-50 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg py-1 min-w-[180px]\"\n style={{\n left: `${adjustedPosition.x}px`,\n top: `${adjustedPosition.y}px`,\n transform: \"translate(-50%, 0)\",\n }}\n >\n {menuItems.map((item) => {\n if (item.separator) {\n return (\n <div\n key={item.id}\n role=\"separator\"\n className=\"border-t border-gray-100 dark:border-gray-700 my-1\"\n />\n );\n }\n\n return (\n <button\n key={item.id}\n role=\"menuitem\"\n onClick={() => handleItemClick(item)}\n disabled={item.disabled}\n className={`w-full flex items-center gap-3 px-3 py-2 text-sm text-left transition-colors ${\n item.disabled\n ? \"text-gray-400 dark:text-gray-600 cursor-not-allowed\"\n : item.id === \"delete\"\n ? \"text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20\"\n : \"text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-700\"\n }`}\n >\n {item.icon && <span className=\"shrink-0\">{item.icon}</span>}\n <span className=\"flex-1\">{item.label}</span>\n </button>\n );\n })}\n </div>\n </>\n );\n};\n","import {\n CSSProperties,\n MouseEvent,\n memo,\n useMemo,\n useState,\n useCallback,\n} from \"react\";\nimport {\n GridRow,\n GridColumn,\n VirtualizedRange,\n ContextMenuItem,\n RowEventParams,\n CellClickParams,\n CellContextMenuParams,\n} from \"../types\";\nimport { RowContextMenu } from \"./RowContextMenu\";\nimport { SELECT_COL_WIDTH } from \"../constants\";\nimport { highlightText, containsSearchQuery } from \"../utils/highlightText\";\n\ninterface GridRowsProps {\n data: GridRow[];\n columns: GridColumn[];\n selectedRows: Set<string | number>;\n virtualized: boolean;\n virtualizedRange: VirtualizedRange;\n rowHeight: number;\n selectable: boolean;\n isRowSelectable?: (row: GridRow) => boolean;\n onRowSelect: (rowId: string | number, isSelected: boolean) => void;\n pinnedColumns?: Set<string>;\n hvPadLeft?: number;\n hvPadRight?: number;\n rowStyle?: (row: GridRow) => CSSProperties | undefined;\n rowClassName?: string | ((row: GridRow, index: number) => string);\n globalFilter?: string;\n onContextMenu?: (params: RowEventParams) => void;\n onRowDoubleClick?: (params: RowEventParams) => void;\n onRowClick?: (params: RowEventParams) => void;\n onCellClick?: (params: CellClickParams) => void;\n // Cell focus & selection\n isCellFocused?: (rowId: string | number, columnKey: string) => boolean;\n isCellSelected?: (rowId: string | number, columnKey: string) => boolean;\n // Cell-level context menu (right-click)\n onCellContextMenu?: (params: CellContextMenuParams) => void;\n onCellMouseDown?: (args: {\n row: GridRow;\n column: GridColumn;\n event: MouseEvent;\n }) => void;\n onCellMouseEnter?: (args: {\n row: GridRow;\n column: GridColumn;\n event: MouseEvent;\n }) => void;\n /** Custom items for the row right-click context menu. */\n contextMenuItems?: ContextMenuItem[];\n getRowId?: (row: GridRow) => string | number;\n}\n\nconst GridRowsComponent = ({\n data,\n columns,\n selectedRows,\n virtualized,\n virtualizedRange,\n rowHeight,\n selectable,\n isRowSelectable,\n onRowSelect,\n pinnedColumns = new Set(),\n hvPadLeft = 0,\n hvPadRight = 0,\n rowStyle,\n rowClassName,\n globalFilter,\n onContextMenu,\n onRowDoubleClick,\n onRowClick,\n onCellClick,\n isCellFocused,\n isCellSelected,\n onCellContextMenu,\n onCellMouseDown,\n onCellMouseEnter,\n contextMenuItems,\n getRowId,\n}: GridRowsProps) => {\n // Helper to extract row ID\n const extractRowId = (row: GridRow, rowIndex?: number): string | number => {\n if (getRowId) {\n return getRowId(row);\n }\n if (row.id !== undefined) {\n return row.id;\n }\n // Fallback: use row index\n if (process.env.NODE_ENV === \"development\" && rowIndex === 0) {\n console.warn(\n \"[KDGrid] No row IDs found. Either:\\n\" +\n \" 1. Add 'id' property to each row object, or\\n\" +\n \" 2. Provide 'getRowId' prop to extract a unique identifier.\\n\" +\n \" Using row index as fallback ID, but this may cause issues with pagination/filtering.\",\n );\n }\n return rowIndex ?? 0;\n };\n const totalHeight = useMemo(\n () => data.length * rowHeight,\n [data.length, rowHeight],\n );\n\n // Precompute pinned metadata for left offsets efficiently - OPTIMIZED\n const { leftOffsetByPinnedKey } = useMemo(() => {\n // Early return if no pinned columns\n if (pinnedColumns.size === 0) {\n return { leftOffsetByPinnedKey: new Map<string, number>() };\n }\n\n const pinnedKeysInOrder = columns\n .filter((c) => pinnedColumns.has(c.key))\n .map((c) => c.key);\n\n // Use direct property access instead of Map for better performance\n const widthByKey = new Map<string, number>();\n for (const col of columns) {\n widthByKey.set(col.key, col.width || 100);\n }\n\n const leftOffsetByPinnedKey = new Map<string, number>();\n let acc = selectable ? SELECT_COL_WIDTH : 0;\n\n for (const key of pinnedKeysInOrder) {\n leftOffsetByPinnedKey.set(key, acc);\n acc += widthByKey.get(key) || 100;\n }\n\n return { leftOffsetByPinnedKey };\n }, [columns, pinnedColumns, selectable]);\n\n // Count how many columns are pinned in the provided visible columns list\n const pinnedCount = useMemo(\n () => columns.reduce((n, c) => n + (pinnedColumns.has(c.key) ? 1 : 0), 0),\n [columns, pinnedColumns],\n );\n\n const handleDoubleClick = (e: MouseEvent, row: GridRow) => {\n onRowDoubleClick?.({ row, event: e });\n };\n\n const handleRowClick = (e: MouseEvent, row: GridRow) => {\n onRowClick?.({ row, event: e });\n };\n\n const handleCellClick = (\n e: MouseEvent,\n row: GridRow,\n column: GridColumn,\n value: any,\n ) => {\n onCellClick?.({ row, column, value, event: e });\n };\n\n // ── Context menu state (only needed when contextMenuItems provided) ──────\n const [ctxMenu, setCtxMenu] = useState<{\n row: GridRow;\n x: number;\n y: number;\n } | null>(null);\n\n const handleContextMenu = useCallback(\n (e: MouseEvent, row: GridRow) => {\n e.preventDefault();\n // Fire the external onContextMenu callback\n onContextMenu?.({ row, event: e });\n // Show built-in context menu only if items are configured\n if (contextMenuItems?.length) {\n setCtxMenu({ row, x: e.clientX, y: e.clientY });\n }\n },\n [onContextMenu, contextMenuItems],\n );\n\n const closeCtxMenu = useCallback(() => setCtxMenu(null), []);\n\n return (\n <>\n {/* Outer div provides total height for virtualization scroll */}\n <div\n style={{\n height: virtualized ? `${totalHeight}px` : \"auto\",\n position: \"relative\",\n }}\n >\n <div\n style={{\n transform: virtualized\n ? `translate3d(0, ${virtualizedRange.offsetY}px, 0)`\n : \"none\",\n position: virtualized ? \"absolute\" : \"static\",\n top: 0,\n left: 0,\n right: 0,\n }}\n >\n {data.map((row, index) => {\n const actualIndex = virtualized\n ? virtualizedRange.startIndex + index\n : index;\n const customRowStyles = rowStyle?.(row);\n const rowId = extractRowId(row, actualIndex);\n const defaultRowColor =\n actualIndex % 2 === 0\n ? \"bg-white dark:bg-gray-900\"\n : \"bg-gray-25 dark:bg-gray-800\";\n const selectedRowColor = selectedRows.has(rowId)\n ? \"bg-blue-50 dark:bg-blue-900/20\"\n : \"\";\n\n return (\n <div\n key={`${rowId}-${actualIndex}`}\n className={`flex border-b border-gray-100 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-700 ${\n selectedRowColor || (customRowStyles ? \"\" : defaultRowColor)\n }`}\n style={{\n height: `${rowHeight}px`,\n ...customRowStyles,\n }}\n onContextMenu={(e) => handleContextMenu(e, row)}\n onDoubleClick={(e) => handleDoubleClick(e, row)}\n onClick={(e) => handleRowClick(e, row)}\n >\n {selectable && (\n <div\n className=\"flex items-center justify-center sticky left-0 bg-white dark:bg-gray-900 z-2 border-r border-gray-200 dark:border-gray-700\"\n style={{ width: SELECT_COL_WIDTH }}\n >\n <input\n type=\"checkbox\"\n checked={selectedRows.has(rowId)}\n disabled={isRowSelectable ? !isRowSelectable(row) : false}\n onChange={(e) => onRowSelect(rowId, e.target.checked)}\n onKeyDown={(e) => {\n if (e.key === \" \" || e.key === \"Enter\") {\n e.preventDefault();\n onRowSelect(rowId, !selectedRows.has(rowId));\n }\n }}\n className=\"rounded border-gray-300 dark:border-gray-600 text-blue-600 cursor-pointer disabled:cursor-not-allowed disabled:opacity-50 h-4 w-4 transition-all duration-150\"\n aria-label={`Select row ${rowId}`}\n tabIndex={0}\n />\n </div>\n )}\n\n {columns.map((column, colIndex) => {\n const isPinned = pinnedColumns.has(column.key);\n const leftOffset = isPinned\n ? leftOffsetByPinnedKey.get(column.key) || 0\n : 0;\n\n // Optimized cell value processing\n const rawCell = row[column.key];\n let renderedValue: React.ReactNode;\n let displayValue: string | undefined;\n\n // Optimize cell renderer calls\n if (column.cellRenderer) {\n renderedValue = column.cellRenderer(rawCell, row);\n // Only compute display value if needed for tooltip\n if (\n typeof rawCell === \"string\" ||\n typeof rawCell === \"number\" ||\n typeof rawCell === \"boolean\"\n ) {\n displayValue = String(rawCell);\n }\n } else if (column.formatter) {\n renderedValue = column.formatter(rawCell);\n displayValue = String(renderedValue);\n } else {\n renderedValue = rawCell ?? \"\";\n displayValue = renderedValue\n ? String(renderedValue)\n : undefined;\n }\n\n // Apply highlighting for global filter if present and no custom renderer\n if (\n globalFilter &&\n globalFilter.trim() &&\n !column.cellRenderer &&\n renderedValue\n ) {\n const textValue = String(renderedValue);\n if (containsSearchQuery(textValue, globalFilter)) {\n renderedValue = highlightText(textValue, globalFilter);\n }\n }\n\n // Clean up empty display values\n if (displayValue && displayValue.trim().length === 0) {\n displayValue = undefined;\n }\n\n // Pre-compute CSS classes for better performance\n const alignClass =\n column.align === \"center\"\n ? \"text-center\"\n : column.align === \"right\"\n ? \"text-right\"\n : \"text-left\";\n const justifyClass =\n column.align === \"center\"\n ? \"justify-center\"\n : column.align === \"right\"\n ? \"justify-end\"\n : \"justify-start\";\n const paddingClass = column.noPadding ? \"p-0\" : \"p-3\";\n\n // Optimize dynamic class/style computation\n const extraCellClass =\n typeof column.className === \"function\"\n ? column.className(rawCell, row)\n : column.className || \"\";\n const extraCellStyle =\n typeof column.cellStyle === \"function\"\n ? column.cellStyle(rawCell, row)\n : column.cellStyle || undefined;\n\n const cell = (\n <div\n key={`${column.key}-${colIndex}`}\n className={`border-r border-gray-200 last:border-r-0 ${paddingClass} text-sm flex items-center ${\n isCellSelected?.(rowId, column.key)\n ? \"bg-blue-100/60 dark:bg-blue-900/30\"\n : \"\"\n } ${\n isPinned\n ? isCellFocused?.(rowId, column.key)\n ? \"sticky z-2 bg-inherit\"\n : \"sticky z-1 bg-inherit\"\n : \"\"\n } ${\n isCellFocused?.(rowId, column.key) ? \"relative\" : \"\"\n } ${alignClass} ${justifyClass} ${extraCellClass}`}\n style={{\n width: `${column.width || 100}px`,\n left: isPinned ? `${leftOffset}px` : \"auto\",\n ...extraCellStyle,\n }}\n // Show native tooltip only when a meaningful value exists (non-empty string after trimming)\n title={displayValue}\n onClick={(e) =>\n handleCellClick(e, row, column, row[column.key])\n }\n onContextMenu={(e) => {\n // Only handle for real data rows\n if (\n (row as any)._isGroupHeader ||\n (row as any)._isGroupFooter\n )\n return;\n if (onCellContextMenu) {\n e.preventDefault();\n e.stopPropagation();\n onCellContextMenu({\n row,\n column,\n value: (row as any)[column.key],\n displayValue: displayValue ?? \"\",\n event: e as any,\n });\n }\n // If no onCellContextMenu prop, fall back to row-level handler (do not stop propagation)\n }}\n onMouseDown={(e) =>\n onCellMouseDown?.({ row, column, event: e })\n }\n onMouseEnter={(e) =>\n onCellMouseEnter?.({ row, column, event: e })\n }\n >\n {isCellFocused?.(rowId, column.key) && (\n <div className=\"pointer-events-none absolute inset-0 border border-blue-400\" />\n )}\n {column.wrapCellContent === false ? (\n <>{renderedValue}</>\n ) : (\n <div className=\"truncate w-full\">{renderedValue}</div>\n )}\n </div>\n );\n // Insert left spacer once before the first unpinned visible column\n if (hvPadLeft > 0 && colIndex === pinnedCount) {\n return (\n <>\n <div\n style={{ width: hvPadLeft }}\n className=\"flex-none\"\n />\n {cell}\n </>\n );\n }\n\n return cell;\n })}\n {/* Spacer after last visible unpinned col */}\n {hvPadRight > 0 && (\n <div style={{ width: hvPadRight }} className=\"flex-none\" />\n )}\n </div>\n );\n })}\n </div>\n </div>\n\n {/* Context menu portal — renders outside the scrollable area */}\n {ctxMenu && (\n <RowContextMenu\n row={ctxMenu.row}\n position={{ x: ctxMenu.x, y: ctxMenu.y }}\n isVisible={true}\n onClose={closeCtxMenu}\n menuItems={contextMenuItems}\n />\n )}\n </>\n );\n};\n\nconst areEqual = (prev: GridRowsProps, next: GridRowsProps) => {\n if (prev.rowHeight !== next.rowHeight) return false;\n if (prev.selectable !== next.selectable) return false;\n if (prev.virtualized !== next.virtualized) return false;\n if (prev.globalFilter !== next.globalFilter) return false;\n if (prev.virtualizedRange.startIndex !== next.virtualizedRange.startIndex)\n return false;\n if (prev.virtualizedRange.endIndex !== next.virtualizedRange.endIndex)\n return false;\n if (prev.virtualizedRange.offsetY !== next.virtualizedRange.offsetY)\n return false;\n // Re-render when focus/selection functions change identity (they depend on selection & focus states)\n if (prev.isCellSelected !== next.isCellSelected) return false;\n if (prev.isCellFocused !== next.isCellFocused) return false;\n // Re-render when drag-selection handlers change identity (closure depends on selectionAnchor/end)\n if (prev.onCellMouseDown !== next.onCellMouseDown) return false;\n if (prev.onCellMouseEnter !== next.onCellMouseEnter) return false;\n if (prev.getRowId !== next.getRowId) return false;\n if (prev.selectedRows.size !== next.selectedRows.size) return false;\n if (prev.pinnedColumns?.size !== next.pinnedColumns?.size) return false;\n const prevCols = prev.columns.map((c) => c.key).join(\"|\");\n const nextCols = next.columns.map((c) => c.key).join(\"|\");\n if (prevCols !== nextCols) return false;\n if (prev.data.length !== next.data.length) return false;\n\n // Fast path: same array reference → nothing changed\n if (prev.data === next.data) return true;\n\n // Full ID scan: detects mutations anywhere in the list (not just first/last).\n // O(n) but n = visible rows only (typically 20-80), not the entire dataset.\n const extractId = (\n row: GridRow,\n idx: number,\n getRowId?: (r: GridRow) => string | number,\n ) => {\n if (getRowId) return getRowId(row);\n if (row.id !== undefined) return row.id;\n return idx;\n };\n\n for (let i = 0; i < next.data.length; i++) {\n const pid = extractId(prev.data[i], i, prev.getRowId);\n const nid = extractId(next.data[i], i, next.getRowId);\n if (pid !== nid) return false;\n }\n\n return true;\n};\n\nGridRowsComponent.displayName = \"GridRows\";\nexport const GridRows = /*#__PURE__*/ memo(GridRowsComponent, areEqual);\n","import React from \"react\";\n\n/**\n * Highlights matching text within a string based on a search query\n * @param text - The text to highlight\n * @param searchQuery - The search query to match against\n * @returns JSX element with highlighted matches\n */\nexport const highlightText = (\n text: string,\n searchQuery: string\n): React.ReactNode => {\n if (!searchQuery || !text) {\n return text;\n }\n\n const query = searchQuery.toLowerCase().trim();\n const lowerText = text.toLowerCase();\n\n if (!query || !lowerText.includes(query)) {\n return text;\n }\n\n const parts: React.ReactNode[] = [];\n let lastIndex = 0;\n let searchIndex = 0;\n let keyCounter = 0; // Use counter for unique keys\n\n while ((searchIndex = lowerText.indexOf(query, lastIndex)) !== -1) {\n // Add text before the match\n if (searchIndex > lastIndex) {\n parts.push(text.slice(lastIndex, searchIndex));\n }\n\n // Add the highlighted match\n parts.push(\n <mark\n key={`highlight-${keyCounter++}`}\n className=\"bg-yellow-200 dark:bg-yellow-600/40 text-current font-medium px-0.5 py-0 rounded-sm\"\n style={{ margin: 0 }} // Ensure no unwanted margins\n >\n {text.slice(searchIndex, searchIndex + query.length)}\n </mark>\n );\n\n lastIndex = searchIndex + query.length;\n }\n\n // Add remaining text after the last match\n if (lastIndex < text.length) {\n parts.push(text.slice(lastIndex));\n }\n\n return <>{parts}</>;\n};\n\n/**\n * Checks if a value contains the search query (case-insensitive)\n * @param value - The value to check\n * @param searchQuery - The search query\n * @returns true if the value contains the search query\n */\nexport const containsSearchQuery = (\n value: any,\n searchQuery: string\n): boolean => {\n if (!searchQuery || value == null) {\n return false;\n }\n\n const query = searchQuery.toLowerCase().trim();\n if (!query) {\n return false;\n }\n\n const text = String(value).toLowerCase();\n return text.includes(query);\n};\n","import { useState } from \"react\";\nimport type { GridColumn } from \"../types\";\n\ninterface GroupBarProps {\n columns: GridColumn[];\n groupedKeys: string[];\n onRemove: (columnKey: string) => void;\n onReorder: (newOrder: string[]) => void;\n onDropColumnKey: (columnKey: string) => void;\n onToggleExpandAll?: () => void;\n isAnyExpanded?: boolean;\n}\n\nexport const GroupBar = ({\n columns,\n groupedKeys,\n onRemove,\n onReorder,\n onDropColumnKey,\n onToggleExpandAll,\n isAnyExpanded = false,\n}: GroupBarProps) => {\n const [dragKey, setDragKey] = useState<string | null>(null);\n const [dragOverKey, setDragOverKey] = useState<string | null>(null);\n const [dragOverBefore, setDragOverBefore] = useState<boolean>(true);\n\n const labelFor = (key: string) => columns.find((c) => c.key === key)?.header || key;\n\n const handleDropFromHeader: React.DragEventHandler<HTMLDivElement> = (e) => {\n e.preventDefault();\n const key = e.dataTransfer.getData(\"text/plain\");\n if (!key) return;\n if (!groupedKeys.includes(key)) onDropColumnKey(key);\n };\n\n const onDragOverBar: React.DragEventHandler<HTMLDivElement> = (e) => {\n e.preventDefault();\n };\n\n const handleChipDragStart = (key: string): React.DragEventHandler<HTMLDivElement> => (e) => {\n setDragKey(key);\n e.dataTransfer.effectAllowed = \"move\";\n e.dataTransfer.setData(\"application/x-group-key\", key);\n };\n\n const handleChipDragOver = (key: string): React.DragEventHandler<HTMLDivElement> => (e) => {\n e.preventDefault();\n const rect = (e.currentTarget as HTMLDivElement).getBoundingClientRect();\n const before = e.clientX < rect.left + rect.width / 2;\n setDragOverKey(key);\n setDragOverBefore(before);\n };\n\n const handleChipDrop = (targetKey: string): React.DragEventHandler<HTMLDivElement> => () => {\n if (!dragKey || dragKey === targetKey) {\n setDragKey(null);\n setDragOverKey(null);\n return;\n }\n const order = groupedKeys.filter((k) => k !== dragKey);\n const idx = order.indexOf(targetKey);\n if (idx === -1) return;\n if (!dragOverBefore) {\n order.splice(idx + 1, 0, dragKey);\n } else {\n order.splice(idx, 0, dragKey);\n }\n onReorder(order);\n setDragKey(null);\n setDragOverKey(null);\n };\n\n const clearDnD = () => {\n setDragKey(null);\n setDragOverKey(null);\n };\n\n return (\n <div\n className=\"flex items-center gap-2 px-3 py-2 bg-gray-50 border-b border-gray-200 text-sm\"\n onDrop={handleDropFromHeader}\n onDragOver={onDragOverBar}\n onDragEnd={clearDnD}\n >\n <span className=\"text-gray-600 whitespace-nowrap\">Group by:</span>\n {groupedKeys.length > 0 && (\n <button\n type=\"button\"\n className=\"ml-1 px-2 py-1 text-xs border border-gray-300 rounded hover:bg-gray-100\"\n title={isAnyExpanded ? \"Collapse all groups\" : \"Expand all groups\"}\n onClick={(e) => {\n e.preventDefault();\n e.stopPropagation();\n onToggleExpandAll?.();\n }}\n >\n {isAnyExpanded ? \"Collapse All\" : \"Expand All\"}\n </button>\n )}\n {groupedKeys.length === 0 && (\n <span className=\"text-gray-400\">Drag a column here</span>\n )}\n <div className=\"flex items-center gap-2 flex-wrap\">\n {groupedKeys.map((key) => (\n <div\n key={key}\n className=\"inline-flex items-center gap-2 bg-blue-100 text-blue-800 px-2 py-1 rounded-md border border-blue-200 cursor-move relative\"\n draggable\n onDragStart={handleChipDragStart(key)}\n onDragOver={handleChipDragOver(key)}\n onDrop={handleChipDrop(key)}\n title={labelFor(key)}\n >\n <span className=\"text-xs font-medium truncate max-w-[160px]\">{labelFor(key)}</span>\n <button\n className=\"text-blue-700 hover:text-blue-900\"\n onClick={() => onRemove(key)}\n aria-label={`Remove grouping ${labelFor(key)}`}\n >\n ×\n </button>\n {dragOverKey === key && (\n <span\n className=\"absolute top-0 bottom-0 w-0.5 bg-blue-600 dark:bg-blue-400 animate-pulse\"\n style={{ left: dragOverBefore ? 0 : undefined, right: dragOverBefore ? undefined : 0 }}\n aria-hidden=\"true\"\n />\n )}\n </div>\n ))}\n </div>\n </div>\n );\n};\n","import { memo } from \"react\";\nimport { ChevronDown, ChevronRight } from \"../icons\";\nimport { GridRow, KDGridProps } from \"../types\";\nimport { SELECT_COL_WIDTH } from \"../constants\";\n\ninterface GroupHeaderProps {\n row: GridRow & {\n _isGroupHeader?: boolean;\n _groupKey?: string;\n _groupCount?: number;\n };\n isExpanded: boolean;\n onToggle: (groupKey: string) => void;\n viewportWidth: number;\n selectable: boolean;\n rowHeight?: number;\n /**\n * Optional function to map a column key to its display label (header).\n * If not provided, the raw column key will be used as a fallback.\n */\n getHeaderLabel?: (columnKey: string) => string;\n /**\n * Optional function to map a column key and raw group value to a display label.\n * Useful to apply the column's formatter for group headers.\n */\n getValueLabel?: (columnKey: string, rawValue: any) => string;\n /**\n * Optional custom renderer for actions on grouped rows.\n */\n renderGroupActions?: KDGridProps[\"renderGroupActions\"];\n}\n\nexport const GroupHeader = memo(\n ({\n row,\n isExpanded,\n onToggle,\n viewportWidth,\n selectable,\n rowHeight = 40,\n getHeaderLabel,\n getValueLabel,\n renderGroupActions,\n }: GroupHeaderProps) => {\n const handleToggle = () => {\n if (row._groupKey) {\n onToggle(row._groupKey);\n }\n };\n\n return (\n <div\n className=\"flex items-center bg-blue-50 dark:bg-blue-900/20 border-b border-gray-200 dark:border-gray-800 hover:bg-blue-100/70 cursor-pointer sticky left-0 z-20 overflow-hidden\"\n style={{\n minWidth: `${viewportWidth + (selectable ? SELECT_COL_WIDTH : 0)}px`,\n height: `${rowHeight}px`,\n }}\n onClick={handleToggle}\n role=\"button\"\n tabIndex={0}\n aria-expanded={isExpanded}\n onKeyDown={(e) => {\n if (e.key === \"Enter\" || e.key === \" \") {\n e.preventDefault();\n handleToggle();\n }\n }}\n >\n {selectable && (\n <div className=\"w-12 flex items-center justify-center\">\n {/* Empty space for checkbox column */}\n </div>\n )}\n\n <div className=\"flex items-center px-4 py-2 flex-1\">\n <div\n className=\"flex items-center mr-3\"\n style={{\n paddingLeft: `${(row as any)._groupLevel ? ((row as any)._groupLevel as number) * 16 : 0}px`,\n }}\n >\n {isExpanded ? (\n <ChevronDown className=\"w-4 h-4 text-gray-600\" />\n ) : (\n <ChevronRight className=\"w-4 h-4 text-gray-600\" />\n )}\n </div>\n\n <div className=\"flex items-center gap-2\">\n <span className=\"font-medium text-gray-900\">\n {(row as any)._groupColumnKey\n ? `${getHeaderLabel ? getHeaderLabel((row as any)._groupColumnKey) : (row as any)._groupColumnKey}: `\n : \"\"}\n {getValueLabel && (row as any)._groupColumnKey\n ? getValueLabel(\n (row as any)._groupColumnKey,\n (row as any)._groupValue,\n )\n : ((row as any)._groupValue ?? (row._groupKey || \"Unknown\"))}\n </span>\n <span className=\"text-sm text-gray-600 bg-gray-200/70 px-2 py-1 rounded-full\">\n {row._groupCount} {row._groupCount === 1 ? \"item\" : \"items\"}\n </span>\n </div>\n\n {renderGroupActions && (\n <div\n className=\"flex items-center px-4\"\n onClick={(e) => e.stopPropagation()}\n >\n {renderGroupActions({\n groupKey: row._groupKey || \"\",\n columnKey: (row as any)._groupColumnKey || \"\",\n groupValue: (row as any)._groupValue,\n rows: (row as any)._groupRows || [],\n count: row._groupCount || 0,\n level: (row as any)._groupLevel || 0,\n })}\n </div>\n )}\n </div>\n </div>\n );\n },\n);\n","import { Search, Database } from \"../icons\";\n\ninterface NoDataMessageProps {\n hasFilters?: boolean;\n hasData?: boolean;\n message?: string;\n}\n\nexport const NoDataMessage = ({\n hasFilters = false,\n hasData = true,\n message,\n}: NoDataMessageProps) => {\n const getMessage = () => {\n if (message) {\n return {\n title: message,\n description: \"\",\n icon: Database,\n };\n }\n\n if (!hasData) {\n return {\n title: \"No Data Available\",\n description: \"There is no data to display in this table.\",\n icon: Database,\n };\n }\n\n if (hasFilters) {\n return {\n title: \"No Results Found\",\n description:\n \"No data matches your current search criteria. Try adjusting your filters.\",\n icon: Search,\n };\n }\n\n return {\n title: \"No Data to Display\",\n description: \"There are no items to show at the moment.\",\n icon: Database,\n };\n };\n\n const { title, description, icon: Icon } = getMessage();\n\n return (\n <div className=\"flex flex-col items-center justify-center pt-16 pb-10 px-4 text-center\">\n <div className=\"w-16 h-16 bg-gray-100 dark:bg-gray-800 rounded-full flex items-center justify-center mb-4\">\n <Icon className=\"w-8 h-8 text-gray-400 dark:text-gray-500\" />\n </div>\n <h3 className=\"text-lg font-medium text-gray-900 dark:text-gray-100 mb-2\">\n {title}\n </h3>\n <p className=\"text-sm text-gray-500 dark:text-gray-400 max-w-md\">\n {description}\n </p>\n </div>\n );\n};\n","import { memo } from \"react\";\nimport {\n ChevronLeft,\n ChevronRight,\n ChevronsLeft,\n ChevronsRight,\n Loader2,\n Users,\n Eye,\n Database,\n} from \"../icons\";\nimport { PaginationConfig } from \"../types\";\n\ninterface PaginationControlsProps {\n paginationConfig: PaginationConfig;\n currentPage: number;\n isServerLoading: boolean;\n selectedRowsCount: number;\n totalDataLength: number;\n filteredDataLength?: number;\n paginationMode?: \"client\" | \"server\";\n onPageChange: (page: number, pageSize: number) => void;\n onPageSizeChange: (pageSize: number) => void;\n showNoDataMessage?: boolean;\n}\n\nconst PaginationControlsComponent = ({\n paginationConfig,\n currentPage,\n isServerLoading,\n selectedRowsCount,\n totalDataLength,\n filteredDataLength,\n paginationMode = \"client\",\n onPageChange,\n onPageSizeChange,\n}: PaginationControlsProps) => {\n // Helper function to get the effective total count\n const getEffectiveTotalCount = () => {\n if (paginationMode === \"server\") {\n return paginationConfig.totalRows || totalDataLength;\n }\n return filteredDataLength || totalDataLength;\n };\n\n // Helper function to get the current page range\n const getCurrentPageRange = () => {\n const effectiveTotal = paginationConfig.enabled\n ? paginationConfig.totalRows || totalDataLength\n : getEffectiveTotalCount();\n\n const start = paginationConfig.enabled\n ? Math.min(\n (currentPage - 1) * paginationConfig.pageSize + 1,\n effectiveTotal,\n )\n : 1;\n\n const end = paginationConfig.enabled\n ? Math.min(currentPage * paginationConfig.pageSize, effectiveTotal)\n : effectiveTotal;\n\n return { start, end, total: effectiveTotal };\n };\n\n const { start, end, total } = getCurrentPageRange();\n const isFiltered =\n paginationMode === \"client\" &&\n filteredDataLength &&\n filteredDataLength !== totalDataLength;\n\n return (\n <div className=\"px-3 sm:px-6 py-2 border-t border-gray-200 dark:border-gray-700 bg-linear-to-r from-white via-gray-50 to-white dark:from-gray-900 dark:via-gray-800 dark:to-gray-900\">\n <div className=\"flex flex-col xl:flex-row gap-4 xl:gap-6 xl:justify-between xl:items-center\">\n {/* Left Section: Stats and Page Size */}\n <div className=\"flex flex-col sm:flex-row gap-3 sm:gap-4 items-start sm:items-center\">\n {/* Stats Section */}\n <div className=\"flex flex-wrap items-center gap-2 sm:gap-3\">\n {/* Total Count Badge - Only when pagination is disabled */}\n {!paginationConfig.enabled && (\n <div className=\"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-semibold bg-linear-to-r from-blue-500 to-blue-600 text-white shadow-lg ring-2 ring-blue-500/20\">\n <Database className=\"w-3 h-3\" />\n <span className=\"font-bold\">\n {total.toLocaleString()} {total === 1 ? \"Record\" : \"Records\"}\n </span>\n {isFiltered && (\n <span className=\"text-blue-100 font-normal\">\n (of {totalDataLength.toLocaleString()})\n </span>\n )}\n </div>\n )}\n\n {/* Selected Count Badge */}\n {selectedRowsCount > 0 && (\n <div className=\"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-semibold bg-linear-to-r from-primary to-primary text-white shadow-lg ring-2 ring-primary/20\">\n <Users className=\"w-3 h-3\" />\n <span>{selectedRowsCount.toLocaleString()} selected</span>\n </div>\n )}\n\n {/* Filtered Indicator */}\n {isFiltered && (\n <div className=\"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium bg-linear-to-r from-warning/10 to-warning/5 text-warning border border-warning/20\">\n <Eye className=\"w-3 h-3\" />\n <span>Filtered</span>\n </div>\n )}\n\n {/* Page Range Info (Desktop) */}\n {paginationConfig.enabled && (\n <div className=\"hidden sm:block text-sm text-gray-600 dark:text-gray-400 font-medium\">\n <span className=\"inline-flex items-center gap-1\">\n <span>Showing</span>\n <span className=\"px-2 py-0.5 bg-gray-100 dark:bg-gray-700 rounded-md font-bold text-gray-900 dark:text-gray-100\">\n {start.toLocaleString()}\n </span>\n <span>-</span>\n <span className=\"px-2 py-0.5 bg-gray-100 dark:bg-gray-700 rounded-md font-bold text-gray-900 dark:text-gray-100\">\n {end.toLocaleString()}\n </span>\n <span>of {total.toLocaleString()}</span>\n </span>\n </div>\n )}\n </div>\n\n {/* Page Size Selector */}\n {paginationConfig.enabled &&\n paginationConfig.showPageSizeSelector && (\n <div className=\"flex items-center gap-2\">\n <span className=\"text-sm font-medium text-gray-700 dark:text-gray-300 whitespace-nowrap\">\n Rows per page:\n </span>\n <select\n value={paginationConfig.pageSize}\n onChange={(e) => onPageSizeChange(Number(e.target.value))}\n className=\"border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 rounded-xl px-3 py-1 text-sm font-medium focus:ring-2 focus:ring-primary focus:border-primary disabled:opacity-50 disabled:cursor-not-allowed shadow-sm transition-all duration-200 hover:border-gray-400 dark:hover:border-gray-500\"\n disabled={isServerLoading}\n >\n {paginationConfig.pageSizeOptions?.map((size) => (\n <option key={size} value={size}>\n {size}\n </option>\n ))}\n </select>\n </div>\n )}\n </div>\n\n {/* Right Section: Pagination Controls */}\n {paginationConfig.enabled && (\n <div className=\"flex flex-col sm:flex-row items-start sm:items-center gap-3 sm:gap-4\">\n {/* Loading Indicator */}\n {isServerLoading && (\n <div className=\"flex items-center gap-2 px-3 py-1.5 bg-blue-50 dark:bg-blue-900/20 rounded-full border border-blue-200 dark:border-blue-800\">\n <Loader2 className=\"w-4 h-4 animate-spin text-primary\" />\n <span className=\"text-sm font-medium text-primary\">\n Loading...\n </span>\n </div>\n )}\n\n {/* Mobile Page Info */}\n <div className=\"sm:hidden text-sm text-gray-600 dark:text-gray-400 font-medium\">\n <div className=\"flex flex-col gap-1\">\n <span className=\"inline-flex items-center gap-1\">\n <span>Page</span>\n <span className=\"px-2 py-0.5 bg-gray-100 dark:bg-gray-700 rounded-md font-bold text-gray-900 dark:text-gray-100\">\n {currentPage.toLocaleString()}\n </span>\n <span>of</span>\n <span className=\"px-2 py-0.5 bg-gray-100 dark:bg-gray-700 rounded-md font-bold text-gray-900 dark:text-gray-100\">\n {paginationConfig.totalPages.toLocaleString()}\n </span>\n </span>\n <span className=\"text-xs text-gray-500 dark:text-gray-500\">\n {start.toLocaleString()} - {end.toLocaleString()} of{\" \"}\n {total.toLocaleString()}\n </span>\n </div>\n </div>\n\n {/* Pagination Navigation */}\n <div className=\"flex items-center gap-1 sm:gap-2\">\n {/* First Page Button */}\n <button\n onClick={() => onPageChange(1, paginationConfig.pageSize)}\n disabled={currentPage === 1 || isServerLoading}\n className=\"inline-flex items-center justify-center w-8 h-8 rounded-full border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer text-gray-600 dark:text-gray-300 hover:text-gray-900 dark:hover:text-gray-100 transition-all duration-200 hover:border-gray-400 dark:hover:border-gray-500 hover:shadow-md focus:ring-2 focus:ring-primary/20 focus:border-primary\"\n title=\"First page\"\n aria-label=\"Go to first page\"\n >\n <ChevronsLeft className=\"w-3.5 h-3.5\" />\n </button>\n\n {/* Previous Page Button */}\n <button\n onClick={() =>\n onPageChange(currentPage - 1, paginationConfig.pageSize)\n }\n disabled={currentPage === 1 || isServerLoading}\n className=\"inline-flex items-center justify-center w-8 h-8 rounded-full border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer text-gray-600 dark:text-gray-300 hover:text-gray-900 dark:hover:text-gray-100 transition-all duration-200 hover:border-gray-400 dark:hover:border-gray-500 hover:shadow-md focus:ring-2 focus:ring-primary/20 focus:border-primary\"\n title=\"Previous page\"\n aria-label=\"Go to previous page\"\n >\n <ChevronLeft className=\"w-3.5 h-3.5\" />\n </button>\n\n {/* Mobile Page Selector */}\n <div className=\"sm:hidden\">\n <select\n value={currentPage}\n onChange={(e) =>\n onPageChange(\n Number(e.target.value),\n paginationConfig.pageSize,\n )\n }\n className=\"border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 rounded-xl px-3 py-2 text-sm font-medium focus:ring-2 focus:ring-primary focus:border-primary disabled:opacity-50 disabled:cursor-not-allowed shadow-sm min-w-[80px]\"\n disabled={isServerLoading}\n aria-label=\"Select page\"\n >\n {Array.from(\n { length: paginationConfig.totalPages },\n (_, i) => i + 1,\n ).map((page) => (\n <option key={page} value={page}>\n {page}\n </option>\n ))}\n </select>\n </div>\n\n {/* Desktop Page Numbers */}\n <div className=\"hidden sm:flex items-center gap-1 mx-2\">\n {(() => {\n const pages = [];\n const totalPages = paginationConfig.totalPages;\n const current = currentPage;\n const maxVisible =\n typeof window !== \"undefined\" && window.innerWidth >= 768\n ? 7\n : 5;\n\n if (totalPages <= maxVisible) {\n for (let i = 1; i <= totalPages; i++) {\n pages.push(i);\n }\n } else {\n const delta = Math.floor(maxVisible / 2) - 1;\n if (current <= delta + 1) {\n for (let i = 1; i <= maxVisible - 2; i++) pages.push(i);\n pages.push(\"ellipsis1\");\n pages.push(totalPages);\n } else if (current >= totalPages - delta) {\n pages.push(1);\n pages.push(\"ellipsis1\");\n for (\n let i = totalPages - (maxVisible - 3);\n i <= totalPages;\n i++\n )\n pages.push(i);\n } else {\n pages.push(1);\n pages.push(\"ellipsis1\");\n for (let i = current - delta; i <= current + delta; i++)\n pages.push(i);\n pages.push(\"ellipsis2\");\n pages.push(totalPages);\n }\n }\n\n return pages.map((page) => {\n if (typeof page === \"string\") {\n return (\n <div\n key={page}\n className=\"flex items-center justify-center w-8 h-8 text-gray-400 dark:text-gray-500 select-none\"\n aria-hidden=\"true\"\n >\n <span className=\"text-lg leading-none\">⋯</span>\n </div>\n );\n }\n\n const isActive = page === current;\n return (\n <button\n key={page}\n onClick={() =>\n onPageChange(page, paginationConfig.pageSize)\n }\n disabled={isServerLoading}\n className={`inline-flex items-center justify-center w-8 h-8 rounded-full text-sm font-semibold transition-all duration-200 focus:ring-2 focus:ring-primary/20 focus:outline-none cursor-pointer ${\n isActive\n ? \"bg-linear-to-r from-primary to-primary text-white shadow-lg ring-2 ring-primary/20 transform scale-105 z-10 relative bg-blue-500\"\n : \"border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 hover:border-gray-400 dark:hover:border-gray-500 hover:shadow-md disabled:opacity-40 disabled:cursor-not-allowed\"\n }`}\n aria-label={`Go to page ${page}`}\n aria-current={isActive ? \"page\" : undefined}\n >\n {page}\n </button>\n );\n });\n })()}\n </div>\n\n {/* Next Page Button */}\n <button\n onClick={() =>\n onPageChange(currentPage + 1, paginationConfig.pageSize)\n }\n disabled={\n currentPage === paginationConfig.totalPages || isServerLoading\n }\n className=\"inline-flex items-center justify-center w-8 h-8 rounded-full border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer text-gray-600 dark:text-gray-300 hover:text-gray-900 dark:hover:text-gray-100 transition-all duration-200 hover:border-gray-400 dark:hover:border-gray-500 hover:shadow-md focus:ring-2 focus:ring-primary/20 focus:border-primary\"\n title=\"Next page\"\n aria-label=\"Go to next page\"\n >\n <ChevronRight className=\"w-3.5 h-3.5\" />\n </button>\n\n {/* Last Page Button */}\n <button\n onClick={() =>\n onPageChange(\n paginationConfig.totalPages,\n paginationConfig.pageSize,\n )\n }\n disabled={\n currentPage === paginationConfig.totalPages || isServerLoading\n }\n className=\"inline-flex items-center justify-center w-8 h-8 rounded-full border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer text-gray-600 dark:text-gray-300 hover:text-gray-900 dark:hover:text-gray-100 transition-all duration-200 hover:border-gray-400 dark:hover:border-gray-500 hover:shadow-md focus:ring-2 focus:ring-primary/20 focus:border-primary\"\n title=\"Last page\"\n aria-label=\"Go to last page\"\n >\n <ChevronsRight className=\"w-3.5 h-3.5\" />\n </button>\n </div>\n </div>\n )}\n </div>\n </div>\n );\n};\n\nPaginationControlsComponent.displayName = \"PaginationControls\";\nexport const PaginationControls = /*#__PURE__*/ memo(\n PaginationControlsComponent,\n);\n","import { useState, useRef, useEffect, ChangeEvent } from \"react\";\nimport { ChevronDown, Check } from \"../icons\";\n\ninterface Option {\n label: string;\n value: string;\n}\n\ninterface CustomSelectProps {\n options: Option[];\n value?: string;\n placeholder?: string;\n onChange: (value: string) => void;\n searchable?: boolean;\n className?: string;\n}\n\nexport const CustomSelect = ({\n options,\n value,\n placeholder = \"Select an option...\",\n onChange,\n searchable = true,\n className = \"\",\n}: CustomSelectProps) => {\n const [isOpen, setIsOpen] = useState(false);\n const [searchTerm, setSearchTerm] = useState(\"\");\n const [highlightedIndex, setHighlightedIndex] = useState(-1);\n\n const containerRef = useRef<HTMLDivElement>(null);\n const inputRef = useRef<HTMLInputElement>(null);\n const listRef = useRef<HTMLUListElement>(null);\n\n const selectedOption = options.find((option) => option.value === value);\n\n const filteredOptions = searchable\n ? options.filter((option) =>\n option.label?.toLowerCase()?.includes(searchTerm?.toLowerCase()),\n )\n : options;\n\n // Close dropdown when clicking outside\n useEffect(() => {\n const handleClickOutside = (event: MouseEvent) => {\n if (\n containerRef.current &&\n !containerRef.current.contains(event.target as Node)\n ) {\n setIsOpen(false);\n setSearchTerm(\"\");\n setHighlightedIndex(-1);\n }\n };\n\n document.addEventListener(\"mousedown\", handleClickOutside);\n return () => document.removeEventListener(\"mousedown\", handleClickOutside);\n }, []);\n\n // Handle keyboard navigation\n useEffect(() => {\n const handleKeyDown = (event: KeyboardEvent) => {\n if (!isOpen) return;\n\n switch (event.key) {\n case \"ArrowDown\":\n event.preventDefault();\n setHighlightedIndex((prev) =>\n prev < filteredOptions.length - 1 ? prev + 1 : 0,\n );\n break;\n case \"ArrowUp\":\n event.preventDefault();\n setHighlightedIndex((prev) =>\n prev > 0 ? prev - 1 : filteredOptions.length - 1,\n );\n break;\n case \"Enter\":\n event.preventDefault();\n if (highlightedIndex >= 0 && filteredOptions[highlightedIndex]) {\n handleSelect(filteredOptions[highlightedIndex].value);\n }\n break;\n case \"Escape\":\n setIsOpen(false);\n setSearchTerm(\"\");\n setHighlightedIndex(-1);\n break;\n }\n };\n\n if (isOpen) {\n document.addEventListener(\"keydown\", handleKeyDown);\n return () => document.removeEventListener(\"keydown\", handleKeyDown);\n }\n }, [isOpen, highlightedIndex, filteredOptions]);\n\n // Scroll highlighted option into view\n useEffect(() => {\n if (highlightedIndex >= 0 && listRef.current) {\n const highlightedElement = listRef.current.children[\n highlightedIndex\n ] as HTMLElement;\n if (highlightedElement) {\n highlightedElement.scrollIntoView({\n block: \"nearest\",\n behavior: \"smooth\",\n });\n }\n }\n }, [highlightedIndex]);\n\n const handleSelect = (optionValue: string) => {\n onChange(optionValue);\n setIsOpen(false);\n setSearchTerm(\"\");\n setHighlightedIndex(-1);\n };\n\n const handleInputClick = () => {\n setIsOpen(!isOpen);\n if (searchable && !isOpen) {\n setTimeout(() => inputRef.current?.focus(), 0);\n }\n };\n\n const handleInputChange = (e: ChangeEvent<HTMLInputElement>) => {\n setSearchTerm(e.target.value);\n setHighlightedIndex(-1);\n if (!isOpen) setIsOpen(true);\n };\n\n return (\n <div className={`relative ${className}`} ref={containerRef}>\n <div\n className={`relative w-full cursor-pointer border border-gray-300 rounded-lg bg-white transition-all duration-200 ${\n isOpen\n ? \"ring-2 ring-blue-500 border-blue-500\"\n : \"hover:border-gray-400 focus-within:ring-2 focus-within:ring-blue-500 focus-within:border-blue-500\"\n }`}\n onClick={handleInputClick}\n >\n <div className=\"flex items-center justify-between px-3 py-2.5\">\n {searchable && isOpen ? (\n <input\n ref={inputRef}\n type=\"text\"\n className=\"flex-1 outline-none text-sm bg-transparent\"\n placeholder={`Search ${placeholder?.toLowerCase()}...`}\n value={searchTerm}\n onChange={handleInputChange}\n onClick={(e) => e.stopPropagation()}\n />\n ) : (\n <span\n className={`flex-1 text-sm truncate ${\n selectedOption ? \"text-gray-900\" : \"text-gray-500\"\n }`}\n >\n {selectedOption ? selectedOption.label : placeholder}\n </span>\n )}\n\n <ChevronDown\n className={`w-4 h-4 text-gray-400 transition-transform duration-200 ${\n isOpen ? \"rotate-180\" : \"\"\n }`}\n />\n </div>\n </div>\n\n {/* Dropdown List */}\n {isOpen && (\n <div className=\"absolute top-full left-0 right-0 mt-1 bg-white border border-gray-200 rounded-lg shadow-lg z-99999 max-h-80 overflow-hidden\">\n {filteredOptions.length > 0 ? (\n <ul ref={listRef} className=\"py-1 overflow-y-auto max-h-80\">\n {filteredOptions.map((option, index) => (\n <li\n key={option.value}\n className={`px-3 py-2 text-sm cursor-pointer flex items-center justify-between transition-colors ${\n index === highlightedIndex\n ? \"bg-blue-50 text-blue-700\"\n : \"text-gray-700 hover:bg-gray-50\"\n }`}\n onClick={() => handleSelect(option.value)}\n onMouseEnter={() => setHighlightedIndex(index)}\n >\n <span className=\"truncate\">{option.label}</span>\n {selectedOption?.value === option.value && (\n <Check className=\"w-4 h-4 text-blue-600 shrink-0 ml-2\" />\n )}\n </li>\n ))}\n </ul>\n ) : (\n <div className=\"px-3 py-2 text-sm text-gray-500 text-center\">\n No options found\n </div>\n )}\n </div>\n )}\n </div>\n );\n};\n","import { useState, useEffect } from \"react\";\nimport { X, Search } from \"../icons\";\nimport { CustomSelect } from \"./CustomSelect\";\nimport { DatePicker } from \"./ui/DatePicker\";\nimport { toYMD, fromYMD, toDMY } from \"../utils/dateUtils\";\n\ninterface ColumnFilterSelectorProps {\n columns: Array<{\n key: string;\n header: string;\n filterable?: {\n type?: string;\n options?: Array<{ label: string; value: string | number }>;\n placeholder?: string;\n };\n }>;\n columnFilters: Record<string, any>;\n onColumnFilter?: (columnKey: string, filter: any) => void;\n}\n\nexport const ColumnFilterSelector = ({\n columns,\n columnFilters,\n onColumnFilter,\n}: ColumnFilterSelectorProps) => {\n // Filter out columns that don't have filterable property\n const filterableColumns = columns.filter((col) => col.filterable);\n\n const [selectedColumn, setSelectedColumn] = useState<string>(\n filterableColumns.length > 0 ? filterableColumns[0].key : \"\",\n );\n // Multiselect search text (shared; reset on column change)\n const [multiSearch, setMultiSearch] = useState(\"\");\n const handleColumnSelect = (columnKey: string) => {\n setSelectedColumn(columnKey);\n };\n\n const handleActiveFilterClick = (columnKey: string) => {\n setSelectedColumn(columnKey);\n // Optionally, could add focus management here if the select is focusable via ref\n };\n\n // Convert columns to options for CustomSelect\n const columnOptions = filterableColumns.map((col) => ({\n label: col.header,\n value: col.key,\n }));\n\n const selectedColumnData = filterableColumns.find(\n (col) => col.key === selectedColumn,\n );\n\n // Reset multiselect search whenever the selected column changes\n useEffect(() => {\n setMultiSearch(\"\");\n }, [selectedColumn]);\n\n const renderFilterInput = () => {\n if (!selectedColumnData) return null;\n\n const filterType = selectedColumnData.filterable?.type || \"text\";\n const currentFilter = columnFilters[selectedColumn];\n\n if (\n filterType === \"multiselect\" &&\n selectedColumnData.filterable?.options\n ) {\n const lowered = multiSearch.toLowerCase();\n const filteredOptions = lowered\n ? selectedColumnData.filterable.options.filter(\n (opt) =>\n opt.label.toLowerCase().includes(lowered) ||\n String(opt.value).toLowerCase().includes(lowered),\n )\n : selectedColumnData.filterable.options;\n return (\n <div className=\"mt-3\">\n <label className=\"text-sm font-medium text-gray-700 mb-2 block\">\n Filter by {selectedColumnData.header}\n </label>\n <div className=\"relative mb-2\">\n <Search className=\"w-4 h-4 text-gray-400 absolute left-2 top-1/2 -translate-y-1/2\" />\n <input\n type=\"text\"\n value={multiSearch}\n onChange={(e) => setMultiSearch(e.target.value)}\n placeholder=\"Search options...\"\n className=\"w-full pl-8 pr-2 py-1.5 border border-gray-300 rounded-md text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500\"\n />\n {multiSearch && (\n <button\n type=\"button\"\n onClick={() => setMultiSearch(\"\")}\n className=\"absolute right-2 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600\"\n title=\"Clear search\"\n >\n <X className=\"w-3 h-3\" />\n </button>\n )}\n </div>\n <div className=\"max-h-32 overflow-y-auto border border-gray-300 rounded-md p-2 bg-white\">\n {filteredOptions.length === 0 && (\n <div className=\"text-xs text-gray-500 px-1 py-1\">No matches</div>\n )}\n {filteredOptions.map((option) => {\n const selectedValues = currentFilter?.value || [];\n const isSelected =\n Array.isArray(selectedValues) &&\n selectedValues.includes(option.value);\n return (\n <label\n key={option.value}\n className=\"flex items-center gap-2 py-1 hover:bg-gray-50 cursor-pointer\"\n >\n <input\n type=\"checkbox\"\n className=\"rounded border-gray-300 text-blue-600 focus:ring-blue-500\"\n checked={isSelected}\n onChange={(e) => {\n const currentValues = currentFilter?.value || [];\n let newValues;\n if (e.target.checked) {\n newValues = [...currentValues, option.value];\n } else {\n newValues = currentValues.filter(\n (v: any) => v !== option.value,\n );\n }\n if (newValues.length > 0) {\n onColumnFilter?.(selectedColumn, {\n type: \"multiselect\",\n value: newValues,\n operator: \"in\",\n });\n } else {\n onColumnFilter?.(selectedColumn, null);\n }\n }}\n />\n <span className=\"text-sm\">{option.label}</span>\n </label>\n );\n })}\n </div>\n </div>\n );\n }\n\n if (filterType === \"select\" && selectedColumnData.filterable?.options) {\n const selectOptions = [\n { label: `All ${selectedColumnData.header}`, value: \"\" },\n ...selectedColumnData.filterable.options.map((opt) => ({\n label: opt.label,\n value: String(opt.value),\n })),\n ];\n\n return (\n <div className=\"mt-3\">\n <label className=\"text-sm font-medium text-gray-700 mb-2 block\">\n Filter by {selectedColumnData.header}\n </label>\n <CustomSelect\n options={selectOptions}\n value={currentFilter?.value || \"\"}\n placeholder={`Select ${selectedColumnData.header.toLowerCase()}...`}\n onChange={(value) => {\n if (value) {\n onColumnFilter?.(selectedColumn, {\n type: \"select\",\n value: value,\n operator: \"between\",\n });\n } else {\n onColumnFilter?.(selectedColumn, null);\n }\n }}\n searchable={true}\n />\n </div>\n );\n }\n\n if (filterType === \"date\") {\n const parseInput = (val: any) => {\n if (!val) return null;\n if (val instanceof Date && !isNaN(val.getTime())) return val;\n // Accept both stored yyyy-MM-dd and other ISO/date strings\n const direct = fromYMD(String(val));\n if (!isNaN(direct.getTime())) return direct;\n const asDate = new Date(val);\n return isNaN(asDate.getTime()) ? null : asDate;\n };\n\n const primaryDate = parseInput(currentFilter?.value);\n const secondDate = parseInput(currentFilter?.secondValue);\n const effectiveOperator = currentFilter?.operator || \"between\";\n\n return (\n <div className=\"mt-3\">\n <label className=\"text-sm font-medium text-gray-700 mb-2 block\">\n Filter by {selectedColumnData.header}\n </label>\n <div className=\"mb-3\">\n <CustomSelect\n key={`date-operator-${selectedColumn}-${effectiveOperator}`}\n options={[\n { label: \"Between Dates\", value: \"between\" },\n { label: \"On Date\", value: \"equals\" },\n ]}\n value={effectiveOperator}\n placeholder=\"Select date filter...\"\n onChange={(operator) => {\n onColumnFilter?.(selectedColumn, {\n type: \"date\",\n value: currentFilter?.value || \"\",\n operator: operator as any,\n secondValue: currentFilter?.secondValue || \"\",\n });\n }}\n searchable={false}\n />\n </div>\n <div className=\"flex items-end gap-2\">\n <div className=\"flex-1 min-w-37.5\">\n <DatePicker\n name=\"column_filter_start\"\n label={effectiveOperator === \"between\" ? \"Start Date\" : \"Date\"}\n value={primaryDate ? toYMD(primaryDate) : null}\n onChange={(newValue) => {\n if (newValue) {\n const stored = toYMD(fromYMD(newValue));\n onColumnFilter?.(selectedColumn, {\n type: \"date\",\n value: stored,\n operator: effectiveOperator,\n secondValue: currentFilter?.secondValue || null,\n });\n } else {\n onColumnFilter?.(selectedColumn, null);\n }\n }}\n className=\"w-full\"\n />\n </div>\n {effectiveOperator === \"between\" && (\n <div className=\"flex-1 min-w-37.5\">\n <DatePicker\n name=\"column_filter_end\"\n label=\"End Date\"\n value={secondDate ? toYMD(secondDate) : null}\n onChange={(newValue) => {\n if (newValue && currentFilter) {\n const stored = toYMD(fromYMD(newValue));\n onColumnFilter?.(selectedColumn, {\n ...currentFilter,\n secondValue: stored,\n });\n }\n }}\n className=\"w-full\"\n />\n </div>\n )}\n </div>\n </div>\n );\n }\n\n // Default text input\n return (\n <div className=\"mt-3\">\n <label className=\"text-sm font-medium text-gray-700 mb-2 block\">\n Filter by {selectedColumnData.header}\n </label>\n <>\n <input\n type=\"text\"\n placeholder={\n selectedColumnData.filterable?.placeholder ||\n `Filter ${selectedColumnData.header.toLowerCase()}...`\n }\n className=\"w-full px-3 py-2.5 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-200\"\n value={currentFilter?.value || \"\"}\n onChange={(e) => {\n if (e.target.value) {\n onColumnFilter?.(selectedColumn, {\n type: \"text\",\n value: e.target.value,\n operator: \"contains\",\n });\n } else {\n onColumnFilter?.(selectedColumn, null);\n }\n }}\n />\n\n {/* Filter Operator Selector for text filters */}\n {currentFilter && (\n <div className=\"mt-2\">\n <CustomSelect\n options={[\n { label: \"Contains\", value: \"contains\" },\n { label: \"Equals\", value: \"equals\" },\n { label: \"Starts with\", value: \"startsWith\" },\n { label: \"Ends with\", value: \"endsWith\" },\n ]}\n value={currentFilter?.operator || \"contains\"}\n placeholder=\"Select operator...\"\n onChange={(operator) => {\n if (currentFilter) {\n onColumnFilter?.(selectedColumn, {\n ...currentFilter,\n operator: operator as any,\n });\n }\n }}\n searchable={false}\n />\n </div>\n )}\n </>\n </div>\n );\n };\n\n return (\n <div className=\"space-y-4\">\n {/* Column Selection Dropdown */}\n <div>\n <label className=\"text-sm font-medium text-gray-700 mb-2 block\">\n Select Column to Filter\n </label>\n <CustomSelect\n options={columnOptions}\n value={selectedColumn}\n placeholder=\"Choose a column...\"\n onChange={handleColumnSelect}\n searchable={true}\n />\n </div>\n\n {/* Filter Input for Selected Column */}\n {selectedColumn && renderFilterInput()}\n\n {/* Active Filters Display */}\n {Object.keys(columnFilters).length > 0 && (\n <div className=\"mt-4\">\n <label className=\"text-sm font-medium text-gray-700 mb-2 block\">\n Active Filters\n </label>\n <div className=\"space-y-2\">\n {Object.entries(columnFilters).map(([columnKey, filter]) => {\n const column = filterableColumns.find(\n (col) => col.key === columnKey,\n );\n if (!column) return null;\n\n return (\n <div\n key={columnKey}\n className=\"flex items-center justify-between bg-blue-50 border border-blue-200 rounded-md px-3 py-2 cursor-pointer hover:bg-blue-100\"\n role=\"button\"\n title={`Edit filter for ${column.header}`}\n onClick={() => handleActiveFilterClick(columnKey)}\n >\n <div className=\"flex-1\">\n <span className=\"text-sm font-medium text-blue-900\">\n {column.header}:\n </span>\n <span className=\"text-sm text-blue-700 ml-1\">\n {(() => {\n if (Array.isArray(filter.value)) {\n return `${filter.value.length} selected`;\n }\n\n // Handle date filters with operators\n if (filter.type === \"date\") {\n const formatDate = (dateValue: any) => {\n try {\n if (!dateValue) return \"\";\n if (\n dateValue instanceof Date &&\n !isNaN(dateValue.getTime())\n ) {\n return toDMY(dateValue);\n }\n if (typeof dateValue === \"string\") {\n const parsed = fromYMD(dateValue);\n if (!isNaN(parsed.getTime()))\n return toDMY(parsed);\n const asDate = new Date(dateValue);\n if (!isNaN(asDate.getTime()))\n return toDMY(asDate);\n }\n return String(dateValue);\n } catch {\n return String(dateValue ?? \"\");\n }\n };\n\n const operatorLabels: Record<string, string> = {\n equals: \"On\",\n gt: \"After\",\n gte: \"On or After\",\n lt: \"Before\",\n lte: \"On or Before\",\n between: \"Between\",\n };\n\n const operatorLabel =\n operatorLabels[filter.operator as string] || \"On\";\n\n if (\n filter.operator === \"between\" &&\n filter.secondValue\n ) {\n return `${operatorLabel} ${formatDate(\n filter.value,\n )} - ${formatDate(filter.secondValue)}`;\n }\n\n return `${operatorLabel} ${formatDate(filter.value)}`;\n }\n\n return filter.value;\n })()}\n </span>\n </div>\n <button\n onClick={(e) => {\n e.stopPropagation();\n onColumnFilter?.(columnKey, null);\n }}\n className=\"text-blue-400 hover:text-red-500 transition-colors\"\n title=\"Clear filter\"\n >\n <X className=\"w-4 h-4\" />\n </button>\n </div>\n );\n })}\n </div>\n </div>\n )}\n </div>\n );\n};\n","function hasWindow() {\n return typeof window !== 'undefined';\n}\nfunction getNodeName(node) {\n if (isNode(node)) {\n return (node.nodeName || '').toLowerCase();\n }\n // Mocked nodes in testing environments may not be instances of Node. By\n // returning `#document` an infinite loop won't occur.\n // https://github.com/floating-ui/floating-ui/issues/2317\n return '#document';\n}\nfunction getWindow(node) {\n var _node$ownerDocument;\n return (node == null || (_node$ownerDocument = node.ownerDocument) == null ? void 0 : _node$ownerDocument.defaultView) || window;\n}\nfunction getDocumentElement(node) {\n var _ref;\n return (_ref = (isNode(node) ? node.ownerDocument : node.document) || window.document) == null ? void 0 : _ref.documentElement;\n}\nfunction isNode(value) {\n if (!hasWindow()) {\n return false;\n }\n return value instanceof Node || value instanceof getWindow(value).Node;\n}\nfunction isElement(value) {\n if (!hasWindow()) {\n return false;\n }\n return value instanceof Element || value instanceof getWindow(value).Element;\n}\nfunction isHTMLElement(value) {\n if (!hasWindow()) {\n return false;\n }\n return value instanceof HTMLElement || value instanceof getWindow(value).HTMLElement;\n}\nfunction isShadowRoot(value) {\n if (!hasWindow() || typeof ShadowRoot === 'undefined') {\n return false;\n }\n return value instanceof ShadowRoot || value instanceof getWindow(value).ShadowRoot;\n}\nconst invalidOverflowDisplayValues = /*#__PURE__*/new Set(['inline', 'contents']);\nfunction isOverflowElement(element) {\n const {\n overflow,\n overflowX,\n overflowY,\n display\n } = getComputedStyle(element);\n return /auto|scroll|overlay|hidden|clip/.test(overflow + overflowY + overflowX) && !invalidOverflowDisplayValues.has(display);\n}\nconst tableElements = /*#__PURE__*/new Set(['table', 'td', 'th']);\nfunction isTableElement(element) {\n return tableElements.has(getNodeName(element));\n}\nconst topLayerSelectors = [':popover-open', ':modal'];\nfunction isTopLayer(element) {\n return topLayerSelectors.some(selector => {\n try {\n return element.matches(selector);\n } catch (_e) {\n return false;\n }\n });\n}\nconst transformProperties = ['transform', 'translate', 'scale', 'rotate', 'perspective'];\nconst willChangeValues = ['transform', 'translate', 'scale', 'rotate', 'perspective', 'filter'];\nconst containValues = ['paint', 'layout', 'strict', 'content'];\nfunction isContainingBlock(elementOrCss) {\n const webkit = isWebKit();\n const css = isElement(elementOrCss) ? getComputedStyle(elementOrCss) : elementOrCss;\n\n // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block\n // https://drafts.csswg.org/css-transforms-2/#individual-transforms\n return transformProperties.some(value => css[value] ? css[value] !== 'none' : false) || (css.containerType ? css.containerType !== 'normal' : false) || !webkit && (css.backdropFilter ? css.backdropFilter !== 'none' : false) || !webkit && (css.filter ? css.filter !== 'none' : false) || willChangeValues.some(value => (css.willChange || '').includes(value)) || containValues.some(value => (css.contain || '').includes(value));\n}\nfunction getContainingBlock(element) {\n let currentNode = getParentNode(element);\n while (isHTMLElement(currentNode) && !isLastTraversableNode(currentNode)) {\n if (isContainingBlock(currentNode)) {\n return currentNode;\n } else if (isTopLayer(currentNode)) {\n return null;\n }\n currentNode = getParentNode(currentNode);\n }\n return null;\n}\nfunction isWebKit() {\n if (typeof CSS === 'undefined' || !CSS.supports) return false;\n return CSS.supports('-webkit-backdrop-filter', 'none');\n}\nconst lastTraversableNodeNames = /*#__PURE__*/new Set(['html', 'body', '#document']);\nfunction isLastTraversableNode(node) {\n return lastTraversableNodeNames.has(getNodeName(node));\n}\nfunction getComputedStyle(element) {\n return getWindow(element).getComputedStyle(element);\n}\nfunction getNodeScroll(element) {\n if (isElement(element)) {\n return {\n scrollLeft: element.scrollLeft,\n scrollTop: element.scrollTop\n };\n }\n return {\n scrollLeft: element.scrollX,\n scrollTop: element.scrollY\n };\n}\nfunction getParentNode(node) {\n if (getNodeName(node) === 'html') {\n return node;\n }\n const result =\n // Step into the shadow DOM of the parent of a slotted node.\n node.assignedSlot ||\n // DOM Element detected.\n node.parentNode ||\n // ShadowRoot detected.\n isShadowRoot(node) && node.host ||\n // Fallback.\n getDocumentElement(node);\n return isShadowRoot(result) ? result.host : result;\n}\nfunction getNearestOverflowAncestor(node) {\n const parentNode = getParentNode(node);\n if (isLastTraversableNode(parentNode)) {\n return node.ownerDocument ? node.ownerDocument.body : node.body;\n }\n if (isHTMLElement(parentNode) && isOverflowElement(parentNode)) {\n return parentNode;\n }\n return getNearestOverflowAncestor(parentNode);\n}\nfunction getOverflowAncestors(node, list, traverseIframes) {\n var _node$ownerDocument2;\n if (list === void 0) {\n list = [];\n }\n if (traverseIframes === void 0) {\n traverseIframes = true;\n }\n const scrollableAncestor = getNearestOverflowAncestor(node);\n const isBody = scrollableAncestor === ((_node$ownerDocument2 = node.ownerDocument) == null ? void 0 : _node$ownerDocument2.body);\n const win = getWindow(scrollableAncestor);\n if (isBody) {\n const frameElement = getFrameElement(win);\n return list.concat(win, win.visualViewport || [], isOverflowElement(scrollableAncestor) ? scrollableAncestor : [], frameElement && traverseIframes ? getOverflowAncestors(frameElement) : []);\n }\n return list.concat(scrollableAncestor, getOverflowAncestors(scrollableAncestor, [], traverseIframes));\n}\nfunction getFrameElement(win) {\n return win.parent && Object.getPrototypeOf(win.parent) ? win.frameElement : null;\n}\n\nexport { getComputedStyle, getContainingBlock, getDocumentElement, getFrameElement, getNearestOverflowAncestor, getNodeName, getNodeScroll, getOverflowAncestors, getParentNode, getWindow, isContainingBlock, isElement, isHTMLElement, isLastTraversableNode, isNode, isOverflowElement, isShadowRoot, isTableElement, isTopLayer, isWebKit };\n","/**\n * Custom positioning reference element.\n * @see https://floating-ui.com/docs/virtual-elements\n */\n\nconst sides = ['top', 'right', 'bottom', 'left'];\nconst alignments = ['start', 'end'];\nconst placements = /*#__PURE__*/sides.reduce((acc, side) => acc.concat(side, side + \"-\" + alignments[0], side + \"-\" + alignments[1]), []);\nconst min = Math.min;\nconst max = Math.max;\nconst round = Math.round;\nconst floor = Math.floor;\nconst createCoords = v => ({\n x: v,\n y: v\n});\nconst oppositeSideMap = {\n left: 'right',\n right: 'left',\n bottom: 'top',\n top: 'bottom'\n};\nconst oppositeAlignmentMap = {\n start: 'end',\n end: 'start'\n};\nfunction clamp(start, value, end) {\n return max(start, min(value, end));\n}\nfunction evaluate(value, param) {\n return typeof value === 'function' ? value(param) : value;\n}\nfunction getSide(placement) {\n return placement.split('-')[0];\n}\nfunction getAlignment(placement) {\n return placement.split('-')[1];\n}\nfunction getOppositeAxis(axis) {\n return axis === 'x' ? 'y' : 'x';\n}\nfunction getAxisLength(axis) {\n return axis === 'y' ? 'height' : 'width';\n}\nconst yAxisSides = /*#__PURE__*/new Set(['top', 'bottom']);\nfunction getSideAxis(placement) {\n return yAxisSides.has(getSide(placement)) ? 'y' : 'x';\n}\nfunction getAlignmentAxis(placement) {\n return getOppositeAxis(getSideAxis(placement));\n}\nfunction getAlignmentSides(placement, rects, rtl) {\n if (rtl === void 0) {\n rtl = false;\n }\n const alignment = getAlignment(placement);\n const alignmentAxis = getAlignmentAxis(placement);\n const length = getAxisLength(alignmentAxis);\n let mainAlignmentSide = alignmentAxis === 'x' ? alignment === (rtl ? 'end' : 'start') ? 'right' : 'left' : alignment === 'start' ? 'bottom' : 'top';\n if (rects.reference[length] > rects.floating[length]) {\n mainAlignmentSide = getOppositePlacement(mainAlignmentSide);\n }\n return [mainAlignmentSide, getOppositePlacement(mainAlignmentSide)];\n}\nfunction getExpandedPlacements(placement) {\n const oppositePlacement = getOppositePlacement(placement);\n return [getOppositeAlignmentPlacement(placement), oppositePlacement, getOppositeAlignmentPlacement(oppositePlacement)];\n}\nfunction getOppositeAlignmentPlacement(placement) {\n return placement.replace(/start|end/g, alignment => oppositeAlignmentMap[alignment]);\n}\nconst lrPlacement = ['left', 'right'];\nconst rlPlacement = ['right', 'left'];\nconst tbPlacement = ['top', 'bottom'];\nconst btPlacement = ['bottom', 'top'];\nfunction getSideList(side, isStart, rtl) {\n switch (side) {\n case 'top':\n case 'bottom':\n if (rtl) return isStart ? rlPlacement : lrPlacement;\n return isStart ? lrPlacement : rlPlacement;\n case 'left':\n case 'right':\n return isStart ? tbPlacement : btPlacement;\n default:\n return [];\n }\n}\nfunction getOppositeAxisPlacements(placement, flipAlignment, direction, rtl) {\n const alignment = getAlignment(placement);\n let list = getSideList(getSide(placement), direction === 'start', rtl);\n if (alignment) {\n list = list.map(side => side + \"-\" + alignment);\n if (flipAlignment) {\n list = list.concat(list.map(getOppositeAlignmentPlacement));\n }\n }\n return list;\n}\nfunction getOppositePlacement(placement) {\n return placement.replace(/left|right|bottom|top/g, side => oppositeSideMap[side]);\n}\nfunction expandPaddingObject(padding) {\n return {\n top: 0,\n right: 0,\n bottom: 0,\n left: 0,\n ...padding\n };\n}\nfunction getPaddingObject(padding) {\n return typeof padding !== 'number' ? expandPaddingObject(padding) : {\n top: padding,\n right: padding,\n bottom: padding,\n left: padding\n };\n}\nfunction rectToClientRect(rect) {\n const {\n x,\n y,\n width,\n height\n } = rect;\n return {\n width,\n height,\n top: y,\n left: x,\n right: x + width,\n bottom: y + height,\n x,\n y\n };\n}\n\nexport { alignments, clamp, createCoords, evaluate, expandPaddingObject, floor, getAlignment, getAlignmentAxis, getAlignmentSides, getAxisLength, getExpandedPlacements, getOppositeAlignmentPlacement, getOppositeAxis, getOppositeAxisPlacements, getOppositePlacement, getPaddingObject, getSide, getSideAxis, max, min, placements, rectToClientRect, round, sides };\n","import { isShadowRoot, isHTMLElement } from '@floating-ui/utils/dom';\nimport * as React from 'react';\nimport { useLayoutEffect } from 'react';\nimport { floor } from '@floating-ui/utils';\nimport { tabbable } from 'tabbable';\n\n// Avoid Chrome DevTools blue warning.\nfunction getPlatform() {\n const uaData = navigator.userAgentData;\n if (uaData != null && uaData.platform) {\n return uaData.platform;\n }\n return navigator.platform;\n}\nfunction getUserAgent() {\n const uaData = navigator.userAgentData;\n if (uaData && Array.isArray(uaData.brands)) {\n return uaData.brands.map(_ref => {\n let {\n brand,\n version\n } = _ref;\n return brand + \"/\" + version;\n }).join(' ');\n }\n return navigator.userAgent;\n}\nfunction isSafari() {\n // Chrome DevTools does not complain about navigator.vendor\n return /apple/i.test(navigator.vendor);\n}\nfunction isAndroid() {\n const re = /android/i;\n return re.test(getPlatform()) || re.test(getUserAgent());\n}\nfunction isMac() {\n return getPlatform().toLowerCase().startsWith('mac') && !navigator.maxTouchPoints;\n}\nfunction isJSDOM() {\n return getUserAgent().includes('jsdom/');\n}\n\nconst FOCUSABLE_ATTRIBUTE = 'data-floating-ui-focusable';\nconst TYPEABLE_SELECTOR = \"input:not([type='hidden']):not([disabled]),\" + \"[contenteditable]:not([contenteditable='false']),textarea:not([disabled])\";\nconst ARROW_LEFT = 'ArrowLeft';\nconst ARROW_RIGHT = 'ArrowRight';\nconst ARROW_UP = 'ArrowUp';\nconst ARROW_DOWN = 'ArrowDown';\n\nfunction activeElement(doc) {\n let activeElement = doc.activeElement;\n while (((_activeElement = activeElement) == null || (_activeElement = _activeElement.shadowRoot) == null ? void 0 : _activeElement.activeElement) != null) {\n var _activeElement;\n activeElement = activeElement.shadowRoot.activeElement;\n }\n return activeElement;\n}\nfunction contains(parent, child) {\n if (!parent || !child) {\n return false;\n }\n const rootNode = child.getRootNode == null ? void 0 : child.getRootNode();\n\n // First, attempt with faster native method\n if (parent.contains(child)) {\n return true;\n }\n\n // then fallback to custom implementation with Shadow DOM support\n if (rootNode && isShadowRoot(rootNode)) {\n let next = child;\n while (next) {\n if (parent === next) {\n return true;\n }\n // @ts-ignore\n next = next.parentNode || next.host;\n }\n }\n\n // Give up, the result is false\n return false;\n}\nfunction getTarget(event) {\n if ('composedPath' in event) {\n return event.composedPath()[0];\n }\n\n // TS thinks `event` is of type never as it assumes all browsers support\n // `composedPath()`, but browsers without shadow DOM don't.\n return event.target;\n}\nfunction isEventTargetWithin(event, node) {\n if (node == null) {\n return false;\n }\n if ('composedPath' in event) {\n return event.composedPath().includes(node);\n }\n\n // TS thinks `event` is of type never as it assumes all browsers support composedPath, but browsers without shadow dom don't\n const e = event;\n return e.target != null && node.contains(e.target);\n}\nfunction isRootElement(element) {\n return element.matches('html,body');\n}\nfunction getDocument(node) {\n return (node == null ? void 0 : node.ownerDocument) || document;\n}\nfunction isTypeableElement(element) {\n return isHTMLElement(element) && element.matches(TYPEABLE_SELECTOR);\n}\nfunction isTypeableCombobox(element) {\n if (!element) return false;\n return element.getAttribute('role') === 'combobox' && isTypeableElement(element);\n}\nfunction matchesFocusVisible(element) {\n // We don't want to block focus from working with `visibleOnly`\n // (JSDOM doesn't match `:focus-visible` when the element has `:focus`)\n if (!element || isJSDOM()) return true;\n try {\n return element.matches(':focus-visible');\n } catch (_e) {\n return true;\n }\n}\nfunction getFloatingFocusElement(floatingElement) {\n if (!floatingElement) {\n return null;\n }\n // Try to find the element that has `{...getFloatingProps()}` spread on it.\n // This indicates the floating element is acting as a positioning wrapper, and\n // so focus should be managed on the child element with the event handlers and\n // aria props.\n return floatingElement.hasAttribute(FOCUSABLE_ATTRIBUTE) ? floatingElement : floatingElement.querySelector(\"[\" + FOCUSABLE_ATTRIBUTE + \"]\") || floatingElement;\n}\n\nfunction getNodeChildren(nodes, id, onlyOpenChildren) {\n if (onlyOpenChildren === void 0) {\n onlyOpenChildren = true;\n }\n const directChildren = nodes.filter(node => {\n var _node$context;\n return node.parentId === id && (!onlyOpenChildren || ((_node$context = node.context) == null ? void 0 : _node$context.open));\n });\n return directChildren.flatMap(child => [child, ...getNodeChildren(nodes, child.id, onlyOpenChildren)]);\n}\nfunction getDeepestNode(nodes, id) {\n let deepestNodeId;\n let maxDepth = -1;\n function findDeepest(nodeId, depth) {\n if (depth > maxDepth) {\n deepestNodeId = nodeId;\n maxDepth = depth;\n }\n const children = getNodeChildren(nodes, nodeId);\n children.forEach(child => {\n findDeepest(child.id, depth + 1);\n });\n }\n findDeepest(id, 0);\n return nodes.find(node => node.id === deepestNodeId);\n}\nfunction getNodeAncestors(nodes, id) {\n var _nodes$find;\n let allAncestors = [];\n let currentParentId = (_nodes$find = nodes.find(node => node.id === id)) == null ? void 0 : _nodes$find.parentId;\n while (currentParentId) {\n const currentNode = nodes.find(node => node.id === currentParentId);\n currentParentId = currentNode == null ? void 0 : currentNode.parentId;\n if (currentNode) {\n allAncestors = allAncestors.concat(currentNode);\n }\n }\n return allAncestors;\n}\n\nfunction stopEvent(event) {\n event.preventDefault();\n event.stopPropagation();\n}\nfunction isReactEvent(event) {\n return 'nativeEvent' in event;\n}\n\n// License: https://github.com/adobe/react-spectrum/blob/b35d5c02fe900badccd0cf1a8f23bb593419f238/packages/@react-aria/utils/src/isVirtualEvent.ts\nfunction isVirtualClick(event) {\n // FIXME: Firefox is now emitting a deprecation warning for `mozInputSource`.\n // Try to find a workaround for this. `react-aria` source still has the check.\n if (event.mozInputSource === 0 && event.isTrusted) {\n return true;\n }\n if (isAndroid() && event.pointerType) {\n return event.type === 'click' && event.buttons === 1;\n }\n return event.detail === 0 && !event.pointerType;\n}\nfunction isVirtualPointerEvent(event) {\n if (isJSDOM()) return false;\n return !isAndroid() && event.width === 0 && event.height === 0 || isAndroid() && event.width === 1 && event.height === 1 && event.pressure === 0 && event.detail === 0 && event.pointerType === 'mouse' ||\n // iOS VoiceOver returns 0.333• for width/height.\n event.width < 1 && event.height < 1 && event.pressure === 0 && event.detail === 0 && event.pointerType === 'touch';\n}\nfunction isMouseLikePointerType(pointerType, strict) {\n // On some Linux machines with Chromium, mouse inputs return a `pointerType`\n // of \"pen\": https://github.com/floating-ui/floating-ui/issues/2015\n const values = ['mouse', 'pen'];\n if (!strict) {\n values.push('', undefined);\n }\n return values.includes(pointerType);\n}\n\nvar isClient = typeof document !== 'undefined';\n\nvar noop = function noop() {};\nvar index = isClient ? useLayoutEffect : noop;\n\n// https://github.com/mui/material-ui/issues/41190#issuecomment-2040873379\nconst SafeReact = {\n ...React\n};\n\nfunction useLatestRef(value) {\n const ref = React.useRef(value);\n index(() => {\n ref.current = value;\n });\n return ref;\n}\nconst useInsertionEffect = SafeReact.useInsertionEffect;\nconst useSafeInsertionEffect = useInsertionEffect || (fn => fn());\nfunction useEffectEvent(callback) {\n const ref = React.useRef(() => {\n if (process.env.NODE_ENV !== \"production\") {\n throw new Error('Cannot call an event handler while rendering.');\n }\n });\n useSafeInsertionEffect(() => {\n ref.current = callback;\n });\n return React.useCallback(function () {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n return ref.current == null ? void 0 : ref.current(...args);\n }, []);\n}\n\nfunction isDifferentGridRow(index, cols, prevRow) {\n return Math.floor(index / cols) !== prevRow;\n}\nfunction isIndexOutOfListBounds(listRef, index) {\n return index < 0 || index >= listRef.current.length;\n}\nfunction getMinListIndex(listRef, disabledIndices) {\n return findNonDisabledListIndex(listRef, {\n disabledIndices\n });\n}\nfunction getMaxListIndex(listRef, disabledIndices) {\n return findNonDisabledListIndex(listRef, {\n decrement: true,\n startingIndex: listRef.current.length,\n disabledIndices\n });\n}\nfunction findNonDisabledListIndex(listRef, _temp) {\n let {\n startingIndex = -1,\n decrement = false,\n disabledIndices,\n amount = 1\n } = _temp === void 0 ? {} : _temp;\n let index = startingIndex;\n do {\n index += decrement ? -amount : amount;\n } while (index >= 0 && index <= listRef.current.length - 1 && isListIndexDisabled(listRef, index, disabledIndices));\n return index;\n}\nfunction getGridNavigatedIndex(listRef, _ref) {\n let {\n event,\n orientation,\n loop,\n rtl,\n cols,\n disabledIndices,\n minIndex,\n maxIndex,\n prevIndex,\n stopEvent: stop = false\n } = _ref;\n let nextIndex = prevIndex;\n if (event.key === ARROW_UP) {\n stop && stopEvent(event);\n if (prevIndex === -1) {\n nextIndex = maxIndex;\n } else {\n nextIndex = findNonDisabledListIndex(listRef, {\n startingIndex: nextIndex,\n amount: cols,\n decrement: true,\n disabledIndices\n });\n if (loop && (prevIndex - cols < minIndex || nextIndex < 0)) {\n const col = prevIndex % cols;\n const maxCol = maxIndex % cols;\n const offset = maxIndex - (maxCol - col);\n if (maxCol === col) {\n nextIndex = maxIndex;\n } else {\n nextIndex = maxCol > col ? offset : offset - cols;\n }\n }\n }\n if (isIndexOutOfListBounds(listRef, nextIndex)) {\n nextIndex = prevIndex;\n }\n }\n if (event.key === ARROW_DOWN) {\n stop && stopEvent(event);\n if (prevIndex === -1) {\n nextIndex = minIndex;\n } else {\n nextIndex = findNonDisabledListIndex(listRef, {\n startingIndex: prevIndex,\n amount: cols,\n disabledIndices\n });\n if (loop && prevIndex + cols > maxIndex) {\n nextIndex = findNonDisabledListIndex(listRef, {\n startingIndex: prevIndex % cols - cols,\n amount: cols,\n disabledIndices\n });\n }\n }\n if (isIndexOutOfListBounds(listRef, nextIndex)) {\n nextIndex = prevIndex;\n }\n }\n\n // Remains on the same row/column.\n if (orientation === 'both') {\n const prevRow = floor(prevIndex / cols);\n if (event.key === (rtl ? ARROW_LEFT : ARROW_RIGHT)) {\n stop && stopEvent(event);\n if (prevIndex % cols !== cols - 1) {\n nextIndex = findNonDisabledListIndex(listRef, {\n startingIndex: prevIndex,\n disabledIndices\n });\n if (loop && isDifferentGridRow(nextIndex, cols, prevRow)) {\n nextIndex = findNonDisabledListIndex(listRef, {\n startingIndex: prevIndex - prevIndex % cols - 1,\n disabledIndices\n });\n }\n } else if (loop) {\n nextIndex = findNonDisabledListIndex(listRef, {\n startingIndex: prevIndex - prevIndex % cols - 1,\n disabledIndices\n });\n }\n if (isDifferentGridRow(nextIndex, cols, prevRow)) {\n nextIndex = prevIndex;\n }\n }\n if (event.key === (rtl ? ARROW_RIGHT : ARROW_LEFT)) {\n stop && stopEvent(event);\n if (prevIndex % cols !== 0) {\n nextIndex = findNonDisabledListIndex(listRef, {\n startingIndex: prevIndex,\n decrement: true,\n disabledIndices\n });\n if (loop && isDifferentGridRow(nextIndex, cols, prevRow)) {\n nextIndex = findNonDisabledListIndex(listRef, {\n startingIndex: prevIndex + (cols - prevIndex % cols),\n decrement: true,\n disabledIndices\n });\n }\n } else if (loop) {\n nextIndex = findNonDisabledListIndex(listRef, {\n startingIndex: prevIndex + (cols - prevIndex % cols),\n decrement: true,\n disabledIndices\n });\n }\n if (isDifferentGridRow(nextIndex, cols, prevRow)) {\n nextIndex = prevIndex;\n }\n }\n const lastRow = floor(maxIndex / cols) === prevRow;\n if (isIndexOutOfListBounds(listRef, nextIndex)) {\n if (loop && lastRow) {\n nextIndex = event.key === (rtl ? ARROW_RIGHT : ARROW_LEFT) ? maxIndex : findNonDisabledListIndex(listRef, {\n startingIndex: prevIndex - prevIndex % cols - 1,\n disabledIndices\n });\n } else {\n nextIndex = prevIndex;\n }\n }\n }\n return nextIndex;\n}\n\n/** For each cell index, gets the item index that occupies that cell */\nfunction createGridCellMap(sizes, cols, dense) {\n const cellMap = [];\n let startIndex = 0;\n sizes.forEach((_ref2, index) => {\n let {\n width,\n height\n } = _ref2;\n if (width > cols) {\n if (process.env.NODE_ENV !== \"production\") {\n throw new Error(\"[Floating UI]: Invalid grid - item width at index \" + index + \" is greater than grid columns\");\n }\n }\n let itemPlaced = false;\n if (dense) {\n startIndex = 0;\n }\n while (!itemPlaced) {\n const targetCells = [];\n for (let i = 0; i < width; i++) {\n for (let j = 0; j < height; j++) {\n targetCells.push(startIndex + i + j * cols);\n }\n }\n if (startIndex % cols + width <= cols && targetCells.every(cell => cellMap[cell] == null)) {\n targetCells.forEach(cell => {\n cellMap[cell] = index;\n });\n itemPlaced = true;\n } else {\n startIndex++;\n }\n }\n });\n\n // convert into a non-sparse array\n return [...cellMap];\n}\n\n/** Gets cell index of an item's corner or -1 when index is -1. */\nfunction getGridCellIndexOfCorner(index, sizes, cellMap, cols, corner) {\n if (index === -1) return -1;\n const firstCellIndex = cellMap.indexOf(index);\n const sizeItem = sizes[index];\n switch (corner) {\n case 'tl':\n return firstCellIndex;\n case 'tr':\n if (!sizeItem) {\n return firstCellIndex;\n }\n return firstCellIndex + sizeItem.width - 1;\n case 'bl':\n if (!sizeItem) {\n return firstCellIndex;\n }\n return firstCellIndex + (sizeItem.height - 1) * cols;\n case 'br':\n return cellMap.lastIndexOf(index);\n }\n}\n\n/** Gets all cell indices that correspond to the specified indices */\nfunction getGridCellIndices(indices, cellMap) {\n return cellMap.flatMap((index, cellIndex) => indices.includes(index) ? [cellIndex] : []);\n}\nfunction isListIndexDisabled(listRef, index, disabledIndices) {\n if (typeof disabledIndices === 'function') {\n return disabledIndices(index);\n } else if (disabledIndices) {\n return disabledIndices.includes(index);\n }\n const element = listRef.current[index];\n return element == null || element.hasAttribute('disabled') || element.getAttribute('aria-disabled') === 'true';\n}\n\nconst getTabbableOptions = () => ({\n getShadowRoot: true,\n displayCheck:\n // JSDOM does not support the `tabbable` library. To solve this we can\n // check if `ResizeObserver` is a real function (not polyfilled), which\n // determines if the current environment is JSDOM-like.\n typeof ResizeObserver === 'function' && ResizeObserver.toString().includes('[native code]') ? 'full' : 'none'\n});\nfunction getTabbableIn(container, dir) {\n const list = tabbable(container, getTabbableOptions());\n const len = list.length;\n if (len === 0) return;\n const active = activeElement(getDocument(container));\n const index = list.indexOf(active);\n const nextIndex = index === -1 ? dir === 1 ? 0 : len - 1 : index + dir;\n return list[nextIndex];\n}\nfunction getNextTabbable(referenceElement) {\n return getTabbableIn(getDocument(referenceElement).body, 1) || referenceElement;\n}\nfunction getPreviousTabbable(referenceElement) {\n return getTabbableIn(getDocument(referenceElement).body, -1) || referenceElement;\n}\nfunction isOutsideEvent(event, container) {\n const containerElement = container || event.currentTarget;\n const relatedTarget = event.relatedTarget;\n return !relatedTarget || !contains(containerElement, relatedTarget);\n}\nfunction disableFocusInside(container) {\n const tabbableElements = tabbable(container, getTabbableOptions());\n tabbableElements.forEach(element => {\n element.dataset.tabindex = element.getAttribute('tabindex') || '';\n element.setAttribute('tabindex', '-1');\n });\n}\nfunction enableFocusInside(container) {\n const elements = container.querySelectorAll('[data-tabindex]');\n elements.forEach(element => {\n const tabindex = element.dataset.tabindex;\n delete element.dataset.tabindex;\n if (tabindex) {\n element.setAttribute('tabindex', tabindex);\n } else {\n element.removeAttribute('tabindex');\n }\n });\n}\n\nexport { activeElement, contains, createGridCellMap, disableFocusInside, enableFocusInside, findNonDisabledListIndex, getDeepestNode, getDocument, getFloatingFocusElement, getGridCellIndexOfCorner, getGridCellIndices, getGridNavigatedIndex, getMaxListIndex, getMinListIndex, getNextTabbable, getNodeAncestors, getNodeChildren, getPlatform, getPreviousTabbable, getTabbableOptions, getTarget, getUserAgent, isAndroid, isDifferentGridRow, isEventTargetWithin, isIndexOutOfListBounds, isJSDOM, isListIndexDisabled, isMac, isMouseLikePointerType, isOutsideEvent, isReactEvent, isRootElement, isSafari, isTypeableCombobox, isTypeableElement, isVirtualClick, isVirtualPointerEvent, matchesFocusVisible, stopEvent, useEffectEvent, useLatestRef, index as useModernLayoutEffect };\n","import { getSideAxis, getAlignmentAxis, getAxisLength, getSide, getAlignment, evaluate, getPaddingObject, rectToClientRect, min, clamp, placements, getAlignmentSides, getOppositeAlignmentPlacement, getOppositePlacement, getExpandedPlacements, getOppositeAxisPlacements, sides, max, getOppositeAxis } from '@floating-ui/utils';\nexport { rectToClientRect } from '@floating-ui/utils';\n\nfunction computeCoordsFromPlacement(_ref, placement, rtl) {\n let {\n reference,\n floating\n } = _ref;\n const sideAxis = getSideAxis(placement);\n const alignmentAxis = getAlignmentAxis(placement);\n const alignLength = getAxisLength(alignmentAxis);\n const side = getSide(placement);\n const isVertical = sideAxis === 'y';\n const commonX = reference.x + reference.width / 2 - floating.width / 2;\n const commonY = reference.y + reference.height / 2 - floating.height / 2;\n const commonAlign = reference[alignLength] / 2 - floating[alignLength] / 2;\n let coords;\n switch (side) {\n case 'top':\n coords = {\n x: commonX,\n y: reference.y - floating.height\n };\n break;\n case 'bottom':\n coords = {\n x: commonX,\n y: reference.y + reference.height\n };\n break;\n case 'right':\n coords = {\n x: reference.x + reference.width,\n y: commonY\n };\n break;\n case 'left':\n coords = {\n x: reference.x - floating.width,\n y: commonY\n };\n break;\n default:\n coords = {\n x: reference.x,\n y: reference.y\n };\n }\n switch (getAlignment(placement)) {\n case 'start':\n coords[alignmentAxis] -= commonAlign * (rtl && isVertical ? -1 : 1);\n break;\n case 'end':\n coords[alignmentAxis] += commonAlign * (rtl && isVertical ? -1 : 1);\n break;\n }\n return coords;\n}\n\n/**\n * Resolves with an object of overflow side offsets that determine how much the\n * element is overflowing a given clipping boundary on each side.\n * - positive = overflowing the boundary by that number of pixels\n * - negative = how many pixels left before it will overflow\n * - 0 = lies flush with the boundary\n * @see https://floating-ui.com/docs/detectOverflow\n */\nasync function detectOverflow(state, options) {\n var _await$platform$isEle;\n if (options === void 0) {\n options = {};\n }\n const {\n x,\n y,\n platform,\n rects,\n elements,\n strategy\n } = state;\n const {\n boundary = 'clippingAncestors',\n rootBoundary = 'viewport',\n elementContext = 'floating',\n altBoundary = false,\n padding = 0\n } = evaluate(options, state);\n const paddingObject = getPaddingObject(padding);\n const altContext = elementContext === 'floating' ? 'reference' : 'floating';\n const element = elements[altBoundary ? altContext : elementContext];\n const clippingClientRect = rectToClientRect(await platform.getClippingRect({\n element: ((_await$platform$isEle = await (platform.isElement == null ? void 0 : platform.isElement(element))) != null ? _await$platform$isEle : true) ? element : element.contextElement || (await (platform.getDocumentElement == null ? void 0 : platform.getDocumentElement(elements.floating))),\n boundary,\n rootBoundary,\n strategy\n }));\n const rect = elementContext === 'floating' ? {\n x,\n y,\n width: rects.floating.width,\n height: rects.floating.height\n } : rects.reference;\n const offsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(elements.floating));\n const offsetScale = (await (platform.isElement == null ? void 0 : platform.isElement(offsetParent))) ? (await (platform.getScale == null ? void 0 : platform.getScale(offsetParent))) || {\n x: 1,\n y: 1\n } : {\n x: 1,\n y: 1\n };\n const elementClientRect = rectToClientRect(platform.convertOffsetParentRelativeRectToViewportRelativeRect ? await platform.convertOffsetParentRelativeRectToViewportRelativeRect({\n elements,\n rect,\n offsetParent,\n strategy\n }) : rect);\n return {\n top: (clippingClientRect.top - elementClientRect.top + paddingObject.top) / offsetScale.y,\n bottom: (elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom) / offsetScale.y,\n left: (clippingClientRect.left - elementClientRect.left + paddingObject.left) / offsetScale.x,\n right: (elementClientRect.right - clippingClientRect.right + paddingObject.right) / offsetScale.x\n };\n}\n\n/**\n * Computes the `x` and `y` coordinates that will place the floating element\n * next to a given reference element.\n *\n * This export does not have any `platform` interface logic. You will need to\n * write one for the platform you are using Floating UI with.\n */\nconst computePosition = async (reference, floating, config) => {\n const {\n placement = 'bottom',\n strategy = 'absolute',\n middleware = [],\n platform\n } = config;\n const validMiddleware = middleware.filter(Boolean);\n const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(floating));\n let rects = await platform.getElementRects({\n reference,\n floating,\n strategy\n });\n let {\n x,\n y\n } = computeCoordsFromPlacement(rects, placement, rtl);\n let statefulPlacement = placement;\n let middlewareData = {};\n let resetCount = 0;\n for (let i = 0; i < validMiddleware.length; i++) {\n var _platform$detectOverf;\n const {\n name,\n fn\n } = validMiddleware[i];\n const {\n x: nextX,\n y: nextY,\n data,\n reset\n } = await fn({\n x,\n y,\n initialPlacement: placement,\n placement: statefulPlacement,\n strategy,\n middlewareData,\n rects,\n platform: {\n ...platform,\n detectOverflow: (_platform$detectOverf = platform.detectOverflow) != null ? _platform$detectOverf : detectOverflow\n },\n elements: {\n reference,\n floating\n }\n });\n x = nextX != null ? nextX : x;\n y = nextY != null ? nextY : y;\n middlewareData = {\n ...middlewareData,\n [name]: {\n ...middlewareData[name],\n ...data\n }\n };\n if (reset && resetCount <= 50) {\n resetCount++;\n if (typeof reset === 'object') {\n if (reset.placement) {\n statefulPlacement = reset.placement;\n }\n if (reset.rects) {\n rects = reset.rects === true ? await platform.getElementRects({\n reference,\n floating,\n strategy\n }) : reset.rects;\n }\n ({\n x,\n y\n } = computeCoordsFromPlacement(rects, statefulPlacement, rtl));\n }\n i = -1;\n }\n }\n return {\n x,\n y,\n placement: statefulPlacement,\n strategy,\n middlewareData\n };\n};\n\n/**\n * Provides data to position an inner element of the floating element so that it\n * appears centered to the reference element.\n * @see https://floating-ui.com/docs/arrow\n */\nconst arrow = options => ({\n name: 'arrow',\n options,\n async fn(state) {\n const {\n x,\n y,\n placement,\n rects,\n platform,\n elements,\n middlewareData\n } = state;\n // Since `element` is required, we don't Partial<> the type.\n const {\n element,\n padding = 0\n } = evaluate(options, state) || {};\n if (element == null) {\n return {};\n }\n const paddingObject = getPaddingObject(padding);\n const coords = {\n x,\n y\n };\n const axis = getAlignmentAxis(placement);\n const length = getAxisLength(axis);\n const arrowDimensions = await platform.getDimensions(element);\n const isYAxis = axis === 'y';\n const minProp = isYAxis ? 'top' : 'left';\n const maxProp = isYAxis ? 'bottom' : 'right';\n const clientProp = isYAxis ? 'clientHeight' : 'clientWidth';\n const endDiff = rects.reference[length] + rects.reference[axis] - coords[axis] - rects.floating[length];\n const startDiff = coords[axis] - rects.reference[axis];\n const arrowOffsetParent = await (platform.getOffsetParent == null ? void 0 : platform.getOffsetParent(element));\n let clientSize = arrowOffsetParent ? arrowOffsetParent[clientProp] : 0;\n\n // DOM platform can return `window` as the `offsetParent`.\n if (!clientSize || !(await (platform.isElement == null ? void 0 : platform.isElement(arrowOffsetParent)))) {\n clientSize = elements.floating[clientProp] || rects.floating[length];\n }\n const centerToReference = endDiff / 2 - startDiff / 2;\n\n // If the padding is large enough that it causes the arrow to no longer be\n // centered, modify the padding so that it is centered.\n const largestPossiblePadding = clientSize / 2 - arrowDimensions[length] / 2 - 1;\n const minPadding = min(paddingObject[minProp], largestPossiblePadding);\n const maxPadding = min(paddingObject[maxProp], largestPossiblePadding);\n\n // Make sure the arrow doesn't overflow the floating element if the center\n // point is outside the floating element's bounds.\n const min$1 = minPadding;\n const max = clientSize - arrowDimensions[length] - maxPadding;\n const center = clientSize / 2 - arrowDimensions[length] / 2 + centerToReference;\n const offset = clamp(min$1, center, max);\n\n // If the reference is small enough that the arrow's padding causes it to\n // to point to nothing for an aligned placement, adjust the offset of the\n // floating element itself. To ensure `shift()` continues to take action,\n // a single reset is performed when this is true.\n const shouldAddOffset = !middlewareData.arrow && getAlignment(placement) != null && center !== offset && rects.reference[length] / 2 - (center < min$1 ? minPadding : maxPadding) - arrowDimensions[length] / 2 < 0;\n const alignmentOffset = shouldAddOffset ? center < min$1 ? center - min$1 : center - max : 0;\n return {\n [axis]: coords[axis] + alignmentOffset,\n data: {\n [axis]: offset,\n centerOffset: center - offset - alignmentOffset,\n ...(shouldAddOffset && {\n alignmentOffset\n })\n },\n reset: shouldAddOffset\n };\n }\n});\n\nfunction getPlacementList(alignment, autoAlignment, allowedPlacements) {\n const allowedPlacementsSortedByAlignment = alignment ? [...allowedPlacements.filter(placement => getAlignment(placement) === alignment), ...allowedPlacements.filter(placement => getAlignment(placement) !== alignment)] : allowedPlacements.filter(placement => getSide(placement) === placement);\n return allowedPlacementsSortedByAlignment.filter(placement => {\n if (alignment) {\n return getAlignment(placement) === alignment || (autoAlignment ? getOppositeAlignmentPlacement(placement) !== placement : false);\n }\n return true;\n });\n}\n/**\n * Optimizes the visibility of the floating element by choosing the placement\n * that has the most space available automatically, without needing to specify a\n * preferred placement. Alternative to `flip`.\n * @see https://floating-ui.com/docs/autoPlacement\n */\nconst autoPlacement = function (options) {\n if (options === void 0) {\n options = {};\n }\n return {\n name: 'autoPlacement',\n options,\n async fn(state) {\n var _middlewareData$autoP, _middlewareData$autoP2, _placementsThatFitOnE;\n const {\n rects,\n middlewareData,\n placement,\n platform,\n elements\n } = state;\n const {\n crossAxis = false,\n alignment,\n allowedPlacements = placements,\n autoAlignment = true,\n ...detectOverflowOptions\n } = evaluate(options, state);\n const placements$1 = alignment !== undefined || allowedPlacements === placements ? getPlacementList(alignment || null, autoAlignment, allowedPlacements) : allowedPlacements;\n const overflow = await platform.detectOverflow(state, detectOverflowOptions);\n const currentIndex = ((_middlewareData$autoP = middlewareData.autoPlacement) == null ? void 0 : _middlewareData$autoP.index) || 0;\n const currentPlacement = placements$1[currentIndex];\n if (currentPlacement == null) {\n return {};\n }\n const alignmentSides = getAlignmentSides(currentPlacement, rects, await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating)));\n\n // Make `computeCoords` start from the right place.\n if (placement !== currentPlacement) {\n return {\n reset: {\n placement: placements$1[0]\n }\n };\n }\n const currentOverflows = [overflow[getSide(currentPlacement)], overflow[alignmentSides[0]], overflow[alignmentSides[1]]];\n const allOverflows = [...(((_middlewareData$autoP2 = middlewareData.autoPlacement) == null ? void 0 : _middlewareData$autoP2.overflows) || []), {\n placement: currentPlacement,\n overflows: currentOverflows\n }];\n const nextPlacement = placements$1[currentIndex + 1];\n\n // There are more placements to check.\n if (nextPlacement) {\n return {\n data: {\n index: currentIndex + 1,\n overflows: allOverflows\n },\n reset: {\n placement: nextPlacement\n }\n };\n }\n const placementsSortedByMostSpace = allOverflows.map(d => {\n const alignment = getAlignment(d.placement);\n return [d.placement, alignment && crossAxis ?\n // Check along the mainAxis and main crossAxis side.\n d.overflows.slice(0, 2).reduce((acc, v) => acc + v, 0) :\n // Check only the mainAxis.\n d.overflows[0], d.overflows];\n }).sort((a, b) => a[1] - b[1]);\n const placementsThatFitOnEachSide = placementsSortedByMostSpace.filter(d => d[2].slice(0,\n // Aligned placements should not check their opposite crossAxis\n // side.\n getAlignment(d[0]) ? 2 : 3).every(v => v <= 0));\n const resetPlacement = ((_placementsThatFitOnE = placementsThatFitOnEachSide[0]) == null ? void 0 : _placementsThatFitOnE[0]) || placementsSortedByMostSpace[0][0];\n if (resetPlacement !== placement) {\n return {\n data: {\n index: currentIndex + 1,\n overflows: allOverflows\n },\n reset: {\n placement: resetPlacement\n }\n };\n }\n return {};\n }\n };\n};\n\n/**\n * Optimizes the visibility of the floating element by flipping the `placement`\n * in order to keep it in view when the preferred placement(s) will overflow the\n * clipping boundary. Alternative to `autoPlacement`.\n * @see https://floating-ui.com/docs/flip\n */\nconst flip = function (options) {\n if (options === void 0) {\n options = {};\n }\n return {\n name: 'flip',\n options,\n async fn(state) {\n var _middlewareData$arrow, _middlewareData$flip;\n const {\n placement,\n middlewareData,\n rects,\n initialPlacement,\n platform,\n elements\n } = state;\n const {\n mainAxis: checkMainAxis = true,\n crossAxis: checkCrossAxis = true,\n fallbackPlacements: specifiedFallbackPlacements,\n fallbackStrategy = 'bestFit',\n fallbackAxisSideDirection = 'none',\n flipAlignment = true,\n ...detectOverflowOptions\n } = evaluate(options, state);\n\n // If a reset by the arrow was caused due to an alignment offset being\n // added, we should skip any logic now since `flip()` has already done its\n // work.\n // https://github.com/floating-ui/floating-ui/issues/2549#issuecomment-1719601643\n if ((_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) {\n return {};\n }\n const side = getSide(placement);\n const initialSideAxis = getSideAxis(initialPlacement);\n const isBasePlacement = getSide(initialPlacement) === initialPlacement;\n const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating));\n const fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipAlignment ? [getOppositePlacement(initialPlacement)] : getExpandedPlacements(initialPlacement));\n const hasFallbackAxisSideDirection = fallbackAxisSideDirection !== 'none';\n if (!specifiedFallbackPlacements && hasFallbackAxisSideDirection) {\n fallbackPlacements.push(...getOppositeAxisPlacements(initialPlacement, flipAlignment, fallbackAxisSideDirection, rtl));\n }\n const placements = [initialPlacement, ...fallbackPlacements];\n const overflow = await platform.detectOverflow(state, detectOverflowOptions);\n const overflows = [];\n let overflowsData = ((_middlewareData$flip = middlewareData.flip) == null ? void 0 : _middlewareData$flip.overflows) || [];\n if (checkMainAxis) {\n overflows.push(overflow[side]);\n }\n if (checkCrossAxis) {\n const sides = getAlignmentSides(placement, rects, rtl);\n overflows.push(overflow[sides[0]], overflow[sides[1]]);\n }\n overflowsData = [...overflowsData, {\n placement,\n overflows\n }];\n\n // One or more sides is overflowing.\n if (!overflows.every(side => side <= 0)) {\n var _middlewareData$flip2, _overflowsData$filter;\n const nextIndex = (((_middlewareData$flip2 = middlewareData.flip) == null ? void 0 : _middlewareData$flip2.index) || 0) + 1;\n const nextPlacement = placements[nextIndex];\n if (nextPlacement) {\n const ignoreCrossAxisOverflow = checkCrossAxis === 'alignment' ? initialSideAxis !== getSideAxis(nextPlacement) : false;\n if (!ignoreCrossAxisOverflow ||\n // We leave the current main axis only if every placement on that axis\n // overflows the main axis.\n overflowsData.every(d => getSideAxis(d.placement) === initialSideAxis ? d.overflows[0] > 0 : true)) {\n // Try next placement and re-run the lifecycle.\n return {\n data: {\n index: nextIndex,\n overflows: overflowsData\n },\n reset: {\n placement: nextPlacement\n }\n };\n }\n }\n\n // First, find the candidates that fit on the mainAxis side of overflow,\n // then find the placement that fits the best on the main crossAxis side.\n 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;\n\n // Otherwise fallback.\n if (!resetPlacement) {\n switch (fallbackStrategy) {\n case 'bestFit':\n {\n var _overflowsData$filter2;\n const placement = (_overflowsData$filter2 = overflowsData.filter(d => {\n if (hasFallbackAxisSideDirection) {\n const currentSideAxis = getSideAxis(d.placement);\n return currentSideAxis === initialSideAxis ||\n // Create a bias to the `y` side axis due to horizontal\n // reading directions favoring greater width.\n currentSideAxis === 'y';\n }\n return true;\n }).map(d => [d.placement, d.overflows.filter(overflow => overflow > 0).reduce((acc, overflow) => acc + overflow, 0)]).sort((a, b) => a[1] - b[1])[0]) == null ? void 0 : _overflowsData$filter2[0];\n if (placement) {\n resetPlacement = placement;\n }\n break;\n }\n case 'initialPlacement':\n resetPlacement = initialPlacement;\n break;\n }\n }\n if (placement !== resetPlacement) {\n return {\n reset: {\n placement: resetPlacement\n }\n };\n }\n }\n return {};\n }\n };\n};\n\nfunction getSideOffsets(overflow, rect) {\n return {\n top: overflow.top - rect.height,\n right: overflow.right - rect.width,\n bottom: overflow.bottom - rect.height,\n left: overflow.left - rect.width\n };\n}\nfunction isAnySideFullyClipped(overflow) {\n return sides.some(side => overflow[side] >= 0);\n}\n/**\n * Provides data to hide the floating element in applicable situations, such as\n * when it is not in the same clipping context as the reference element.\n * @see https://floating-ui.com/docs/hide\n */\nconst hide = function (options) {\n if (options === void 0) {\n options = {};\n }\n return {\n name: 'hide',\n options,\n async fn(state) {\n const {\n rects,\n platform\n } = state;\n const {\n strategy = 'referenceHidden',\n ...detectOverflowOptions\n } = evaluate(options, state);\n switch (strategy) {\n case 'referenceHidden':\n {\n const overflow = await platform.detectOverflow(state, {\n ...detectOverflowOptions,\n elementContext: 'reference'\n });\n const offsets = getSideOffsets(overflow, rects.reference);\n return {\n data: {\n referenceHiddenOffsets: offsets,\n referenceHidden: isAnySideFullyClipped(offsets)\n }\n };\n }\n case 'escaped':\n {\n const overflow = await platform.detectOverflow(state, {\n ...detectOverflowOptions,\n altBoundary: true\n });\n const offsets = getSideOffsets(overflow, rects.floating);\n return {\n data: {\n escapedOffsets: offsets,\n escaped: isAnySideFullyClipped(offsets)\n }\n };\n }\n default:\n {\n return {};\n }\n }\n }\n };\n};\n\nfunction getBoundingRect(rects) {\n const minX = min(...rects.map(rect => rect.left));\n const minY = min(...rects.map(rect => rect.top));\n const maxX = max(...rects.map(rect => rect.right));\n const maxY = max(...rects.map(rect => rect.bottom));\n return {\n x: minX,\n y: minY,\n width: maxX - minX,\n height: maxY - minY\n };\n}\nfunction getRectsByLine(rects) {\n const sortedRects = rects.slice().sort((a, b) => a.y - b.y);\n const groups = [];\n let prevRect = null;\n for (let i = 0; i < sortedRects.length; i++) {\n const rect = sortedRects[i];\n if (!prevRect || rect.y - prevRect.y > prevRect.height / 2) {\n groups.push([rect]);\n } else {\n groups[groups.length - 1].push(rect);\n }\n prevRect = rect;\n }\n return groups.map(rect => rectToClientRect(getBoundingRect(rect)));\n}\n/**\n * Provides improved positioning for inline reference elements that can span\n * over multiple lines, such as hyperlinks or range selections.\n * @see https://floating-ui.com/docs/inline\n */\nconst inline = function (options) {\n if (options === void 0) {\n options = {};\n }\n return {\n name: 'inline',\n options,\n async fn(state) {\n const {\n placement,\n elements,\n rects,\n platform,\n strategy\n } = state;\n // A MouseEvent's client{X,Y} coords can be up to 2 pixels off a\n // ClientRect's bounds, despite the event listener being triggered. A\n // padding of 2 seems to handle this issue.\n const {\n padding = 2,\n x,\n y\n } = evaluate(options, state);\n const nativeClientRects = Array.from((await (platform.getClientRects == null ? void 0 : platform.getClientRects(elements.reference))) || []);\n const clientRects = getRectsByLine(nativeClientRects);\n const fallback = rectToClientRect(getBoundingRect(nativeClientRects));\n const paddingObject = getPaddingObject(padding);\n function getBoundingClientRect() {\n // There are two rects and they are disjoined.\n if (clientRects.length === 2 && clientRects[0].left > clientRects[1].right && x != null && y != null) {\n // Find the first rect in which the point is fully inside.\n return clientRects.find(rect => x > rect.left - paddingObject.left && x < rect.right + paddingObject.right && y > rect.top - paddingObject.top && y < rect.bottom + paddingObject.bottom) || fallback;\n }\n\n // There are 2 or more connected rects.\n if (clientRects.length >= 2) {\n if (getSideAxis(placement) === 'y') {\n const firstRect = clientRects[0];\n const lastRect = clientRects[clientRects.length - 1];\n const isTop = getSide(placement) === 'top';\n const top = firstRect.top;\n const bottom = lastRect.bottom;\n const left = isTop ? firstRect.left : lastRect.left;\n const right = isTop ? firstRect.right : lastRect.right;\n const width = right - left;\n const height = bottom - top;\n return {\n top,\n bottom,\n left,\n right,\n width,\n height,\n x: left,\n y: top\n };\n }\n const isLeftSide = getSide(placement) === 'left';\n const maxRight = max(...clientRects.map(rect => rect.right));\n const minLeft = min(...clientRects.map(rect => rect.left));\n const measureRects = clientRects.filter(rect => isLeftSide ? rect.left === minLeft : rect.right === maxRight);\n const top = measureRects[0].top;\n const bottom = measureRects[measureRects.length - 1].bottom;\n const left = minLeft;\n const right = maxRight;\n const width = right - left;\n const height = bottom - top;\n return {\n top,\n bottom,\n left,\n right,\n width,\n height,\n x: left,\n y: top\n };\n }\n return fallback;\n }\n const resetRects = await platform.getElementRects({\n reference: {\n getBoundingClientRect\n },\n floating: elements.floating,\n strategy\n });\n if (rects.reference.x !== resetRects.reference.x || rects.reference.y !== resetRects.reference.y || rects.reference.width !== resetRects.reference.width || rects.reference.height !== resetRects.reference.height) {\n return {\n reset: {\n rects: resetRects\n }\n };\n }\n return {};\n }\n };\n};\n\nconst originSides = /*#__PURE__*/new Set(['left', 'top']);\n\n// For type backwards-compatibility, the `OffsetOptions` type was also\n// Derivable.\n\nasync function convertValueToCoords(state, options) {\n const {\n placement,\n platform,\n elements\n } = state;\n const rtl = await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating));\n const side = getSide(placement);\n const alignment = getAlignment(placement);\n const isVertical = getSideAxis(placement) === 'y';\n const mainAxisMulti = originSides.has(side) ? -1 : 1;\n const crossAxisMulti = rtl && isVertical ? -1 : 1;\n const rawValue = evaluate(options, state);\n\n // eslint-disable-next-line prefer-const\n let {\n mainAxis,\n crossAxis,\n alignmentAxis\n } = typeof rawValue === 'number' ? {\n mainAxis: rawValue,\n crossAxis: 0,\n alignmentAxis: null\n } : {\n mainAxis: rawValue.mainAxis || 0,\n crossAxis: rawValue.crossAxis || 0,\n alignmentAxis: rawValue.alignmentAxis\n };\n if (alignment && typeof alignmentAxis === 'number') {\n crossAxis = alignment === 'end' ? alignmentAxis * -1 : alignmentAxis;\n }\n return isVertical ? {\n x: crossAxis * crossAxisMulti,\n y: mainAxis * mainAxisMulti\n } : {\n x: mainAxis * mainAxisMulti,\n y: crossAxis * crossAxisMulti\n };\n}\n\n/**\n * Modifies the placement by translating the floating element along the\n * specified axes.\n * A number (shorthand for `mainAxis` or distance), or an axes configuration\n * object may be passed.\n * @see https://floating-ui.com/docs/offset\n */\nconst offset = function (options) {\n if (options === void 0) {\n options = 0;\n }\n return {\n name: 'offset',\n options,\n async fn(state) {\n var _middlewareData$offse, _middlewareData$arrow;\n const {\n x,\n y,\n placement,\n middlewareData\n } = state;\n const diffCoords = await convertValueToCoords(state, options);\n\n // If the placement is the same and the arrow caused an alignment offset\n // then we don't need to change the positioning coordinates.\n if (placement === ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse.placement) && (_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) {\n return {};\n }\n return {\n x: x + diffCoords.x,\n y: y + diffCoords.y,\n data: {\n ...diffCoords,\n placement\n }\n };\n }\n };\n};\n\n/**\n * Optimizes the visibility of the floating element by shifting it in order to\n * keep it in view when it will overflow the clipping boundary.\n * @see https://floating-ui.com/docs/shift\n */\nconst shift = function (options) {\n if (options === void 0) {\n options = {};\n }\n return {\n name: 'shift',\n options,\n async fn(state) {\n const {\n x,\n y,\n placement,\n platform\n } = state;\n const {\n mainAxis: checkMainAxis = true,\n crossAxis: checkCrossAxis = false,\n limiter = {\n fn: _ref => {\n let {\n x,\n y\n } = _ref;\n return {\n x,\n y\n };\n }\n },\n ...detectOverflowOptions\n } = evaluate(options, state);\n const coords = {\n x,\n y\n };\n const overflow = await platform.detectOverflow(state, detectOverflowOptions);\n const crossAxis = getSideAxis(getSide(placement));\n const mainAxis = getOppositeAxis(crossAxis);\n let mainAxisCoord = coords[mainAxis];\n let crossAxisCoord = coords[crossAxis];\n if (checkMainAxis) {\n const minSide = mainAxis === 'y' ? 'top' : 'left';\n const maxSide = mainAxis === 'y' ? 'bottom' : 'right';\n const min = mainAxisCoord + overflow[minSide];\n const max = mainAxisCoord - overflow[maxSide];\n mainAxisCoord = clamp(min, mainAxisCoord, max);\n }\n if (checkCrossAxis) {\n const minSide = crossAxis === 'y' ? 'top' : 'left';\n const maxSide = crossAxis === 'y' ? 'bottom' : 'right';\n const min = crossAxisCoord + overflow[minSide];\n const max = crossAxisCoord - overflow[maxSide];\n crossAxisCoord = clamp(min, crossAxisCoord, max);\n }\n const limitedCoords = limiter.fn({\n ...state,\n [mainAxis]: mainAxisCoord,\n [crossAxis]: crossAxisCoord\n });\n return {\n ...limitedCoords,\n data: {\n x: limitedCoords.x - x,\n y: limitedCoords.y - y,\n enabled: {\n [mainAxis]: checkMainAxis,\n [crossAxis]: checkCrossAxis\n }\n }\n };\n }\n };\n};\n/**\n * Built-in `limiter` that will stop `shift()` at a certain point.\n */\nconst limitShift = function (options) {\n if (options === void 0) {\n options = {};\n }\n return {\n options,\n fn(state) {\n const {\n x,\n y,\n placement,\n rects,\n middlewareData\n } = state;\n const {\n offset = 0,\n mainAxis: checkMainAxis = true,\n crossAxis: checkCrossAxis = true\n } = evaluate(options, state);\n const coords = {\n x,\n y\n };\n const crossAxis = getSideAxis(placement);\n const mainAxis = getOppositeAxis(crossAxis);\n let mainAxisCoord = coords[mainAxis];\n let crossAxisCoord = coords[crossAxis];\n const rawOffset = evaluate(offset, state);\n const computedOffset = typeof rawOffset === 'number' ? {\n mainAxis: rawOffset,\n crossAxis: 0\n } : {\n mainAxis: 0,\n crossAxis: 0,\n ...rawOffset\n };\n if (checkMainAxis) {\n const len = mainAxis === 'y' ? 'height' : 'width';\n const limitMin = rects.reference[mainAxis] - rects.floating[len] + computedOffset.mainAxis;\n const limitMax = rects.reference[mainAxis] + rects.reference[len] - computedOffset.mainAxis;\n if (mainAxisCoord < limitMin) {\n mainAxisCoord = limitMin;\n } else if (mainAxisCoord > limitMax) {\n mainAxisCoord = limitMax;\n }\n }\n if (checkCrossAxis) {\n var _middlewareData$offse, _middlewareData$offse2;\n const len = mainAxis === 'y' ? 'width' : 'height';\n const isOriginSide = originSides.has(getSide(placement));\n const limitMin = rects.reference[crossAxis] - rects.floating[len] + (isOriginSide ? ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse[crossAxis]) || 0 : 0) + (isOriginSide ? 0 : computedOffset.crossAxis);\n const limitMax = rects.reference[crossAxis] + rects.reference[len] + (isOriginSide ? 0 : ((_middlewareData$offse2 = middlewareData.offset) == null ? void 0 : _middlewareData$offse2[crossAxis]) || 0) - (isOriginSide ? computedOffset.crossAxis : 0);\n if (crossAxisCoord < limitMin) {\n crossAxisCoord = limitMin;\n } else if (crossAxisCoord > limitMax) {\n crossAxisCoord = limitMax;\n }\n }\n return {\n [mainAxis]: mainAxisCoord,\n [crossAxis]: crossAxisCoord\n };\n }\n };\n};\n\n/**\n * Provides data that allows you to change the size of the floating element —\n * for instance, prevent it from overflowing the clipping boundary or match the\n * width of the reference element.\n * @see https://floating-ui.com/docs/size\n */\nconst size = function (options) {\n if (options === void 0) {\n options = {};\n }\n return {\n name: 'size',\n options,\n async fn(state) {\n var _state$middlewareData, _state$middlewareData2;\n const {\n placement,\n rects,\n platform,\n elements\n } = state;\n const {\n apply = () => {},\n ...detectOverflowOptions\n } = evaluate(options, state);\n const overflow = await platform.detectOverflow(state, detectOverflowOptions);\n const side = getSide(placement);\n const alignment = getAlignment(placement);\n const isYAxis = getSideAxis(placement) === 'y';\n const {\n width,\n height\n } = rects.floating;\n let heightSide;\n let widthSide;\n if (side === 'top' || side === 'bottom') {\n heightSide = side;\n widthSide = alignment === ((await (platform.isRTL == null ? void 0 : platform.isRTL(elements.floating))) ? 'start' : 'end') ? 'left' : 'right';\n } else {\n widthSide = side;\n heightSide = alignment === 'end' ? 'top' : 'bottom';\n }\n const maximumClippingHeight = height - overflow.top - overflow.bottom;\n const maximumClippingWidth = width - overflow.left - overflow.right;\n const overflowAvailableHeight = min(height - overflow[heightSide], maximumClippingHeight);\n const overflowAvailableWidth = min(width - overflow[widthSide], maximumClippingWidth);\n const noShift = !state.middlewareData.shift;\n let availableHeight = overflowAvailableHeight;\n let availableWidth = overflowAvailableWidth;\n if ((_state$middlewareData = state.middlewareData.shift) != null && _state$middlewareData.enabled.x) {\n availableWidth = maximumClippingWidth;\n }\n if ((_state$middlewareData2 = state.middlewareData.shift) != null && _state$middlewareData2.enabled.y) {\n availableHeight = maximumClippingHeight;\n }\n if (noShift && !alignment) {\n const xMin = max(overflow.left, 0);\n const xMax = max(overflow.right, 0);\n const yMin = max(overflow.top, 0);\n const yMax = max(overflow.bottom, 0);\n if (isYAxis) {\n availableWidth = width - 2 * (xMin !== 0 || xMax !== 0 ? xMin + xMax : max(overflow.left, overflow.right));\n } else {\n availableHeight = height - 2 * (yMin !== 0 || yMax !== 0 ? yMin + yMax : max(overflow.top, overflow.bottom));\n }\n }\n await apply({\n ...state,\n availableWidth,\n availableHeight\n });\n const nextDimensions = await platform.getDimensions(elements.floating);\n if (width !== nextDimensions.width || height !== nextDimensions.height) {\n return {\n reset: {\n rects: true\n }\n };\n }\n return {};\n }\n };\n};\n\nexport { arrow, autoPlacement, computePosition, detectOverflow, flip, hide, inline, limitShift, offset, shift, size };\n","import { rectToClientRect, arrow as arrow$1, autoPlacement as autoPlacement$1, detectOverflow as detectOverflow$1, flip as flip$1, hide as hide$1, inline as inline$1, limitShift as limitShift$1, offset as offset$1, shift as shift$1, size as size$1, computePosition as computePosition$1 } from '@floating-ui/core';\nimport { round, createCoords, max, min, floor } from '@floating-ui/utils';\nimport { getComputedStyle as getComputedStyle$1, isHTMLElement, isElement, getWindow, isWebKit, getFrameElement, getNodeScroll, getDocumentElement, isTopLayer, getNodeName, isOverflowElement, getOverflowAncestors, getParentNode, isLastTraversableNode, isContainingBlock, isTableElement, getContainingBlock } from '@floating-ui/utils/dom';\nexport { getOverflowAncestors } from '@floating-ui/utils/dom';\n\nfunction getCssDimensions(element) {\n const css = getComputedStyle$1(element);\n // In testing environments, the `width` and `height` properties are empty\n // strings for SVG elements, returning NaN. Fallback to `0` in this case.\n let width = parseFloat(css.width) || 0;\n let height = parseFloat(css.height) || 0;\n const hasOffset = isHTMLElement(element);\n const offsetWidth = hasOffset ? element.offsetWidth : width;\n const offsetHeight = hasOffset ? element.offsetHeight : height;\n const shouldFallback = round(width) !== offsetWidth || round(height) !== offsetHeight;\n if (shouldFallback) {\n width = offsetWidth;\n height = offsetHeight;\n }\n return {\n width,\n height,\n $: shouldFallback\n };\n}\n\nfunction unwrapElement(element) {\n return !isElement(element) ? element.contextElement : element;\n}\n\nfunction getScale(element) {\n const domElement = unwrapElement(element);\n if (!isHTMLElement(domElement)) {\n return createCoords(1);\n }\n const rect = domElement.getBoundingClientRect();\n const {\n width,\n height,\n $\n } = getCssDimensions(domElement);\n let x = ($ ? round(rect.width) : rect.width) / width;\n let y = ($ ? round(rect.height) : rect.height) / height;\n\n // 0, NaN, or Infinity should always fallback to 1.\n\n if (!x || !Number.isFinite(x)) {\n x = 1;\n }\n if (!y || !Number.isFinite(y)) {\n y = 1;\n }\n return {\n x,\n y\n };\n}\n\nconst noOffsets = /*#__PURE__*/createCoords(0);\nfunction getVisualOffsets(element) {\n const win = getWindow(element);\n if (!isWebKit() || !win.visualViewport) {\n return noOffsets;\n }\n return {\n x: win.visualViewport.offsetLeft,\n y: win.visualViewport.offsetTop\n };\n}\nfunction shouldAddVisualOffsets(element, isFixed, floatingOffsetParent) {\n if (isFixed === void 0) {\n isFixed = false;\n }\n if (!floatingOffsetParent || isFixed && floatingOffsetParent !== getWindow(element)) {\n return false;\n }\n return isFixed;\n}\n\nfunction getBoundingClientRect(element, includeScale, isFixedStrategy, offsetParent) {\n if (includeScale === void 0) {\n includeScale = false;\n }\n if (isFixedStrategy === void 0) {\n isFixedStrategy = false;\n }\n const clientRect = element.getBoundingClientRect();\n const domElement = unwrapElement(element);\n let scale = createCoords(1);\n if (includeScale) {\n if (offsetParent) {\n if (isElement(offsetParent)) {\n scale = getScale(offsetParent);\n }\n } else {\n scale = getScale(element);\n }\n }\n const visualOffsets = shouldAddVisualOffsets(domElement, isFixedStrategy, offsetParent) ? getVisualOffsets(domElement) : createCoords(0);\n let x = (clientRect.left + visualOffsets.x) / scale.x;\n let y = (clientRect.top + visualOffsets.y) / scale.y;\n let width = clientRect.width / scale.x;\n let height = clientRect.height / scale.y;\n if (domElement) {\n const win = getWindow(domElement);\n const offsetWin = offsetParent && isElement(offsetParent) ? getWindow(offsetParent) : offsetParent;\n let currentWin = win;\n let currentIFrame = getFrameElement(currentWin);\n while (currentIFrame && offsetParent && offsetWin !== currentWin) {\n const iframeScale = getScale(currentIFrame);\n const iframeRect = currentIFrame.getBoundingClientRect();\n const css = getComputedStyle$1(currentIFrame);\n const left = iframeRect.left + (currentIFrame.clientLeft + parseFloat(css.paddingLeft)) * iframeScale.x;\n const top = iframeRect.top + (currentIFrame.clientTop + parseFloat(css.paddingTop)) * iframeScale.y;\n x *= iframeScale.x;\n y *= iframeScale.y;\n width *= iframeScale.x;\n height *= iframeScale.y;\n x += left;\n y += top;\n currentWin = getWindow(currentIFrame);\n currentIFrame = getFrameElement(currentWin);\n }\n }\n return rectToClientRect({\n width,\n height,\n x,\n y\n });\n}\n\n// If <html> has a CSS width greater than the viewport, then this will be\n// incorrect for RTL.\nfunction getWindowScrollBarX(element, rect) {\n const leftScroll = getNodeScroll(element).scrollLeft;\n if (!rect) {\n return getBoundingClientRect(getDocumentElement(element)).left + leftScroll;\n }\n return rect.left + leftScroll;\n}\n\nfunction getHTMLOffset(documentElement, scroll) {\n const htmlRect = documentElement.getBoundingClientRect();\n const x = htmlRect.left + scroll.scrollLeft - getWindowScrollBarX(documentElement, htmlRect);\n const y = htmlRect.top + scroll.scrollTop;\n return {\n x,\n y\n };\n}\n\nfunction convertOffsetParentRelativeRectToViewportRelativeRect(_ref) {\n let {\n elements,\n rect,\n offsetParent,\n strategy\n } = _ref;\n const isFixed = strategy === 'fixed';\n const documentElement = getDocumentElement(offsetParent);\n const topLayer = elements ? isTopLayer(elements.floating) : false;\n if (offsetParent === documentElement || topLayer && isFixed) {\n return rect;\n }\n let scroll = {\n scrollLeft: 0,\n scrollTop: 0\n };\n let scale = createCoords(1);\n const offsets = createCoords(0);\n const isOffsetParentAnElement = isHTMLElement(offsetParent);\n if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {\n if (getNodeName(offsetParent) !== 'body' || isOverflowElement(documentElement)) {\n scroll = getNodeScroll(offsetParent);\n }\n if (isHTMLElement(offsetParent)) {\n const offsetRect = getBoundingClientRect(offsetParent);\n scale = getScale(offsetParent);\n offsets.x = offsetRect.x + offsetParent.clientLeft;\n offsets.y = offsetRect.y + offsetParent.clientTop;\n }\n }\n const htmlOffset = documentElement && !isOffsetParentAnElement && !isFixed ? getHTMLOffset(documentElement, scroll) : createCoords(0);\n return {\n width: rect.width * scale.x,\n height: rect.height * scale.y,\n x: rect.x * scale.x - scroll.scrollLeft * scale.x + offsets.x + htmlOffset.x,\n y: rect.y * scale.y - scroll.scrollTop * scale.y + offsets.y + htmlOffset.y\n };\n}\n\nfunction getClientRects(element) {\n return Array.from(element.getClientRects());\n}\n\n// Gets the entire size of the scrollable document area, even extending outside\n// of the `<html>` and `<body>` rect bounds if horizontally scrollable.\nfunction getDocumentRect(element) {\n const html = getDocumentElement(element);\n const scroll = getNodeScroll(element);\n const body = element.ownerDocument.body;\n const width = max(html.scrollWidth, html.clientWidth, body.scrollWidth, body.clientWidth);\n const height = max(html.scrollHeight, html.clientHeight, body.scrollHeight, body.clientHeight);\n let x = -scroll.scrollLeft + getWindowScrollBarX(element);\n const y = -scroll.scrollTop;\n if (getComputedStyle$1(body).direction === 'rtl') {\n x += max(html.clientWidth, body.clientWidth) - width;\n }\n return {\n width,\n height,\n x,\n y\n };\n}\n\n// Safety check: ensure the scrollbar space is reasonable in case this\n// calculation is affected by unusual styles.\n// Most scrollbars leave 15-18px of space.\nconst SCROLLBAR_MAX = 25;\nfunction getViewportRect(element, strategy) {\n const win = getWindow(element);\n const html = getDocumentElement(element);\n const visualViewport = win.visualViewport;\n let width = html.clientWidth;\n let height = html.clientHeight;\n let x = 0;\n let y = 0;\n if (visualViewport) {\n width = visualViewport.width;\n height = visualViewport.height;\n const visualViewportBased = isWebKit();\n if (!visualViewportBased || visualViewportBased && strategy === 'fixed') {\n x = visualViewport.offsetLeft;\n y = visualViewport.offsetTop;\n }\n }\n const windowScrollbarX = getWindowScrollBarX(html);\n // <html> `overflow: hidden` + `scrollbar-gutter: stable` reduces the\n // visual width of the <html> but this is not considered in the size\n // of `html.clientWidth`.\n if (windowScrollbarX <= 0) {\n const doc = html.ownerDocument;\n const body = doc.body;\n const bodyStyles = getComputedStyle(body);\n const bodyMarginInline = doc.compatMode === 'CSS1Compat' ? parseFloat(bodyStyles.marginLeft) + parseFloat(bodyStyles.marginRight) || 0 : 0;\n const clippingStableScrollbarWidth = Math.abs(html.clientWidth - body.clientWidth - bodyMarginInline);\n if (clippingStableScrollbarWidth <= SCROLLBAR_MAX) {\n width -= clippingStableScrollbarWidth;\n }\n } else if (windowScrollbarX <= SCROLLBAR_MAX) {\n // If the <body> scrollbar is on the left, the width needs to be extended\n // by the scrollbar amount so there isn't extra space on the right.\n width += windowScrollbarX;\n }\n return {\n width,\n height,\n x,\n y\n };\n}\n\nconst absoluteOrFixed = /*#__PURE__*/new Set(['absolute', 'fixed']);\n// Returns the inner client rect, subtracting scrollbars if present.\nfunction getInnerBoundingClientRect(element, strategy) {\n const clientRect = getBoundingClientRect(element, true, strategy === 'fixed');\n const top = clientRect.top + element.clientTop;\n const left = clientRect.left + element.clientLeft;\n const scale = isHTMLElement(element) ? getScale(element) : createCoords(1);\n const width = element.clientWidth * scale.x;\n const height = element.clientHeight * scale.y;\n const x = left * scale.x;\n const y = top * scale.y;\n return {\n width,\n height,\n x,\n y\n };\n}\nfunction getClientRectFromClippingAncestor(element, clippingAncestor, strategy) {\n let rect;\n if (clippingAncestor === 'viewport') {\n rect = getViewportRect(element, strategy);\n } else if (clippingAncestor === 'document') {\n rect = getDocumentRect(getDocumentElement(element));\n } else if (isElement(clippingAncestor)) {\n rect = getInnerBoundingClientRect(clippingAncestor, strategy);\n } else {\n const visualOffsets = getVisualOffsets(element);\n rect = {\n x: clippingAncestor.x - visualOffsets.x,\n y: clippingAncestor.y - visualOffsets.y,\n width: clippingAncestor.width,\n height: clippingAncestor.height\n };\n }\n return rectToClientRect(rect);\n}\nfunction hasFixedPositionAncestor(element, stopNode) {\n const parentNode = getParentNode(element);\n if (parentNode === stopNode || !isElement(parentNode) || isLastTraversableNode(parentNode)) {\n return false;\n }\n return getComputedStyle$1(parentNode).position === 'fixed' || hasFixedPositionAncestor(parentNode, stopNode);\n}\n\n// A \"clipping ancestor\" is an `overflow` element with the characteristic of\n// clipping (or hiding) child elements. This returns all clipping ancestors\n// of the given element up the tree.\nfunction getClippingElementAncestors(element, cache) {\n const cachedResult = cache.get(element);\n if (cachedResult) {\n return cachedResult;\n }\n let result = getOverflowAncestors(element, [], false).filter(el => isElement(el) && getNodeName(el) !== 'body');\n let currentContainingBlockComputedStyle = null;\n const elementIsFixed = getComputedStyle$1(element).position === 'fixed';\n let currentNode = elementIsFixed ? getParentNode(element) : element;\n\n // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block\n while (isElement(currentNode) && !isLastTraversableNode(currentNode)) {\n const computedStyle = getComputedStyle$1(currentNode);\n const currentNodeIsContaining = isContainingBlock(currentNode);\n if (!currentNodeIsContaining && computedStyle.position === 'fixed') {\n currentContainingBlockComputedStyle = null;\n }\n const shouldDropCurrentNode = elementIsFixed ? !currentNodeIsContaining && !currentContainingBlockComputedStyle : !currentNodeIsContaining && computedStyle.position === 'static' && !!currentContainingBlockComputedStyle && absoluteOrFixed.has(currentContainingBlockComputedStyle.position) || isOverflowElement(currentNode) && !currentNodeIsContaining && hasFixedPositionAncestor(element, currentNode);\n if (shouldDropCurrentNode) {\n // Drop non-containing blocks.\n result = result.filter(ancestor => ancestor !== currentNode);\n } else {\n // Record last containing block for next iteration.\n currentContainingBlockComputedStyle = computedStyle;\n }\n currentNode = getParentNode(currentNode);\n }\n cache.set(element, result);\n return result;\n}\n\n// Gets the maximum area that the element is visible in due to any number of\n// clipping ancestors.\nfunction getClippingRect(_ref) {\n let {\n element,\n boundary,\n rootBoundary,\n strategy\n } = _ref;\n const elementClippingAncestors = boundary === 'clippingAncestors' ? isTopLayer(element) ? [] : getClippingElementAncestors(element, this._c) : [].concat(boundary);\n const clippingAncestors = [...elementClippingAncestors, rootBoundary];\n const firstClippingAncestor = clippingAncestors[0];\n const clippingRect = clippingAncestors.reduce((accRect, clippingAncestor) => {\n const rect = getClientRectFromClippingAncestor(element, clippingAncestor, strategy);\n accRect.top = max(rect.top, accRect.top);\n accRect.right = min(rect.right, accRect.right);\n accRect.bottom = min(rect.bottom, accRect.bottom);\n accRect.left = max(rect.left, accRect.left);\n return accRect;\n }, getClientRectFromClippingAncestor(element, firstClippingAncestor, strategy));\n return {\n width: clippingRect.right - clippingRect.left,\n height: clippingRect.bottom - clippingRect.top,\n x: clippingRect.left,\n y: clippingRect.top\n };\n}\n\nfunction getDimensions(element) {\n const {\n width,\n height\n } = getCssDimensions(element);\n return {\n width,\n height\n };\n}\n\nfunction getRectRelativeToOffsetParent(element, offsetParent, strategy) {\n const isOffsetParentAnElement = isHTMLElement(offsetParent);\n const documentElement = getDocumentElement(offsetParent);\n const isFixed = strategy === 'fixed';\n const rect = getBoundingClientRect(element, true, isFixed, offsetParent);\n let scroll = {\n scrollLeft: 0,\n scrollTop: 0\n };\n const offsets = createCoords(0);\n\n // If the <body> scrollbar appears on the left (e.g. RTL systems). Use\n // Firefox with layout.scrollbar.side = 3 in about:config to test this.\n function setLeftRTLScrollbarOffset() {\n offsets.x = getWindowScrollBarX(documentElement);\n }\n if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {\n if (getNodeName(offsetParent) !== 'body' || isOverflowElement(documentElement)) {\n scroll = getNodeScroll(offsetParent);\n }\n if (isOffsetParentAnElement) {\n const offsetRect = getBoundingClientRect(offsetParent, true, isFixed, offsetParent);\n offsets.x = offsetRect.x + offsetParent.clientLeft;\n offsets.y = offsetRect.y + offsetParent.clientTop;\n } else if (documentElement) {\n setLeftRTLScrollbarOffset();\n }\n }\n if (isFixed && !isOffsetParentAnElement && documentElement) {\n setLeftRTLScrollbarOffset();\n }\n const htmlOffset = documentElement && !isOffsetParentAnElement && !isFixed ? getHTMLOffset(documentElement, scroll) : createCoords(0);\n const x = rect.left + scroll.scrollLeft - offsets.x - htmlOffset.x;\n const y = rect.top + scroll.scrollTop - offsets.y - htmlOffset.y;\n return {\n x,\n y,\n width: rect.width,\n height: rect.height\n };\n}\n\nfunction isStaticPositioned(element) {\n return getComputedStyle$1(element).position === 'static';\n}\n\nfunction getTrueOffsetParent(element, polyfill) {\n if (!isHTMLElement(element) || getComputedStyle$1(element).position === 'fixed') {\n return null;\n }\n if (polyfill) {\n return polyfill(element);\n }\n let rawOffsetParent = element.offsetParent;\n\n // Firefox returns the <html> element as the offsetParent if it's non-static,\n // while Chrome and Safari return the <body> element. The <body> element must\n // be used to perform the correct calculations even if the <html> element is\n // non-static.\n if (getDocumentElement(element) === rawOffsetParent) {\n rawOffsetParent = rawOffsetParent.ownerDocument.body;\n }\n return rawOffsetParent;\n}\n\n// Gets the closest ancestor positioned element. Handles some edge cases,\n// such as table ancestors and cross browser bugs.\nfunction getOffsetParent(element, polyfill) {\n const win = getWindow(element);\n if (isTopLayer(element)) {\n return win;\n }\n if (!isHTMLElement(element)) {\n let svgOffsetParent = getParentNode(element);\n while (svgOffsetParent && !isLastTraversableNode(svgOffsetParent)) {\n if (isElement(svgOffsetParent) && !isStaticPositioned(svgOffsetParent)) {\n return svgOffsetParent;\n }\n svgOffsetParent = getParentNode(svgOffsetParent);\n }\n return win;\n }\n let offsetParent = getTrueOffsetParent(element, polyfill);\n while (offsetParent && isTableElement(offsetParent) && isStaticPositioned(offsetParent)) {\n offsetParent = getTrueOffsetParent(offsetParent, polyfill);\n }\n if (offsetParent && isLastTraversableNode(offsetParent) && isStaticPositioned(offsetParent) && !isContainingBlock(offsetParent)) {\n return win;\n }\n return offsetParent || getContainingBlock(element) || win;\n}\n\nconst getElementRects = async function (data) {\n const getOffsetParentFn = this.getOffsetParent || getOffsetParent;\n const getDimensionsFn = this.getDimensions;\n const floatingDimensions = await getDimensionsFn(data.floating);\n return {\n reference: getRectRelativeToOffsetParent(data.reference, await getOffsetParentFn(data.floating), data.strategy),\n floating: {\n x: 0,\n y: 0,\n width: floatingDimensions.width,\n height: floatingDimensions.height\n }\n };\n};\n\nfunction isRTL(element) {\n return getComputedStyle$1(element).direction === 'rtl';\n}\n\nconst platform = {\n convertOffsetParentRelativeRectToViewportRelativeRect,\n getDocumentElement,\n getClippingRect,\n getOffsetParent,\n getElementRects,\n getClientRects,\n getDimensions,\n getScale,\n isElement,\n isRTL\n};\n\nfunction rectsAreEqual(a, b) {\n return a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height;\n}\n\n// https://samthor.au/2021/observing-dom/\nfunction observeMove(element, onMove) {\n let io = null;\n let timeoutId;\n const root = getDocumentElement(element);\n function cleanup() {\n var _io;\n clearTimeout(timeoutId);\n (_io = io) == null || _io.disconnect();\n io = null;\n }\n function refresh(skip, threshold) {\n if (skip === void 0) {\n skip = false;\n }\n if (threshold === void 0) {\n threshold = 1;\n }\n cleanup();\n const elementRectForRootMargin = element.getBoundingClientRect();\n const {\n left,\n top,\n width,\n height\n } = elementRectForRootMargin;\n if (!skip) {\n onMove();\n }\n if (!width || !height) {\n return;\n }\n const insetTop = floor(top);\n const insetRight = floor(root.clientWidth - (left + width));\n const insetBottom = floor(root.clientHeight - (top + height));\n const insetLeft = floor(left);\n const rootMargin = -insetTop + \"px \" + -insetRight + \"px \" + -insetBottom + \"px \" + -insetLeft + \"px\";\n const options = {\n rootMargin,\n threshold: max(0, min(1, threshold)) || 1\n };\n let isFirstUpdate = true;\n function handleObserve(entries) {\n const ratio = entries[0].intersectionRatio;\n if (ratio !== threshold) {\n if (!isFirstUpdate) {\n return refresh();\n }\n if (!ratio) {\n // If the reference is clipped, the ratio is 0. Throttle the refresh\n // to prevent an infinite loop of updates.\n timeoutId = setTimeout(() => {\n refresh(false, 1e-7);\n }, 1000);\n } else {\n refresh(false, ratio);\n }\n }\n if (ratio === 1 && !rectsAreEqual(elementRectForRootMargin, element.getBoundingClientRect())) {\n // It's possible that even though the ratio is reported as 1, the\n // element is not actually fully within the IntersectionObserver's root\n // area anymore. This can happen under performance constraints. This may\n // be a bug in the browser's IntersectionObserver implementation. To\n // work around this, we compare the element's bounding rect now with\n // what it was at the time we created the IntersectionObserver. If they\n // are not equal then the element moved, so we refresh.\n refresh();\n }\n isFirstUpdate = false;\n }\n\n // Older browsers don't support a `document` as the root and will throw an\n // error.\n try {\n io = new IntersectionObserver(handleObserve, {\n ...options,\n // Handle <iframe>s\n root: root.ownerDocument\n });\n } catch (_e) {\n io = new IntersectionObserver(handleObserve, options);\n }\n io.observe(element);\n }\n refresh(true);\n return cleanup;\n}\n\n/**\n * Automatically updates the position of the floating element when necessary.\n * Should only be called when the floating element is mounted on the DOM or\n * visible on the screen.\n * @returns cleanup function that should be invoked when the floating element is\n * removed from the DOM or hidden from the screen.\n * @see https://floating-ui.com/docs/autoUpdate\n */\nfunction autoUpdate(reference, floating, update, options) {\n if (options === void 0) {\n options = {};\n }\n const {\n ancestorScroll = true,\n ancestorResize = true,\n elementResize = typeof ResizeObserver === 'function',\n layoutShift = typeof IntersectionObserver === 'function',\n animationFrame = false\n } = options;\n const referenceEl = unwrapElement(reference);\n const ancestors = ancestorScroll || ancestorResize ? [...(referenceEl ? getOverflowAncestors(referenceEl) : []), ...getOverflowAncestors(floating)] : [];\n ancestors.forEach(ancestor => {\n ancestorScroll && ancestor.addEventListener('scroll', update, {\n passive: true\n });\n ancestorResize && ancestor.addEventListener('resize', update);\n });\n const cleanupIo = referenceEl && layoutShift ? observeMove(referenceEl, update) : null;\n let reobserveFrame = -1;\n let resizeObserver = null;\n if (elementResize) {\n resizeObserver = new ResizeObserver(_ref => {\n let [firstEntry] = _ref;\n if (firstEntry && firstEntry.target === referenceEl && resizeObserver) {\n // Prevent update loops when using the `size` middleware.\n // https://github.com/floating-ui/floating-ui/issues/1740\n resizeObserver.unobserve(floating);\n cancelAnimationFrame(reobserveFrame);\n reobserveFrame = requestAnimationFrame(() => {\n var _resizeObserver;\n (_resizeObserver = resizeObserver) == null || _resizeObserver.observe(floating);\n });\n }\n update();\n });\n if (referenceEl && !animationFrame) {\n resizeObserver.observe(referenceEl);\n }\n resizeObserver.observe(floating);\n }\n let frameId;\n let prevRefRect = animationFrame ? getBoundingClientRect(reference) : null;\n if (animationFrame) {\n frameLoop();\n }\n function frameLoop() {\n const nextRefRect = getBoundingClientRect(reference);\n if (prevRefRect && !rectsAreEqual(prevRefRect, nextRefRect)) {\n update();\n }\n prevRefRect = nextRefRect;\n frameId = requestAnimationFrame(frameLoop);\n }\n update();\n return () => {\n var _resizeObserver2;\n ancestors.forEach(ancestor => {\n ancestorScroll && ancestor.removeEventListener('scroll', update);\n ancestorResize && ancestor.removeEventListener('resize', update);\n });\n cleanupIo == null || cleanupIo();\n (_resizeObserver2 = resizeObserver) == null || _resizeObserver2.disconnect();\n resizeObserver = null;\n if (animationFrame) {\n cancelAnimationFrame(frameId);\n }\n };\n}\n\n/**\n * Resolves with an object of overflow side offsets that determine how much the\n * element is overflowing a given clipping boundary on each side.\n * - positive = overflowing the boundary by that number of pixels\n * - negative = how many pixels left before it will overflow\n * - 0 = lies flush with the boundary\n * @see https://floating-ui.com/docs/detectOverflow\n */\nconst detectOverflow = detectOverflow$1;\n\n/**\n * Modifies the placement by translating the floating element along the\n * specified axes.\n * A number (shorthand for `mainAxis` or distance), or an axes configuration\n * object may be passed.\n * @see https://floating-ui.com/docs/offset\n */\nconst offset = offset$1;\n\n/**\n * Optimizes the visibility of the floating element by choosing the placement\n * that has the most space available automatically, without needing to specify a\n * preferred placement. Alternative to `flip`.\n * @see https://floating-ui.com/docs/autoPlacement\n */\nconst autoPlacement = autoPlacement$1;\n\n/**\n * Optimizes the visibility of the floating element by shifting it in order to\n * keep it in view when it will overflow the clipping boundary.\n * @see https://floating-ui.com/docs/shift\n */\nconst shift = shift$1;\n\n/**\n * Optimizes the visibility of the floating element by flipping the `placement`\n * in order to keep it in view when the preferred placement(s) will overflow the\n * clipping boundary. Alternative to `autoPlacement`.\n * @see https://floating-ui.com/docs/flip\n */\nconst flip = flip$1;\n\n/**\n * Provides data that allows you to change the size of the floating element —\n * for instance, prevent it from overflowing the clipping boundary or match the\n * width of the reference element.\n * @see https://floating-ui.com/docs/size\n */\nconst size = size$1;\n\n/**\n * Provides data to hide the floating element in applicable situations, such as\n * when it is not in the same clipping context as the reference element.\n * @see https://floating-ui.com/docs/hide\n */\nconst hide = hide$1;\n\n/**\n * Provides data to position an inner element of the floating element so that it\n * appears centered to the reference element.\n * @see https://floating-ui.com/docs/arrow\n */\nconst arrow = arrow$1;\n\n/**\n * Provides improved positioning for inline reference elements that can span\n * over multiple lines, such as hyperlinks or range selections.\n * @see https://floating-ui.com/docs/inline\n */\nconst inline = inline$1;\n\n/**\n * Built-in `limiter` that will stop `shift()` at a certain point.\n */\nconst limitShift = limitShift$1;\n\n/**\n * Computes the `x` and `y` coordinates that will place the floating element\n * next to a given reference element.\n */\nconst computePosition = (reference, floating, options) => {\n // This caches the expensive `getClippingElementAncestors` function so that\n // multiple lifecycle resets re-use the same result. It only lives for a\n // single call. If other functions become expensive, we can add them as well.\n const cache = new Map();\n const mergedOptions = {\n platform,\n ...options\n };\n const platformWithCache = {\n ...mergedOptions.platform,\n _c: cache\n };\n return computePosition$1(reference, floating, {\n ...mergedOptions,\n platform: platformWithCache\n });\n};\n\nexport { arrow, autoPlacement, autoUpdate, computePosition, detectOverflow, flip, hide, inline, limitShift, offset, platform, shift, size };\n","import { computePosition, arrow as arrow$2, autoPlacement as autoPlacement$1, flip as flip$1, hide as hide$1, inline as inline$1, limitShift as limitShift$1, offset as offset$1, shift as shift$1, size as size$1 } from '@floating-ui/dom';\nexport { autoUpdate, computePosition, detectOverflow, getOverflowAncestors, platform } from '@floating-ui/dom';\nimport * as React from 'react';\nimport { useLayoutEffect } from 'react';\nimport * as ReactDOM from 'react-dom';\n\nvar isClient = typeof document !== 'undefined';\n\nvar noop = function noop() {};\nvar index = isClient ? useLayoutEffect : noop;\n\n// Fork of `fast-deep-equal` that only does the comparisons we need and compares\n// functions\nfunction deepEqual(a, b) {\n if (a === b) {\n return true;\n }\n if (typeof a !== typeof b) {\n return false;\n }\n if (typeof a === 'function' && a.toString() === b.toString()) {\n return true;\n }\n let length;\n let i;\n let keys;\n if (a && b && typeof a === 'object') {\n if (Array.isArray(a)) {\n length = a.length;\n if (length !== b.length) return false;\n for (i = length; i-- !== 0;) {\n if (!deepEqual(a[i], b[i])) {\n return false;\n }\n }\n return true;\n }\n keys = Object.keys(a);\n length = keys.length;\n if (length !== Object.keys(b).length) {\n return false;\n }\n for (i = length; i-- !== 0;) {\n if (!{}.hasOwnProperty.call(b, keys[i])) {\n return false;\n }\n }\n for (i = length; i-- !== 0;) {\n const key = keys[i];\n if (key === '_owner' && a.$$typeof) {\n continue;\n }\n if (!deepEqual(a[key], b[key])) {\n return false;\n }\n }\n return true;\n }\n return a !== a && b !== b;\n}\n\nfunction getDPR(element) {\n if (typeof window === 'undefined') {\n return 1;\n }\n const win = element.ownerDocument.defaultView || window;\n return win.devicePixelRatio || 1;\n}\n\nfunction roundByDPR(element, value) {\n const dpr = getDPR(element);\n return Math.round(value * dpr) / dpr;\n}\n\nfunction useLatestRef(value) {\n const ref = React.useRef(value);\n index(() => {\n ref.current = value;\n });\n return ref;\n}\n\n/**\n * Provides data to position a floating element.\n * @see https://floating-ui.com/docs/useFloating\n */\nfunction useFloating(options) {\n if (options === void 0) {\n options = {};\n }\n const {\n placement = 'bottom',\n strategy = 'absolute',\n middleware = [],\n platform,\n elements: {\n reference: externalReference,\n floating: externalFloating\n } = {},\n transform = true,\n whileElementsMounted,\n open\n } = options;\n const [data, setData] = React.useState({\n x: 0,\n y: 0,\n strategy,\n placement,\n middlewareData: {},\n isPositioned: false\n });\n const [latestMiddleware, setLatestMiddleware] = React.useState(middleware);\n if (!deepEqual(latestMiddleware, middleware)) {\n setLatestMiddleware(middleware);\n }\n const [_reference, _setReference] = React.useState(null);\n const [_floating, _setFloating] = React.useState(null);\n const setReference = React.useCallback(node => {\n if (node !== referenceRef.current) {\n referenceRef.current = node;\n _setReference(node);\n }\n }, []);\n const setFloating = React.useCallback(node => {\n if (node !== floatingRef.current) {\n floatingRef.current = node;\n _setFloating(node);\n }\n }, []);\n const referenceEl = externalReference || _reference;\n const floatingEl = externalFloating || _floating;\n const referenceRef = React.useRef(null);\n const floatingRef = React.useRef(null);\n const dataRef = React.useRef(data);\n const hasWhileElementsMounted = whileElementsMounted != null;\n const whileElementsMountedRef = useLatestRef(whileElementsMounted);\n const platformRef = useLatestRef(platform);\n const openRef = useLatestRef(open);\n const update = React.useCallback(() => {\n if (!referenceRef.current || !floatingRef.current) {\n return;\n }\n const config = {\n placement,\n strategy,\n middleware: latestMiddleware\n };\n if (platformRef.current) {\n config.platform = platformRef.current;\n }\n computePosition(referenceRef.current, floatingRef.current, config).then(data => {\n const fullData = {\n ...data,\n // The floating element's position may be recomputed while it's closed\n // but still mounted (such as when transitioning out). To ensure\n // `isPositioned` will be `false` initially on the next open, avoid\n // setting it to `true` when `open === false` (must be specified).\n isPositioned: openRef.current !== false\n };\n if (isMountedRef.current && !deepEqual(dataRef.current, fullData)) {\n dataRef.current = fullData;\n ReactDOM.flushSync(() => {\n setData(fullData);\n });\n }\n });\n }, [latestMiddleware, placement, strategy, platformRef, openRef]);\n index(() => {\n if (open === false && dataRef.current.isPositioned) {\n dataRef.current.isPositioned = false;\n setData(data => ({\n ...data,\n isPositioned: false\n }));\n }\n }, [open]);\n const isMountedRef = React.useRef(false);\n index(() => {\n isMountedRef.current = true;\n return () => {\n isMountedRef.current = false;\n };\n }, []);\n index(() => {\n if (referenceEl) referenceRef.current = referenceEl;\n if (floatingEl) floatingRef.current = floatingEl;\n if (referenceEl && floatingEl) {\n if (whileElementsMountedRef.current) {\n return whileElementsMountedRef.current(referenceEl, floatingEl, update);\n }\n update();\n }\n }, [referenceEl, floatingEl, update, whileElementsMountedRef, hasWhileElementsMounted]);\n const refs = React.useMemo(() => ({\n reference: referenceRef,\n floating: floatingRef,\n setReference,\n setFloating\n }), [setReference, setFloating]);\n const elements = React.useMemo(() => ({\n reference: referenceEl,\n floating: floatingEl\n }), [referenceEl, floatingEl]);\n const floatingStyles = React.useMemo(() => {\n const initialStyles = {\n position: strategy,\n left: 0,\n top: 0\n };\n if (!elements.floating) {\n return initialStyles;\n }\n const x = roundByDPR(elements.floating, data.x);\n const y = roundByDPR(elements.floating, data.y);\n if (transform) {\n return {\n ...initialStyles,\n transform: \"translate(\" + x + \"px, \" + y + \"px)\",\n ...(getDPR(elements.floating) >= 1.5 && {\n willChange: 'transform'\n })\n };\n }\n return {\n position: strategy,\n left: x,\n top: y\n };\n }, [strategy, transform, elements.floating, data.x, data.y]);\n return React.useMemo(() => ({\n ...data,\n update,\n refs,\n elements,\n floatingStyles\n }), [data, update, refs, elements, floatingStyles]);\n}\n\n/**\n * Provides data to position an inner element of the floating element so that it\n * appears centered to the reference element.\n * This wraps the core `arrow` middleware to allow React refs as the element.\n * @see https://floating-ui.com/docs/arrow\n */\nconst arrow$1 = options => {\n function isRef(value) {\n return {}.hasOwnProperty.call(value, 'current');\n }\n return {\n name: 'arrow',\n options,\n fn(state) {\n const {\n element,\n padding\n } = typeof options === 'function' ? options(state) : options;\n if (element && isRef(element)) {\n if (element.current != null) {\n return arrow$2({\n element: element.current,\n padding\n }).fn(state);\n }\n return {};\n }\n if (element) {\n return arrow$2({\n element,\n padding\n }).fn(state);\n }\n return {};\n }\n };\n};\n\n/**\n * Modifies the placement by translating the floating element along the\n * specified axes.\n * A number (shorthand for `mainAxis` or distance), or an axes configuration\n * object may be passed.\n * @see https://floating-ui.com/docs/offset\n */\nconst offset = (options, deps) => ({\n ...offset$1(options),\n options: [options, deps]\n});\n\n/**\n * Optimizes the visibility of the floating element by shifting it in order to\n * keep it in view when it will overflow the clipping boundary.\n * @see https://floating-ui.com/docs/shift\n */\nconst shift = (options, deps) => ({\n ...shift$1(options),\n options: [options, deps]\n});\n\n/**\n * Built-in `limiter` that will stop `shift()` at a certain point.\n */\nconst limitShift = (options, deps) => ({\n ...limitShift$1(options),\n options: [options, deps]\n});\n\n/**\n * Optimizes the visibility of the floating element by flipping the `placement`\n * in order to keep it in view when the preferred placement(s) will overflow the\n * clipping boundary. Alternative to `autoPlacement`.\n * @see https://floating-ui.com/docs/flip\n */\nconst flip = (options, deps) => ({\n ...flip$1(options),\n options: [options, deps]\n});\n\n/**\n * Provides data that allows you to change the size of the floating element —\n * for instance, prevent it from overflowing the clipping boundary or match the\n * width of the reference element.\n * @see https://floating-ui.com/docs/size\n */\nconst size = (options, deps) => ({\n ...size$1(options),\n options: [options, deps]\n});\n\n/**\n * Optimizes the visibility of the floating element by choosing the placement\n * that has the most space available automatically, without needing to specify a\n * preferred placement. Alternative to `flip`.\n * @see https://floating-ui.com/docs/autoPlacement\n */\nconst autoPlacement = (options, deps) => ({\n ...autoPlacement$1(options),\n options: [options, deps]\n});\n\n/**\n * Provides data to hide the floating element in applicable situations, such as\n * when it is not in the same clipping context as the reference element.\n * @see https://floating-ui.com/docs/hide\n */\nconst hide = (options, deps) => ({\n ...hide$1(options),\n options: [options, deps]\n});\n\n/**\n * Provides improved positioning for inline reference elements that can span\n * over multiple lines, such as hyperlinks or range selections.\n * @see https://floating-ui.com/docs/inline\n */\nconst inline = (options, deps) => ({\n ...inline$1(options),\n options: [options, deps]\n});\n\n/**\n * Provides data to position an inner element of the floating element so that it\n * appears centered to the reference element.\n * This wraps the core `arrow` middleware to allow React refs as the element.\n * @see https://floating-ui.com/docs/arrow\n */\nconst arrow = (options, deps) => ({\n ...arrow$1(options),\n options: [options, deps]\n});\n\nexport { arrow, autoPlacement, flip, hide, inline, limitShift, offset, shift, size, useFloating };\n","import * as React from 'react';\nimport { useModernLayoutEffect, useEffectEvent, getMinListIndex, getMaxListIndex, createGridCellMap, isListIndexDisabled, getGridNavigatedIndex, getGridCellIndexOfCorner, getGridCellIndices, findNonDisabledListIndex, isIndexOutOfListBounds, useLatestRef, getDocument as getDocument$1, isMouseLikePointerType, contains as contains$1, isSafari, enableFocusInside, isOutsideEvent, getPreviousTabbable, getNextTabbable, disableFocusInside, isTypeableCombobox, getFloatingFocusElement, getTabbableOptions, getNodeAncestors, activeElement, getNodeChildren as getNodeChildren$1, stopEvent, getTarget as getTarget$1, isVirtualClick, isVirtualPointerEvent, getPlatform, isTypeableElement, isReactEvent, isRootElement, isEventTargetWithin, matchesFocusVisible, isMac, getDeepestNode, getUserAgent } from '@floating-ui/react/utils';\nimport { jsx, jsxs, Fragment } from 'react/jsx-runtime';\nimport { getComputedStyle, isElement, isShadowRoot, getNodeName, isNode, isHTMLElement, getWindow, isLastTraversableNode, getParentNode, isWebKit } from '@floating-ui/utils/dom';\nimport { tabbable, isTabbable, focusable } from 'tabbable';\nimport * as ReactDOM from 'react-dom';\nimport { getOverflowAncestors, useFloating as useFloating$1, offset } from '@floating-ui/react-dom';\nexport { arrow, autoPlacement, autoUpdate, computePosition, detectOverflow, flip, getOverflowAncestors, hide, inline, limitShift, offset, platform, shift, size } from '@floating-ui/react-dom';\nimport { evaluate, max, round, min } from '@floating-ui/utils';\n\n/**\n * Merges an array of refs into a single memoized callback ref or `null`.\n * @see https://floating-ui.com/docs/react-utils#usemergerefs\n */\nfunction useMergeRefs(refs) {\n const cleanupRef = React.useRef(undefined);\n const refEffect = React.useCallback(instance => {\n const cleanups = refs.map(ref => {\n if (ref == null) {\n return;\n }\n if (typeof ref === 'function') {\n const refCallback = ref;\n const refCleanup = refCallback(instance);\n return typeof refCleanup === 'function' ? refCleanup : () => {\n refCallback(null);\n };\n }\n ref.current = instance;\n return () => {\n ref.current = null;\n };\n });\n return () => {\n cleanups.forEach(refCleanup => refCleanup == null ? void 0 : refCleanup());\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, refs);\n return React.useMemo(() => {\n if (refs.every(ref => ref == null)) {\n return null;\n }\n return value => {\n if (cleanupRef.current) {\n cleanupRef.current();\n cleanupRef.current = undefined;\n }\n if (value != null) {\n cleanupRef.current = refEffect(value);\n }\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, refs);\n}\n\nfunction sortByDocumentPosition(a, b) {\n const position = a.compareDocumentPosition(b);\n if (position & Node.DOCUMENT_POSITION_FOLLOWING || position & Node.DOCUMENT_POSITION_CONTAINED_BY) {\n return -1;\n }\n if (position & Node.DOCUMENT_POSITION_PRECEDING || position & Node.DOCUMENT_POSITION_CONTAINS) {\n return 1;\n }\n return 0;\n}\nconst FloatingListContext = /*#__PURE__*/React.createContext({\n register: () => {},\n unregister: () => {},\n map: /*#__PURE__*/new Map(),\n elementsRef: {\n current: []\n }\n});\n/**\n * Provides context for a list of items within the floating element.\n * @see https://floating-ui.com/docs/FloatingList\n */\nfunction FloatingList(props) {\n const {\n children,\n elementsRef,\n labelsRef\n } = props;\n const [nodes, setNodes] = React.useState(() => new Set());\n const register = React.useCallback(node => {\n setNodes(prevSet => new Set(prevSet).add(node));\n }, []);\n const unregister = React.useCallback(node => {\n setNodes(prevSet => {\n const set = new Set(prevSet);\n set.delete(node);\n return set;\n });\n }, []);\n const map = React.useMemo(() => {\n const newMap = new Map();\n const sortedNodes = Array.from(nodes.keys()).sort(sortByDocumentPosition);\n sortedNodes.forEach((node, index) => {\n newMap.set(node, index);\n });\n return newMap;\n }, [nodes]);\n return /*#__PURE__*/jsx(FloatingListContext.Provider, {\n value: React.useMemo(() => ({\n register,\n unregister,\n map,\n elementsRef,\n labelsRef\n }), [register, unregister, map, elementsRef, labelsRef]),\n children: children\n });\n}\n/**\n * Used to register a list item and its index (DOM position) in the\n * `FloatingList`.\n * @see https://floating-ui.com/docs/FloatingList#uselistitem\n */\nfunction useListItem(props) {\n if (props === void 0) {\n props = {};\n }\n const {\n label\n } = props;\n const {\n register,\n unregister,\n map,\n elementsRef,\n labelsRef\n } = React.useContext(FloatingListContext);\n const [index, setIndex] = React.useState(null);\n const componentRef = React.useRef(null);\n const ref = React.useCallback(node => {\n componentRef.current = node;\n if (index !== null) {\n elementsRef.current[index] = node;\n if (labelsRef) {\n var _node$textContent;\n const isLabelDefined = label !== undefined;\n labelsRef.current[index] = isLabelDefined ? label : (_node$textContent = node == null ? void 0 : node.textContent) != null ? _node$textContent : null;\n }\n }\n }, [index, elementsRef, labelsRef, label]);\n useModernLayoutEffect(() => {\n const node = componentRef.current;\n if (node) {\n register(node);\n return () => {\n unregister(node);\n };\n }\n }, [register, unregister]);\n useModernLayoutEffect(() => {\n const index = componentRef.current ? map.get(componentRef.current) : null;\n if (index != null) {\n setIndex(index);\n }\n }, [map]);\n return React.useMemo(() => ({\n ref,\n index: index == null ? -1 : index\n }), [index, ref]);\n}\n\nconst FOCUSABLE_ATTRIBUTE = 'data-floating-ui-focusable';\nconst ACTIVE_KEY = 'active';\nconst SELECTED_KEY = 'selected';\nconst ARROW_LEFT = 'ArrowLeft';\nconst ARROW_RIGHT = 'ArrowRight';\nconst ARROW_UP = 'ArrowUp';\nconst ARROW_DOWN = 'ArrowDown';\n\nfunction renderJsx(render, computedProps) {\n if (typeof render === 'function') {\n return render(computedProps);\n }\n if (render) {\n return /*#__PURE__*/React.cloneElement(render, computedProps);\n }\n return /*#__PURE__*/jsx(\"div\", {\n ...computedProps\n });\n}\nconst CompositeContext = /*#__PURE__*/React.createContext({\n activeIndex: 0,\n onNavigate: () => {}\n});\nconst horizontalKeys = [ARROW_LEFT, ARROW_RIGHT];\nconst verticalKeys = [ARROW_UP, ARROW_DOWN];\nconst allKeys = [...horizontalKeys, ...verticalKeys];\n\n/**\n * Creates a single tab stop whose items are navigated by arrow keys, which\n * provides list navigation outside of floating element contexts.\n *\n * This is useful to enable navigation of a list of items that aren’t part of a\n * floating element. A menubar is an example of a composite, with each reference\n * element being an item.\n * @see https://floating-ui.com/docs/Composite\n */\nconst Composite = /*#__PURE__*/React.forwardRef(function Composite(props, forwardedRef) {\n const {\n render,\n orientation = 'both',\n loop = true,\n rtl = false,\n cols = 1,\n disabledIndices,\n activeIndex: externalActiveIndex,\n onNavigate: externalSetActiveIndex,\n itemSizes,\n dense = false,\n ...domProps\n } = props;\n const [internalActiveIndex, internalSetActiveIndex] = React.useState(0);\n const activeIndex = externalActiveIndex != null ? externalActiveIndex : internalActiveIndex;\n const onNavigate = useEffectEvent(externalSetActiveIndex != null ? externalSetActiveIndex : internalSetActiveIndex);\n const elementsRef = React.useRef([]);\n const renderElementProps = render && typeof render !== 'function' ? render.props : {};\n const contextValue = React.useMemo(() => ({\n activeIndex,\n onNavigate\n }), [activeIndex, onNavigate]);\n const isGrid = cols > 1;\n function handleKeyDown(event) {\n if (!allKeys.includes(event.key)) return;\n let nextIndex = activeIndex;\n const minIndex = getMinListIndex(elementsRef, disabledIndices);\n const maxIndex = getMaxListIndex(elementsRef, disabledIndices);\n const horizontalEndKey = rtl ? ARROW_LEFT : ARROW_RIGHT;\n const horizontalStartKey = rtl ? ARROW_RIGHT : ARROW_LEFT;\n if (isGrid) {\n const sizes = itemSizes || Array.from({\n length: elementsRef.current.length\n }, () => ({\n width: 1,\n height: 1\n }));\n // To calculate movements on the grid, we use hypothetical cell indices\n // as if every item was 1x1, then convert back to real indices.\n const cellMap = createGridCellMap(sizes, cols, dense);\n const minGridIndex = cellMap.findIndex(index => index != null && !isListIndexDisabled(elementsRef, index, disabledIndices));\n // last enabled index\n const maxGridIndex = cellMap.reduce((foundIndex, index, cellIndex) => index != null && !isListIndexDisabled(elementsRef, index, disabledIndices) ? cellIndex : foundIndex, -1);\n const maybeNextIndex = cellMap[getGridNavigatedIndex({\n current: cellMap.map(itemIndex => itemIndex ? elementsRef.current[itemIndex] : null)\n }, {\n event,\n orientation,\n loop,\n rtl,\n cols,\n // treat undefined (empty grid spaces) as disabled indices so we\n // don't end up in them\n disabledIndices: getGridCellIndices([...((typeof disabledIndices !== 'function' ? disabledIndices : null) || elementsRef.current.map((_, index) => isListIndexDisabled(elementsRef, index, disabledIndices) ? index : undefined)), undefined], cellMap),\n minIndex: minGridIndex,\n maxIndex: maxGridIndex,\n prevIndex: getGridCellIndexOfCorner(activeIndex > maxIndex ? minIndex : activeIndex, sizes, cellMap, cols,\n // use a corner matching the edge closest to the direction we're\n // moving in so we don't end up in the same item. Prefer\n // top/left over bottom/right.\n event.key === ARROW_DOWN ? 'bl' : event.key === horizontalEndKey ? 'tr' : 'tl')\n })];\n if (maybeNextIndex != null) {\n nextIndex = maybeNextIndex;\n }\n }\n const toEndKeys = {\n horizontal: [horizontalEndKey],\n vertical: [ARROW_DOWN],\n both: [horizontalEndKey, ARROW_DOWN]\n }[orientation];\n const toStartKeys = {\n horizontal: [horizontalStartKey],\n vertical: [ARROW_UP],\n both: [horizontalStartKey, ARROW_UP]\n }[orientation];\n const preventedKeys = isGrid ? allKeys : {\n horizontal: horizontalKeys,\n vertical: verticalKeys,\n both: allKeys\n }[orientation];\n if (nextIndex === activeIndex && [...toEndKeys, ...toStartKeys].includes(event.key)) {\n if (loop && nextIndex === maxIndex && toEndKeys.includes(event.key)) {\n nextIndex = minIndex;\n } else if (loop && nextIndex === minIndex && toStartKeys.includes(event.key)) {\n nextIndex = maxIndex;\n } else {\n nextIndex = findNonDisabledListIndex(elementsRef, {\n startingIndex: nextIndex,\n decrement: toStartKeys.includes(event.key),\n disabledIndices\n });\n }\n }\n if (nextIndex !== activeIndex && !isIndexOutOfListBounds(elementsRef, nextIndex)) {\n var _elementsRef$current$;\n event.stopPropagation();\n if (preventedKeys.includes(event.key)) {\n event.preventDefault();\n }\n onNavigate(nextIndex);\n (_elementsRef$current$ = elementsRef.current[nextIndex]) == null || _elementsRef$current$.focus();\n }\n }\n const computedProps = {\n ...domProps,\n ...renderElementProps,\n ref: forwardedRef,\n 'aria-orientation': orientation === 'both' ? undefined : orientation,\n onKeyDown(e) {\n domProps.onKeyDown == null || domProps.onKeyDown(e);\n renderElementProps.onKeyDown == null || renderElementProps.onKeyDown(e);\n handleKeyDown(e);\n }\n };\n return /*#__PURE__*/jsx(CompositeContext.Provider, {\n value: contextValue,\n children: /*#__PURE__*/jsx(FloatingList, {\n elementsRef: elementsRef,\n children: renderJsx(render, computedProps)\n })\n });\n});\n/**\n * @see https://floating-ui.com/docs/Composite\n */\nconst CompositeItem = /*#__PURE__*/React.forwardRef(function CompositeItem(props, forwardedRef) {\n const {\n render,\n ...domProps\n } = props;\n const renderElementProps = render && typeof render !== 'function' ? render.props : {};\n const {\n activeIndex,\n onNavigate\n } = React.useContext(CompositeContext);\n const {\n ref,\n index\n } = useListItem();\n const mergedRef = useMergeRefs([ref, forwardedRef, renderElementProps.ref]);\n const isActive = activeIndex === index;\n const computedProps = {\n ...domProps,\n ...renderElementProps,\n ref: mergedRef,\n tabIndex: isActive ? 0 : -1,\n 'data-active': isActive ? '' : undefined,\n onFocus(e) {\n domProps.onFocus == null || domProps.onFocus(e);\n renderElementProps.onFocus == null || renderElementProps.onFocus(e);\n onNavigate(index);\n }\n };\n return renderJsx(render, computedProps);\n});\n\n// https://github.com/mui/material-ui/issues/41190#issuecomment-2040873379\nconst SafeReact = {\n ...React\n};\n\nlet serverHandoffComplete = false;\nlet count = 0;\nconst genId = () => // Ensure the id is unique with multiple independent versions of Floating UI\n// on <React 18\n\"floating-ui-\" + Math.random().toString(36).slice(2, 6) + count++;\nfunction useFloatingId() {\n const [id, setId] = React.useState(() => serverHandoffComplete ? genId() : undefined);\n useModernLayoutEffect(() => {\n if (id == null) {\n setId(genId());\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n React.useEffect(() => {\n serverHandoffComplete = true;\n }, []);\n return id;\n}\nconst useReactId = SafeReact.useId;\n\n/**\n * Uses React 18's built-in `useId()` when available, or falls back to a\n * slightly less performant (requiring a double render) implementation for\n * earlier React versions.\n * @see https://floating-ui.com/docs/react-utils#useid\n */\nconst useId = useReactId || useFloatingId;\n\nlet devMessageSet;\nif (process.env.NODE_ENV !== \"production\") {\n devMessageSet = /*#__PURE__*/new Set();\n}\nfunction warn() {\n var _devMessageSet;\n for (var _len = arguments.length, messages = new Array(_len), _key = 0; _key < _len; _key++) {\n messages[_key] = arguments[_key];\n }\n const message = \"Floating UI: \" + messages.join(' ');\n if (!((_devMessageSet = devMessageSet) != null && _devMessageSet.has(message))) {\n var _devMessageSet2;\n (_devMessageSet2 = devMessageSet) == null || _devMessageSet2.add(message);\n console.warn(message);\n }\n}\nfunction error() {\n var _devMessageSet3;\n for (var _len2 = arguments.length, messages = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n messages[_key2] = arguments[_key2];\n }\n const message = \"Floating UI: \" + messages.join(' ');\n if (!((_devMessageSet3 = devMessageSet) != null && _devMessageSet3.has(message))) {\n var _devMessageSet4;\n (_devMessageSet4 = devMessageSet) == null || _devMessageSet4.add(message);\n console.error(message);\n }\n}\n\n/**\n * Renders a pointing arrow triangle.\n * @see https://floating-ui.com/docs/FloatingArrow\n */\nconst FloatingArrow = /*#__PURE__*/React.forwardRef(function FloatingArrow(props, ref) {\n const {\n context: {\n placement,\n elements: {\n floating\n },\n middlewareData: {\n arrow,\n shift\n }\n },\n width = 14,\n height = 7,\n tipRadius = 0,\n strokeWidth = 0,\n staticOffset,\n stroke,\n d,\n style: {\n transform,\n ...restStyle\n } = {},\n ...rest\n } = props;\n if (process.env.NODE_ENV !== \"production\") {\n if (!ref) {\n warn('The `ref` prop is required for `FloatingArrow`.');\n }\n }\n const clipPathId = useId();\n const [isRTL, setIsRTL] = React.useState(false);\n\n // https://github.com/floating-ui/floating-ui/issues/2932\n useModernLayoutEffect(() => {\n if (!floating) return;\n const isRTL = getComputedStyle(floating).direction === 'rtl';\n if (isRTL) {\n setIsRTL(true);\n }\n }, [floating]);\n if (!floating) {\n return null;\n }\n const [side, alignment] = placement.split('-');\n const isVerticalSide = side === 'top' || side === 'bottom';\n let computedStaticOffset = staticOffset;\n if (isVerticalSide && shift != null && shift.x || !isVerticalSide && shift != null && shift.y) {\n computedStaticOffset = null;\n }\n\n // Strokes must be double the border width, this ensures the stroke's width\n // works as you'd expect.\n const computedStrokeWidth = strokeWidth * 2;\n const halfStrokeWidth = computedStrokeWidth / 2;\n const svgX = width / 2 * (tipRadius / -8 + 1);\n const svgY = height / 2 * tipRadius / 4;\n const isCustomShape = !!d;\n const yOffsetProp = computedStaticOffset && alignment === 'end' ? 'bottom' : 'top';\n let xOffsetProp = computedStaticOffset && alignment === 'end' ? 'right' : 'left';\n if (computedStaticOffset && isRTL) {\n xOffsetProp = alignment === 'end' ? 'left' : 'right';\n }\n const arrowX = (arrow == null ? void 0 : arrow.x) != null ? computedStaticOffset || arrow.x : '';\n const arrowY = (arrow == null ? void 0 : arrow.y) != null ? computedStaticOffset || arrow.y : '';\n const dValue = d || 'M0,0' + (\" H\" + width) + (\" L\" + (width - svgX) + \",\" + (height - svgY)) + (\" Q\" + width / 2 + \",\" + height + \" \" + svgX + \",\" + (height - svgY)) + ' Z';\n const rotation = {\n top: isCustomShape ? 'rotate(180deg)' : '',\n left: isCustomShape ? 'rotate(90deg)' : 'rotate(-90deg)',\n bottom: isCustomShape ? '' : 'rotate(180deg)',\n right: isCustomShape ? 'rotate(-90deg)' : 'rotate(90deg)'\n }[side];\n return /*#__PURE__*/jsxs(\"svg\", {\n ...rest,\n \"aria-hidden\": true,\n ref: ref,\n width: isCustomShape ? width : width + computedStrokeWidth,\n height: width,\n viewBox: \"0 0 \" + width + \" \" + (height > width ? height : width),\n style: {\n position: 'absolute',\n pointerEvents: 'none',\n [xOffsetProp]: arrowX,\n [yOffsetProp]: arrowY,\n [side]: isVerticalSide || isCustomShape ? '100%' : \"calc(100% - \" + computedStrokeWidth / 2 + \"px)\",\n transform: [rotation, transform].filter(t => !!t).join(' '),\n ...restStyle\n },\n children: [computedStrokeWidth > 0 && /*#__PURE__*/jsx(\"path\", {\n clipPath: \"url(#\" + clipPathId + \")\",\n fill: \"none\",\n stroke: stroke\n // Account for the stroke on the fill path rendered below.\n ,\n strokeWidth: computedStrokeWidth + (d ? 0 : 1),\n d: dValue\n }), /*#__PURE__*/jsx(\"path\", {\n stroke: computedStrokeWidth && !d ? rest.fill : 'none',\n d: dValue\n }), /*#__PURE__*/jsx(\"clipPath\", {\n id: clipPathId,\n children: /*#__PURE__*/jsx(\"rect\", {\n x: -halfStrokeWidth,\n y: halfStrokeWidth * (isCustomShape ? -1 : 1),\n width: width + computedStrokeWidth,\n height: width\n })\n })]\n });\n});\n\nfunction createEventEmitter() {\n const map = new Map();\n return {\n emit(event, data) {\n var _map$get;\n (_map$get = map.get(event)) == null || _map$get.forEach(listener => listener(data));\n },\n on(event, listener) {\n if (!map.has(event)) {\n map.set(event, new Set());\n }\n map.get(event).add(listener);\n },\n off(event, listener) {\n var _map$get2;\n (_map$get2 = map.get(event)) == null || _map$get2.delete(listener);\n }\n };\n}\n\nconst FloatingNodeContext = /*#__PURE__*/React.createContext(null);\nconst FloatingTreeContext = /*#__PURE__*/React.createContext(null);\n\n/**\n * Returns the parent node id for nested floating elements, if available.\n * Returns `null` for top-level floating elements.\n */\nconst useFloatingParentNodeId = () => {\n var _React$useContext;\n return ((_React$useContext = React.useContext(FloatingNodeContext)) == null ? void 0 : _React$useContext.id) || null;\n};\n\n/**\n * Returns the nearest floating tree context, if available.\n */\nconst useFloatingTree = () => React.useContext(FloatingTreeContext);\n\n/**\n * Registers a node into the `FloatingTree`, returning its id.\n * @see https://floating-ui.com/docs/FloatingTree\n */\nfunction useFloatingNodeId(customParentId) {\n const id = useId();\n const tree = useFloatingTree();\n const reactParentId = useFloatingParentNodeId();\n const parentId = customParentId || reactParentId;\n useModernLayoutEffect(() => {\n if (!id) return;\n const node = {\n id,\n parentId\n };\n tree == null || tree.addNode(node);\n return () => {\n tree == null || tree.removeNode(node);\n };\n }, [tree, id, parentId]);\n return id;\n}\n/**\n * Provides parent node context for nested floating elements.\n * @see https://floating-ui.com/docs/FloatingTree\n */\nfunction FloatingNode(props) {\n const {\n children,\n id\n } = props;\n const parentId = useFloatingParentNodeId();\n return /*#__PURE__*/jsx(FloatingNodeContext.Provider, {\n value: React.useMemo(() => ({\n id,\n parentId\n }), [id, parentId]),\n children: children\n });\n}\n/**\n * Provides context for nested floating elements when they are not children of\n * each other on the DOM.\n * This is not necessary in all cases, except when there must be explicit communication between parent and child floating elements. It is necessary for:\n * - The `bubbles` option in the `useDismiss()` Hook\n * - Nested virtual list navigation\n * - Nested floating elements that each open on hover\n * - Custom communication between parent and child floating elements\n * @see https://floating-ui.com/docs/FloatingTree\n */\nfunction FloatingTree(props) {\n const {\n children\n } = props;\n const nodesRef = React.useRef([]);\n const addNode = React.useCallback(node => {\n nodesRef.current = [...nodesRef.current, node];\n }, []);\n const removeNode = React.useCallback(node => {\n nodesRef.current = nodesRef.current.filter(n => n !== node);\n }, []);\n const [events] = React.useState(() => createEventEmitter());\n return /*#__PURE__*/jsx(FloatingTreeContext.Provider, {\n value: React.useMemo(() => ({\n nodesRef,\n addNode,\n removeNode,\n events\n }), [addNode, removeNode, events]),\n children: children\n });\n}\n\nfunction createAttribute(name) {\n return \"data-floating-ui-\" + name;\n}\n\nfunction clearTimeoutIfSet(timeoutRef) {\n if (timeoutRef.current !== -1) {\n clearTimeout(timeoutRef.current);\n timeoutRef.current = -1;\n }\n}\n\nconst safePolygonIdentifier = /*#__PURE__*/createAttribute('safe-polygon');\nfunction getDelay(value, prop, pointerType) {\n if (pointerType && !isMouseLikePointerType(pointerType)) {\n return 0;\n }\n if (typeof value === 'number') {\n return value;\n }\n if (typeof value === 'function') {\n const result = value();\n if (typeof result === 'number') {\n return result;\n }\n return result == null ? void 0 : result[prop];\n }\n return value == null ? void 0 : value[prop];\n}\nfunction getRestMs(value) {\n if (typeof value === 'function') {\n return value();\n }\n return value;\n}\n/**\n * Opens the floating element while hovering over the reference element, like\n * CSS `:hover`.\n * @see https://floating-ui.com/docs/useHover\n */\nfunction useHover(context, props) {\n if (props === void 0) {\n props = {};\n }\n const {\n open,\n onOpenChange,\n dataRef,\n events,\n elements\n } = context;\n const {\n enabled = true,\n delay = 0,\n handleClose = null,\n mouseOnly = false,\n restMs = 0,\n move = true\n } = props;\n const tree = useFloatingTree();\n const parentId = useFloatingParentNodeId();\n const handleCloseRef = useLatestRef(handleClose);\n const delayRef = useLatestRef(delay);\n const openRef = useLatestRef(open);\n const restMsRef = useLatestRef(restMs);\n const pointerTypeRef = React.useRef();\n const timeoutRef = React.useRef(-1);\n const handlerRef = React.useRef();\n const restTimeoutRef = React.useRef(-1);\n const blockMouseMoveRef = React.useRef(true);\n const performedPointerEventsMutationRef = React.useRef(false);\n const unbindMouseMoveRef = React.useRef(() => {});\n const restTimeoutPendingRef = React.useRef(false);\n const isHoverOpen = useEffectEvent(() => {\n var _dataRef$current$open;\n const type = (_dataRef$current$open = dataRef.current.openEvent) == null ? void 0 : _dataRef$current$open.type;\n return (type == null ? void 0 : type.includes('mouse')) && type !== 'mousedown';\n });\n\n // When closing before opening, clear the delay timeouts to cancel it\n // from showing.\n React.useEffect(() => {\n if (!enabled) return;\n function onOpenChange(_ref) {\n let {\n open\n } = _ref;\n if (!open) {\n clearTimeoutIfSet(timeoutRef);\n clearTimeoutIfSet(restTimeoutRef);\n blockMouseMoveRef.current = true;\n restTimeoutPendingRef.current = false;\n }\n }\n events.on('openchange', onOpenChange);\n return () => {\n events.off('openchange', onOpenChange);\n };\n }, [enabled, events]);\n React.useEffect(() => {\n if (!enabled) return;\n if (!handleCloseRef.current) return;\n if (!open) return;\n function onLeave(event) {\n if (isHoverOpen()) {\n onOpenChange(false, event, 'hover');\n }\n }\n const html = getDocument$1(elements.floating).documentElement;\n html.addEventListener('mouseleave', onLeave);\n return () => {\n html.removeEventListener('mouseleave', onLeave);\n };\n }, [elements.floating, open, onOpenChange, enabled, handleCloseRef, isHoverOpen]);\n const closeWithDelay = React.useCallback(function (event, runElseBranch, reason) {\n if (runElseBranch === void 0) {\n runElseBranch = true;\n }\n if (reason === void 0) {\n reason = 'hover';\n }\n const closeDelay = getDelay(delayRef.current, 'close', pointerTypeRef.current);\n if (closeDelay && !handlerRef.current) {\n clearTimeoutIfSet(timeoutRef);\n timeoutRef.current = window.setTimeout(() => onOpenChange(false, event, reason), closeDelay);\n } else if (runElseBranch) {\n clearTimeoutIfSet(timeoutRef);\n onOpenChange(false, event, reason);\n }\n }, [delayRef, onOpenChange]);\n const cleanupMouseMoveHandler = useEffectEvent(() => {\n unbindMouseMoveRef.current();\n handlerRef.current = undefined;\n });\n const clearPointerEvents = useEffectEvent(() => {\n if (performedPointerEventsMutationRef.current) {\n const body = getDocument$1(elements.floating).body;\n body.style.pointerEvents = '';\n body.removeAttribute(safePolygonIdentifier);\n performedPointerEventsMutationRef.current = false;\n }\n });\n const isClickLikeOpenEvent = useEffectEvent(() => {\n return dataRef.current.openEvent ? ['click', 'mousedown'].includes(dataRef.current.openEvent.type) : false;\n });\n\n // Registering the mouse events on the reference directly to bypass React's\n // delegation system. If the cursor was on a disabled element and then entered\n // the reference (no gap), `mouseenter` doesn't fire in the delegation system.\n React.useEffect(() => {\n if (!enabled) return;\n function onReferenceMouseEnter(event) {\n clearTimeoutIfSet(timeoutRef);\n blockMouseMoveRef.current = false;\n if (mouseOnly && !isMouseLikePointerType(pointerTypeRef.current) || getRestMs(restMsRef.current) > 0 && !getDelay(delayRef.current, 'open')) {\n return;\n }\n const openDelay = getDelay(delayRef.current, 'open', pointerTypeRef.current);\n if (openDelay) {\n timeoutRef.current = window.setTimeout(() => {\n if (!openRef.current) {\n onOpenChange(true, event, 'hover');\n }\n }, openDelay);\n } else if (!open) {\n onOpenChange(true, event, 'hover');\n }\n }\n function onReferenceMouseLeave(event) {\n if (isClickLikeOpenEvent()) {\n clearPointerEvents();\n return;\n }\n unbindMouseMoveRef.current();\n const doc = getDocument$1(elements.floating);\n clearTimeoutIfSet(restTimeoutRef);\n restTimeoutPendingRef.current = false;\n if (handleCloseRef.current && dataRef.current.floatingContext) {\n // Prevent clearing `onScrollMouseLeave` timeout.\n if (!open) {\n clearTimeoutIfSet(timeoutRef);\n }\n handlerRef.current = handleCloseRef.current({\n ...dataRef.current.floatingContext,\n tree,\n x: event.clientX,\n y: event.clientY,\n onClose() {\n clearPointerEvents();\n cleanupMouseMoveHandler();\n if (!isClickLikeOpenEvent()) {\n closeWithDelay(event, true, 'safe-polygon');\n }\n }\n });\n const handler = handlerRef.current;\n doc.addEventListener('mousemove', handler);\n unbindMouseMoveRef.current = () => {\n doc.removeEventListener('mousemove', handler);\n };\n return;\n }\n\n // Allow interactivity without `safePolygon` on touch devices. With a\n // pointer, a short close delay is an alternative, so it should work\n // consistently.\n const shouldClose = pointerTypeRef.current === 'touch' ? !contains$1(elements.floating, event.relatedTarget) : true;\n if (shouldClose) {\n closeWithDelay(event);\n }\n }\n\n // Ensure the floating element closes after scrolling even if the pointer\n // did not move.\n // https://github.com/floating-ui/floating-ui/discussions/1692\n function onScrollMouseLeave(event) {\n if (isClickLikeOpenEvent()) return;\n if (!dataRef.current.floatingContext) return;\n handleCloseRef.current == null || handleCloseRef.current({\n ...dataRef.current.floatingContext,\n tree,\n x: event.clientX,\n y: event.clientY,\n onClose() {\n clearPointerEvents();\n cleanupMouseMoveHandler();\n if (!isClickLikeOpenEvent()) {\n closeWithDelay(event);\n }\n }\n })(event);\n }\n function onFloatingMouseEnter() {\n clearTimeoutIfSet(timeoutRef);\n }\n function onFloatingMouseLeave(event) {\n if (!isClickLikeOpenEvent()) {\n closeWithDelay(event, false);\n }\n }\n if (isElement(elements.domReference)) {\n const reference = elements.domReference;\n const floating = elements.floating;\n if (open) {\n reference.addEventListener('mouseleave', onScrollMouseLeave);\n }\n if (move) {\n reference.addEventListener('mousemove', onReferenceMouseEnter, {\n once: true\n });\n }\n reference.addEventListener('mouseenter', onReferenceMouseEnter);\n reference.addEventListener('mouseleave', onReferenceMouseLeave);\n if (floating) {\n floating.addEventListener('mouseleave', onScrollMouseLeave);\n floating.addEventListener('mouseenter', onFloatingMouseEnter);\n floating.addEventListener('mouseleave', onFloatingMouseLeave);\n }\n return () => {\n if (open) {\n reference.removeEventListener('mouseleave', onScrollMouseLeave);\n }\n if (move) {\n reference.removeEventListener('mousemove', onReferenceMouseEnter);\n }\n reference.removeEventListener('mouseenter', onReferenceMouseEnter);\n reference.removeEventListener('mouseleave', onReferenceMouseLeave);\n if (floating) {\n floating.removeEventListener('mouseleave', onScrollMouseLeave);\n floating.removeEventListener('mouseenter', onFloatingMouseEnter);\n floating.removeEventListener('mouseleave', onFloatingMouseLeave);\n }\n };\n }\n }, [elements, enabled, context, mouseOnly, move, closeWithDelay, cleanupMouseMoveHandler, clearPointerEvents, onOpenChange, open, openRef, tree, delayRef, handleCloseRef, dataRef, isClickLikeOpenEvent, restMsRef]);\n\n // Block pointer-events of every element other than the reference and floating\n // while the floating element is open and has a `handleClose` handler. Also\n // handles nested floating elements.\n // https://github.com/floating-ui/floating-ui/issues/1722\n useModernLayoutEffect(() => {\n var _handleCloseRef$curre;\n if (!enabled) return;\n if (open && (_handleCloseRef$curre = handleCloseRef.current) != null && (_handleCloseRef$curre = _handleCloseRef$curre.__options) != null && _handleCloseRef$curre.blockPointerEvents && isHoverOpen()) {\n performedPointerEventsMutationRef.current = true;\n const floatingEl = elements.floating;\n if (isElement(elements.domReference) && floatingEl) {\n var _tree$nodesRef$curren;\n const body = getDocument$1(elements.floating).body;\n body.setAttribute(safePolygonIdentifier, '');\n const ref = elements.domReference;\n const parentFloating = tree == null || (_tree$nodesRef$curren = tree.nodesRef.current.find(node => node.id === parentId)) == null || (_tree$nodesRef$curren = _tree$nodesRef$curren.context) == null ? void 0 : _tree$nodesRef$curren.elements.floating;\n if (parentFloating) {\n parentFloating.style.pointerEvents = '';\n }\n body.style.pointerEvents = 'none';\n ref.style.pointerEvents = 'auto';\n floatingEl.style.pointerEvents = 'auto';\n return () => {\n body.style.pointerEvents = '';\n ref.style.pointerEvents = '';\n floatingEl.style.pointerEvents = '';\n };\n }\n }\n }, [enabled, open, parentId, elements, tree, handleCloseRef, isHoverOpen]);\n useModernLayoutEffect(() => {\n if (!open) {\n pointerTypeRef.current = undefined;\n restTimeoutPendingRef.current = false;\n cleanupMouseMoveHandler();\n clearPointerEvents();\n }\n }, [open, cleanupMouseMoveHandler, clearPointerEvents]);\n React.useEffect(() => {\n return () => {\n cleanupMouseMoveHandler();\n clearTimeoutIfSet(timeoutRef);\n clearTimeoutIfSet(restTimeoutRef);\n clearPointerEvents();\n };\n }, [enabled, elements.domReference, cleanupMouseMoveHandler, clearPointerEvents]);\n const reference = React.useMemo(() => {\n function setPointerRef(event) {\n pointerTypeRef.current = event.pointerType;\n }\n return {\n onPointerDown: setPointerRef,\n onPointerEnter: setPointerRef,\n onMouseMove(event) {\n const {\n nativeEvent\n } = event;\n function handleMouseMove() {\n if (!blockMouseMoveRef.current && !openRef.current) {\n onOpenChange(true, nativeEvent, 'hover');\n }\n }\n if (mouseOnly && !isMouseLikePointerType(pointerTypeRef.current)) {\n return;\n }\n if (open || getRestMs(restMsRef.current) === 0) {\n return;\n }\n\n // Ignore insignificant movements to account for tremors.\n if (restTimeoutPendingRef.current && event.movementX ** 2 + event.movementY ** 2 < 2) {\n return;\n }\n clearTimeoutIfSet(restTimeoutRef);\n if (pointerTypeRef.current === 'touch') {\n handleMouseMove();\n } else {\n restTimeoutPendingRef.current = true;\n restTimeoutRef.current = window.setTimeout(handleMouseMove, getRestMs(restMsRef.current));\n }\n }\n };\n }, [mouseOnly, onOpenChange, open, openRef, restMsRef]);\n return React.useMemo(() => enabled ? {\n reference\n } : {}, [enabled, reference]);\n}\n\nconst NOOP = () => {};\nconst FloatingDelayGroupContext = /*#__PURE__*/React.createContext({\n delay: 0,\n initialDelay: 0,\n timeoutMs: 0,\n currentId: null,\n setCurrentId: NOOP,\n setState: NOOP,\n isInstantPhase: false\n});\n\n/**\n * @deprecated\n * Use the return value of `useDelayGroup()` instead.\n */\nconst useDelayGroupContext = () => React.useContext(FloatingDelayGroupContext);\n/**\n * Provides context for a group of floating elements that should share a\n * `delay`.\n * @see https://floating-ui.com/docs/FloatingDelayGroup\n */\nfunction FloatingDelayGroup(props) {\n const {\n children,\n delay,\n timeoutMs = 0\n } = props;\n const [state, setState] = React.useReducer((prev, next) => ({\n ...prev,\n ...next\n }), {\n delay,\n timeoutMs,\n initialDelay: delay,\n currentId: null,\n isInstantPhase: false\n });\n const initialCurrentIdRef = React.useRef(null);\n const setCurrentId = React.useCallback(currentId => {\n setState({\n currentId\n });\n }, []);\n useModernLayoutEffect(() => {\n if (state.currentId) {\n if (initialCurrentIdRef.current === null) {\n initialCurrentIdRef.current = state.currentId;\n } else if (!state.isInstantPhase) {\n setState({\n isInstantPhase: true\n });\n }\n } else {\n if (state.isInstantPhase) {\n setState({\n isInstantPhase: false\n });\n }\n initialCurrentIdRef.current = null;\n }\n }, [state.currentId, state.isInstantPhase]);\n return /*#__PURE__*/jsx(FloatingDelayGroupContext.Provider, {\n value: React.useMemo(() => ({\n ...state,\n setState,\n setCurrentId\n }), [state, setCurrentId]),\n children: children\n });\n}\n/**\n * Enables grouping when called inside a component that's a child of a\n * `FloatingDelayGroup`.\n * @see https://floating-ui.com/docs/FloatingDelayGroup\n */\nfunction useDelayGroup(context, options) {\n if (options === void 0) {\n options = {};\n }\n const {\n open,\n onOpenChange,\n floatingId\n } = context;\n const {\n id: optionId,\n enabled = true\n } = options;\n const id = optionId != null ? optionId : floatingId;\n const groupContext = useDelayGroupContext();\n const {\n currentId,\n setCurrentId,\n initialDelay,\n setState,\n timeoutMs\n } = groupContext;\n useModernLayoutEffect(() => {\n if (!enabled) return;\n if (!currentId) return;\n setState({\n delay: {\n open: 1,\n close: getDelay(initialDelay, 'close')\n }\n });\n if (currentId !== id) {\n onOpenChange(false);\n }\n }, [enabled, id, onOpenChange, setState, currentId, initialDelay]);\n useModernLayoutEffect(() => {\n function unset() {\n onOpenChange(false);\n setState({\n delay: initialDelay,\n currentId: null\n });\n }\n if (!enabled) return;\n if (!currentId) return;\n if (!open && currentId === id) {\n if (timeoutMs) {\n const timeout = window.setTimeout(unset, timeoutMs);\n return () => {\n clearTimeout(timeout);\n };\n }\n unset();\n }\n }, [enabled, open, setState, currentId, id, onOpenChange, initialDelay, timeoutMs]);\n useModernLayoutEffect(() => {\n if (!enabled) return;\n if (setCurrentId === NOOP || !open) return;\n setCurrentId(id);\n }, [enabled, open, setCurrentId, id]);\n return groupContext;\n}\n\nconst NextFloatingDelayGroupContext = /*#__PURE__*/React.createContext({\n hasProvider: false,\n timeoutMs: 0,\n delayRef: {\n current: 0\n },\n initialDelayRef: {\n current: 0\n },\n timeoutIdRef: {\n current: -1\n },\n currentIdRef: {\n current: null\n },\n currentContextRef: {\n current: null\n }\n});\n/**\n * Experimental next version of `FloatingDelayGroup` to become the default\n * in the future. This component is not yet stable.\n * Provides context for a group of floating elements that should share a\n * `delay`. Unlike `FloatingDelayGroup`, `useNextDelayGroup` with this\n * component does not cause a re-render of unrelated consumers of the\n * context when the delay changes.\n * @see https://floating-ui.com/docs/FloatingDelayGroup\n */\nfunction NextFloatingDelayGroup(props) {\n const {\n children,\n delay,\n timeoutMs = 0\n } = props;\n const delayRef = React.useRef(delay);\n const initialDelayRef = React.useRef(delay);\n const currentIdRef = React.useRef(null);\n const currentContextRef = React.useRef(null);\n const timeoutIdRef = React.useRef(-1);\n return /*#__PURE__*/jsx(NextFloatingDelayGroupContext.Provider, {\n value: React.useMemo(() => ({\n hasProvider: true,\n delayRef,\n initialDelayRef,\n currentIdRef,\n timeoutMs,\n currentContextRef,\n timeoutIdRef\n }), [timeoutMs]),\n children: children\n });\n}\n/**\n * Enables grouping when called inside a component that's a child of a\n * `NextFloatingDelayGroup`.\n * @see https://floating-ui.com/docs/FloatingDelayGroup\n */\nfunction useNextDelayGroup(context, options) {\n if (options === void 0) {\n options = {};\n }\n const {\n open,\n onOpenChange,\n floatingId\n } = context;\n const {\n enabled = true\n } = options;\n const groupContext = React.useContext(NextFloatingDelayGroupContext);\n const {\n currentIdRef,\n delayRef,\n timeoutMs,\n initialDelayRef,\n currentContextRef,\n hasProvider,\n timeoutIdRef\n } = groupContext;\n const [isInstantPhase, setIsInstantPhase] = React.useState(false);\n useModernLayoutEffect(() => {\n function unset() {\n var _currentContextRef$cu;\n setIsInstantPhase(false);\n (_currentContextRef$cu = currentContextRef.current) == null || _currentContextRef$cu.setIsInstantPhase(false);\n currentIdRef.current = null;\n currentContextRef.current = null;\n delayRef.current = initialDelayRef.current;\n }\n if (!enabled) return;\n if (!currentIdRef.current) return;\n if (!open && currentIdRef.current === floatingId) {\n setIsInstantPhase(false);\n if (timeoutMs) {\n timeoutIdRef.current = window.setTimeout(unset, timeoutMs);\n return () => {\n clearTimeout(timeoutIdRef.current);\n };\n }\n unset();\n }\n }, [enabled, open, floatingId, currentIdRef, delayRef, timeoutMs, initialDelayRef, currentContextRef, timeoutIdRef]);\n useModernLayoutEffect(() => {\n if (!enabled) return;\n if (!open) return;\n const prevContext = currentContextRef.current;\n const prevId = currentIdRef.current;\n currentContextRef.current = {\n onOpenChange,\n setIsInstantPhase\n };\n currentIdRef.current = floatingId;\n delayRef.current = {\n open: 0,\n close: getDelay(initialDelayRef.current, 'close')\n };\n if (prevId !== null && prevId !== floatingId) {\n clearTimeoutIfSet(timeoutIdRef);\n setIsInstantPhase(true);\n prevContext == null || prevContext.setIsInstantPhase(true);\n prevContext == null || prevContext.onOpenChange(false);\n } else {\n setIsInstantPhase(false);\n prevContext == null || prevContext.setIsInstantPhase(false);\n }\n }, [enabled, open, floatingId, onOpenChange, currentIdRef, delayRef, timeoutMs, initialDelayRef, currentContextRef, timeoutIdRef]);\n useModernLayoutEffect(() => {\n return () => {\n currentContextRef.current = null;\n };\n }, [currentContextRef]);\n return React.useMemo(() => ({\n hasProvider,\n delayRef,\n isInstantPhase\n }), [hasProvider, delayRef, isInstantPhase]);\n}\n\nlet rafId = 0;\nfunction enqueueFocus(el, options) {\n if (options === void 0) {\n options = {};\n }\n const {\n preventScroll = false,\n cancelPrevious = true,\n sync = false\n } = options;\n cancelPrevious && cancelAnimationFrame(rafId);\n const exec = () => el == null ? void 0 : el.focus({\n preventScroll\n });\n if (sync) {\n exec();\n } else {\n rafId = requestAnimationFrame(exec);\n }\n}\n\nfunction contains(parent, child) {\n if (!parent || !child) {\n return false;\n }\n const rootNode = child.getRootNode == null ? void 0 : child.getRootNode();\n\n // First, attempt with faster native method\n if (parent.contains(child)) {\n return true;\n }\n\n // then fallback to custom implementation with Shadow DOM support\n if (rootNode && isShadowRoot(rootNode)) {\n let next = child;\n while (next) {\n if (parent === next) {\n return true;\n }\n // @ts-ignore\n next = next.parentNode || next.host;\n }\n }\n\n // Give up, the result is false\n return false;\n}\nfunction getTarget(event) {\n if ('composedPath' in event) {\n return event.composedPath()[0];\n }\n\n // TS thinks `event` is of type never as it assumes all browsers support\n // `composedPath()`, but browsers without shadow DOM don't.\n return event.target;\n}\nfunction getDocument(node) {\n return (node == null ? void 0 : node.ownerDocument) || document;\n}\n\n// Modified to add conditional `aria-hidden` support:\n// https://github.com/theKashey/aria-hidden/blob/9220c8f4a4fd35f63bee5510a9f41a37264382d4/src/index.ts\nconst counters = {\n inert: /*#__PURE__*/new WeakMap(),\n 'aria-hidden': /*#__PURE__*/new WeakMap(),\n none: /*#__PURE__*/new WeakMap()\n};\nfunction getCounterMap(control) {\n if (control === 'inert') return counters.inert;\n if (control === 'aria-hidden') return counters['aria-hidden'];\n return counters.none;\n}\nlet uncontrolledElementsSet = /*#__PURE__*/new WeakSet();\nlet markerMap = {};\nlet lockCount$1 = 0;\nconst supportsInert = () => typeof HTMLElement !== 'undefined' && 'inert' in HTMLElement.prototype;\nconst unwrapHost = node => node && (node.host || unwrapHost(node.parentNode));\nconst correctElements = (parent, targets) => targets.map(target => {\n if (parent.contains(target)) {\n return target;\n }\n const correctedTarget = unwrapHost(target);\n if (parent.contains(correctedTarget)) {\n return correctedTarget;\n }\n return null;\n}).filter(x => x != null);\nfunction applyAttributeToOthers(uncorrectedAvoidElements, body, ariaHidden, inert) {\n const markerName = 'data-floating-ui-inert';\n const controlAttribute = inert ? 'inert' : ariaHidden ? 'aria-hidden' : null;\n const avoidElements = correctElements(body, uncorrectedAvoidElements);\n const elementsToKeep = new Set();\n const elementsToStop = new Set(avoidElements);\n const hiddenElements = [];\n if (!markerMap[markerName]) {\n markerMap[markerName] = new WeakMap();\n }\n const markerCounter = markerMap[markerName];\n avoidElements.forEach(keep);\n deep(body);\n elementsToKeep.clear();\n function keep(el) {\n if (!el || elementsToKeep.has(el)) {\n return;\n }\n elementsToKeep.add(el);\n el.parentNode && keep(el.parentNode);\n }\n function deep(parent) {\n if (!parent || elementsToStop.has(parent)) {\n return;\n }\n [].forEach.call(parent.children, node => {\n if (getNodeName(node) === 'script') return;\n if (elementsToKeep.has(node)) {\n deep(node);\n } else {\n const attr = controlAttribute ? node.getAttribute(controlAttribute) : null;\n const alreadyHidden = attr !== null && attr !== 'false';\n const counterMap = getCounterMap(controlAttribute);\n const counterValue = (counterMap.get(node) || 0) + 1;\n const markerValue = (markerCounter.get(node) || 0) + 1;\n counterMap.set(node, counterValue);\n markerCounter.set(node, markerValue);\n hiddenElements.push(node);\n if (counterValue === 1 && alreadyHidden) {\n uncontrolledElementsSet.add(node);\n }\n if (markerValue === 1) {\n node.setAttribute(markerName, '');\n }\n if (!alreadyHidden && controlAttribute) {\n node.setAttribute(controlAttribute, controlAttribute === 'inert' ? '' : 'true');\n }\n }\n });\n }\n lockCount$1++;\n return () => {\n hiddenElements.forEach(element => {\n const counterMap = getCounterMap(controlAttribute);\n const currentCounterValue = counterMap.get(element) || 0;\n const counterValue = currentCounterValue - 1;\n const markerValue = (markerCounter.get(element) || 0) - 1;\n counterMap.set(element, counterValue);\n markerCounter.set(element, markerValue);\n if (!counterValue) {\n if (!uncontrolledElementsSet.has(element) && controlAttribute) {\n element.removeAttribute(controlAttribute);\n }\n uncontrolledElementsSet.delete(element);\n }\n if (!markerValue) {\n element.removeAttribute(markerName);\n }\n });\n lockCount$1--;\n if (!lockCount$1) {\n counters.inert = new WeakMap();\n counters['aria-hidden'] = new WeakMap();\n counters.none = new WeakMap();\n uncontrolledElementsSet = new WeakSet();\n markerMap = {};\n }\n };\n}\nfunction markOthers(avoidElements, ariaHidden, inert) {\n if (ariaHidden === void 0) {\n ariaHidden = false;\n }\n if (inert === void 0) {\n inert = false;\n }\n const body = getDocument(avoidElements[0]).body;\n return applyAttributeToOthers(avoidElements.concat(Array.from(body.querySelectorAll('[aria-live],[role=\"status\"],output'))), body, ariaHidden, inert);\n}\n\nconst HIDDEN_STYLES = {\n border: 0,\n clip: 'rect(0 0 0 0)',\n height: '1px',\n margin: '-1px',\n overflow: 'hidden',\n padding: 0,\n position: 'fixed',\n whiteSpace: 'nowrap',\n width: '1px',\n top: 0,\n left: 0\n};\nconst FocusGuard = /*#__PURE__*/React.forwardRef(function FocusGuard(props, ref) {\n const [role, setRole] = React.useState();\n useModernLayoutEffect(() => {\n if (isSafari()) {\n // Unlike other screen readers such as NVDA and JAWS, the virtual cursor\n // on VoiceOver does trigger the onFocus event, so we can use the focus\n // trap element. On Safari, only buttons trigger the onFocus event.\n // NB: \"group\" role in the Sandbox no longer appears to work, must be a\n // button role.\n setRole('button');\n }\n }, []);\n const restProps = {\n ref,\n tabIndex: 0,\n // Role is only for VoiceOver\n role,\n 'aria-hidden': role ? undefined : true,\n [createAttribute('focus-guard')]: '',\n style: HIDDEN_STYLES\n };\n return /*#__PURE__*/jsx(\"span\", {\n ...props,\n ...restProps\n });\n});\n\nconst HIDDEN_OWNER_STYLES = {\n clipPath: 'inset(50%)',\n position: 'fixed',\n top: 0,\n left: 0\n};\nconst PortalContext = /*#__PURE__*/React.createContext(null);\nconst attr = /*#__PURE__*/createAttribute('portal');\n/**\n * @see https://floating-ui.com/docs/FloatingPortal#usefloatingportalnode\n */\nfunction useFloatingPortalNode(props) {\n if (props === void 0) {\n props = {};\n }\n const {\n id,\n root\n } = props;\n const uniqueId = useId();\n const portalContext = usePortalContext();\n const [portalNode, setPortalNode] = React.useState(null);\n const portalNodeRef = React.useRef(null);\n useModernLayoutEffect(() => {\n return () => {\n portalNode == null || portalNode.remove();\n // Allow the subsequent layout effects to create a new node on updates.\n // The portal node will still be cleaned up on unmount.\n // https://github.com/floating-ui/floating-ui/issues/2454\n queueMicrotask(() => {\n portalNodeRef.current = null;\n });\n };\n }, [portalNode]);\n useModernLayoutEffect(() => {\n // Wait for the uniqueId to be generated before creating the portal node in\n // React <18 (using `useFloatingId` instead of the native `useId`).\n // https://github.com/floating-ui/floating-ui/issues/2778\n if (!uniqueId) return;\n if (portalNodeRef.current) return;\n const existingIdRoot = id ? document.getElementById(id) : null;\n if (!existingIdRoot) return;\n const subRoot = document.createElement('div');\n subRoot.id = uniqueId;\n subRoot.setAttribute(attr, '');\n existingIdRoot.appendChild(subRoot);\n portalNodeRef.current = subRoot;\n setPortalNode(subRoot);\n }, [id, uniqueId]);\n useModernLayoutEffect(() => {\n // Wait for the root to exist before creating the portal node. The root must\n // be stored in state, not a ref, for this to work reactively.\n if (root === null) return;\n if (!uniqueId) return;\n if (portalNodeRef.current) return;\n let container = root || (portalContext == null ? void 0 : portalContext.portalNode);\n if (container && !isNode(container)) container = container.current;\n container = container || document.body;\n let idWrapper = null;\n if (id) {\n idWrapper = document.createElement('div');\n idWrapper.id = id;\n container.appendChild(idWrapper);\n }\n const subRoot = document.createElement('div');\n subRoot.id = uniqueId;\n subRoot.setAttribute(attr, '');\n container = idWrapper || container;\n container.appendChild(subRoot);\n portalNodeRef.current = subRoot;\n setPortalNode(subRoot);\n }, [id, root, uniqueId, portalContext]);\n return portalNode;\n}\n/**\n * Portals the floating element into a given container element — by default,\n * outside of the app root and into the body.\n * This is necessary to ensure the floating element can appear outside any\n * potential parent containers that cause clipping (such as `overflow: hidden`),\n * while retaining its location in the React tree.\n * @see https://floating-ui.com/docs/FloatingPortal\n */\nfunction FloatingPortal(props) {\n const {\n children,\n id,\n root,\n preserveTabOrder = true\n } = props;\n const portalNode = useFloatingPortalNode({\n id,\n root\n });\n const [focusManagerState, setFocusManagerState] = React.useState(null);\n const beforeOutsideRef = React.useRef(null);\n const afterOutsideRef = React.useRef(null);\n const beforeInsideRef = React.useRef(null);\n const afterInsideRef = React.useRef(null);\n const modal = focusManagerState == null ? void 0 : focusManagerState.modal;\n const open = focusManagerState == null ? void 0 : focusManagerState.open;\n const shouldRenderGuards =\n // The FocusManager and therefore floating element are currently open/\n // rendered.\n !!focusManagerState &&\n // Guards are only for non-modal focus management.\n !focusManagerState.modal &&\n // Don't render if unmount is transitioning.\n focusManagerState.open && preserveTabOrder && !!(root || portalNode);\n\n // https://codesandbox.io/s/tabbable-portal-f4tng?file=/src/TabbablePortal.tsx\n React.useEffect(() => {\n if (!portalNode || !preserveTabOrder || modal) {\n return;\n }\n\n // Make sure elements inside the portal element are tabbable only when the\n // portal has already been focused, either by tabbing into a focus trap\n // element outside or using the mouse.\n function onFocus(event) {\n if (portalNode && isOutsideEvent(event)) {\n const focusing = event.type === 'focusin';\n const manageFocus = focusing ? enableFocusInside : disableFocusInside;\n manageFocus(portalNode);\n }\n }\n // Listen to the event on the capture phase so they run before the focus\n // trap elements onFocus prop is called.\n portalNode.addEventListener('focusin', onFocus, true);\n portalNode.addEventListener('focusout', onFocus, true);\n return () => {\n portalNode.removeEventListener('focusin', onFocus, true);\n portalNode.removeEventListener('focusout', onFocus, true);\n };\n }, [portalNode, preserveTabOrder, modal]);\n React.useEffect(() => {\n if (!portalNode) return;\n if (open) return;\n enableFocusInside(portalNode);\n }, [open, portalNode]);\n return /*#__PURE__*/jsxs(PortalContext.Provider, {\n value: React.useMemo(() => ({\n preserveTabOrder,\n beforeOutsideRef,\n afterOutsideRef,\n beforeInsideRef,\n afterInsideRef,\n portalNode,\n setFocusManagerState\n }), [preserveTabOrder, portalNode]),\n children: [shouldRenderGuards && portalNode && /*#__PURE__*/jsx(FocusGuard, {\n \"data-type\": \"outside\",\n ref: beforeOutsideRef,\n onFocus: event => {\n if (isOutsideEvent(event, portalNode)) {\n var _beforeInsideRef$curr;\n (_beforeInsideRef$curr = beforeInsideRef.current) == null || _beforeInsideRef$curr.focus();\n } else {\n const domReference = focusManagerState ? focusManagerState.domReference : null;\n const prevTabbable = getPreviousTabbable(domReference);\n prevTabbable == null || prevTabbable.focus();\n }\n }\n }), shouldRenderGuards && portalNode && /*#__PURE__*/jsx(\"span\", {\n \"aria-owns\": portalNode.id,\n style: HIDDEN_OWNER_STYLES\n }), portalNode && /*#__PURE__*/ReactDOM.createPortal(children, portalNode), shouldRenderGuards && portalNode && /*#__PURE__*/jsx(FocusGuard, {\n \"data-type\": \"outside\",\n ref: afterOutsideRef,\n onFocus: event => {\n if (isOutsideEvent(event, portalNode)) {\n var _afterInsideRef$curre;\n (_afterInsideRef$curre = afterInsideRef.current) == null || _afterInsideRef$curre.focus();\n } else {\n const domReference = focusManagerState ? focusManagerState.domReference : null;\n const nextTabbable = getNextTabbable(domReference);\n nextTabbable == null || nextTabbable.focus();\n (focusManagerState == null ? void 0 : focusManagerState.closeOnFocusOut) && (focusManagerState == null ? void 0 : focusManagerState.onOpenChange(false, event.nativeEvent, 'focus-out'));\n }\n }\n })]\n });\n}\nconst usePortalContext = () => React.useContext(PortalContext);\n\nfunction useLiteMergeRefs(refs) {\n return React.useMemo(() => {\n return value => {\n refs.forEach(ref => {\n if (ref) {\n ref.current = value;\n }\n });\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, refs);\n}\n\nconst LIST_LIMIT = 20;\nlet previouslyFocusedElements = [];\nfunction clearDisconnectedPreviouslyFocusedElements() {\n previouslyFocusedElements = previouslyFocusedElements.filter(elementRef => {\n var _elementRef$deref;\n return (_elementRef$deref = elementRef.deref()) == null ? void 0 : _elementRef$deref.isConnected;\n });\n}\nfunction addPreviouslyFocusedElement(element) {\n clearDisconnectedPreviouslyFocusedElements();\n if (element && getNodeName(element) !== 'body') {\n previouslyFocusedElements.push(new WeakRef(element));\n if (previouslyFocusedElements.length > LIST_LIMIT) {\n previouslyFocusedElements = previouslyFocusedElements.slice(-20);\n }\n }\n}\nfunction getPreviouslyFocusedElement() {\n clearDisconnectedPreviouslyFocusedElements();\n const elementRef = previouslyFocusedElements[previouslyFocusedElements.length - 1];\n return elementRef == null ? void 0 : elementRef.deref();\n}\nfunction getFirstTabbableElement(container) {\n const tabbableOptions = getTabbableOptions();\n if (isTabbable(container, tabbableOptions)) {\n return container;\n }\n return tabbable(container, tabbableOptions)[0] || container;\n}\nfunction handleTabIndex(floatingFocusElement, orderRef) {\n var _floatingFocusElement;\n if (!orderRef.current.includes('floating') && !((_floatingFocusElement = floatingFocusElement.getAttribute('role')) != null && _floatingFocusElement.includes('dialog'))) {\n return;\n }\n const options = getTabbableOptions();\n const focusableElements = focusable(floatingFocusElement, options);\n const tabbableContent = focusableElements.filter(element => {\n const dataTabIndex = element.getAttribute('data-tabindex') || '';\n return isTabbable(element, options) || element.hasAttribute('data-tabindex') && !dataTabIndex.startsWith('-');\n });\n const tabIndex = floatingFocusElement.getAttribute('tabindex');\n if (orderRef.current.includes('floating') || tabbableContent.length === 0) {\n if (tabIndex !== '0') {\n floatingFocusElement.setAttribute('tabindex', '0');\n }\n } else if (tabIndex !== '-1' || floatingFocusElement.hasAttribute('data-tabindex') && floatingFocusElement.getAttribute('data-tabindex') !== '-1') {\n floatingFocusElement.setAttribute('tabindex', '-1');\n floatingFocusElement.setAttribute('data-tabindex', '-1');\n }\n}\nconst VisuallyHiddenDismiss = /*#__PURE__*/React.forwardRef(function VisuallyHiddenDismiss(props, ref) {\n return /*#__PURE__*/jsx(\"button\", {\n ...props,\n type: \"button\",\n ref: ref,\n tabIndex: -1,\n style: HIDDEN_STYLES\n });\n});\n/**\n * Provides focus management for the floating element.\n * @see https://floating-ui.com/docs/FloatingFocusManager\n */\nfunction FloatingFocusManager(props) {\n const {\n context,\n children,\n disabled = false,\n order = ['content'],\n guards: _guards = true,\n initialFocus = 0,\n returnFocus = true,\n restoreFocus = false,\n modal = true,\n visuallyHiddenDismiss = false,\n closeOnFocusOut = true,\n outsideElementsInert = false,\n getInsideElements: _getInsideElements = () => []\n } = props;\n const {\n open,\n onOpenChange,\n events,\n dataRef,\n elements: {\n domReference,\n floating\n }\n } = context;\n const getNodeId = useEffectEvent(() => {\n var _dataRef$current$floa;\n return (_dataRef$current$floa = dataRef.current.floatingContext) == null ? void 0 : _dataRef$current$floa.nodeId;\n });\n const getInsideElements = useEffectEvent(_getInsideElements);\n const ignoreInitialFocus = typeof initialFocus === 'number' && initialFocus < 0;\n // If the reference is a combobox and is typeable (e.g. input/textarea),\n // there are different focus semantics. The guards should not be rendered, but\n // aria-hidden should be applied to all nodes still. Further, the visually\n // hidden dismiss button should only appear at the end of the list, not the\n // start.\n const isUntrappedTypeableCombobox = isTypeableCombobox(domReference) && ignoreInitialFocus;\n\n // Force the guards to be rendered if the `inert` attribute is not supported.\n const inertSupported = supportsInert();\n const guards = inertSupported ? _guards : true;\n const useInert = !guards || inertSupported && outsideElementsInert;\n const orderRef = useLatestRef(order);\n const initialFocusRef = useLatestRef(initialFocus);\n const returnFocusRef = useLatestRef(returnFocus);\n const tree = useFloatingTree();\n const portalContext = usePortalContext();\n const startDismissButtonRef = React.useRef(null);\n const endDismissButtonRef = React.useRef(null);\n const preventReturnFocusRef = React.useRef(false);\n const isPointerDownRef = React.useRef(false);\n const tabbableIndexRef = React.useRef(-1);\n const blurTimeoutRef = React.useRef(-1);\n const isInsidePortal = portalContext != null;\n const floatingFocusElement = getFloatingFocusElement(floating);\n const getTabbableContent = useEffectEvent(function (container) {\n if (container === void 0) {\n container = floatingFocusElement;\n }\n return container ? tabbable(container, getTabbableOptions()) : [];\n });\n const getTabbableElements = useEffectEvent(container => {\n const content = getTabbableContent(container);\n return orderRef.current.map(type => {\n if (domReference && type === 'reference') {\n return domReference;\n }\n if (floatingFocusElement && type === 'floating') {\n return floatingFocusElement;\n }\n return content;\n }).filter(Boolean).flat();\n });\n React.useEffect(() => {\n if (disabled) return;\n if (!modal) return;\n function onKeyDown(event) {\n if (event.key === 'Tab') {\n // The focus guards have nothing to focus, so we need to stop the event.\n if (contains$1(floatingFocusElement, activeElement(getDocument$1(floatingFocusElement))) && getTabbableContent().length === 0 && !isUntrappedTypeableCombobox) {\n stopEvent(event);\n }\n const els = getTabbableElements();\n const target = getTarget$1(event);\n if (orderRef.current[0] === 'reference' && target === domReference) {\n stopEvent(event);\n if (event.shiftKey) {\n enqueueFocus(els[els.length - 1]);\n } else {\n enqueueFocus(els[1]);\n }\n }\n if (orderRef.current[1] === 'floating' && target === floatingFocusElement && event.shiftKey) {\n stopEvent(event);\n enqueueFocus(els[0]);\n }\n }\n }\n const doc = getDocument$1(floatingFocusElement);\n doc.addEventListener('keydown', onKeyDown);\n return () => {\n doc.removeEventListener('keydown', onKeyDown);\n };\n }, [disabled, domReference, floatingFocusElement, modal, orderRef, isUntrappedTypeableCombobox, getTabbableContent, getTabbableElements]);\n React.useEffect(() => {\n if (disabled) return;\n if (!floating) return;\n function handleFocusIn(event) {\n const target = getTarget$1(event);\n const tabbableContent = getTabbableContent();\n const tabbableIndex = tabbableContent.indexOf(target);\n if (tabbableIndex !== -1) {\n tabbableIndexRef.current = tabbableIndex;\n }\n }\n floating.addEventListener('focusin', handleFocusIn);\n return () => {\n floating.removeEventListener('focusin', handleFocusIn);\n };\n }, [disabled, floating, getTabbableContent]);\n React.useEffect(() => {\n if (disabled) return;\n if (!closeOnFocusOut) return;\n\n // In Safari, buttons lose focus when pressing them.\n function handlePointerDown() {\n isPointerDownRef.current = true;\n setTimeout(() => {\n isPointerDownRef.current = false;\n });\n }\n function handleFocusOutside(event) {\n const relatedTarget = event.relatedTarget;\n const currentTarget = event.currentTarget;\n const target = getTarget$1(event);\n queueMicrotask(() => {\n const nodeId = getNodeId();\n const movedToUnrelatedNode = !(contains$1(domReference, relatedTarget) || contains$1(floating, relatedTarget) || contains$1(relatedTarget, floating) || contains$1(portalContext == null ? void 0 : portalContext.portalNode, relatedTarget) || relatedTarget != null && relatedTarget.hasAttribute(createAttribute('focus-guard')) || tree && (getNodeChildren$1(tree.nodesRef.current, nodeId).find(node => {\n var _node$context, _node$context2;\n return contains$1((_node$context = node.context) == null ? void 0 : _node$context.elements.floating, relatedTarget) || contains$1((_node$context2 = node.context) == null ? void 0 : _node$context2.elements.domReference, relatedTarget);\n }) || getNodeAncestors(tree.nodesRef.current, nodeId).find(node => {\n var _node$context3, _node$context4, _node$context5;\n return [(_node$context3 = node.context) == null ? void 0 : _node$context3.elements.floating, getFloatingFocusElement((_node$context4 = node.context) == null ? void 0 : _node$context4.elements.floating)].includes(relatedTarget) || ((_node$context5 = node.context) == null ? void 0 : _node$context5.elements.domReference) === relatedTarget;\n })));\n if (currentTarget === domReference && floatingFocusElement) {\n handleTabIndex(floatingFocusElement, orderRef);\n }\n\n // Restore focus to the previous tabbable element index to prevent\n // focus from being lost outside the floating tree.\n if (restoreFocus && currentTarget !== domReference && !(target != null && target.isConnected) && activeElement(getDocument$1(floatingFocusElement)) === getDocument$1(floatingFocusElement).body) {\n // Let `FloatingPortal` effect knows that focus is still inside the\n // floating tree.\n if (isHTMLElement(floatingFocusElement)) {\n floatingFocusElement.focus();\n }\n const prevTabbableIndex = tabbableIndexRef.current;\n const tabbableContent = getTabbableContent();\n const nodeToFocus = tabbableContent[prevTabbableIndex] || tabbableContent[tabbableContent.length - 1] || floatingFocusElement;\n if (isHTMLElement(nodeToFocus)) {\n nodeToFocus.focus();\n }\n }\n\n // https://github.com/floating-ui/floating-ui/issues/3060\n if (dataRef.current.insideReactTree) {\n dataRef.current.insideReactTree = false;\n return;\n }\n\n // Focus did not move inside the floating tree, and there are no tabbable\n // portal guards to handle closing.\n if ((isUntrappedTypeableCombobox ? true : !modal) && relatedTarget && movedToUnrelatedNode && !isPointerDownRef.current &&\n // Fix React 18 Strict Mode returnFocus due to double rendering.\n relatedTarget !== getPreviouslyFocusedElement()) {\n preventReturnFocusRef.current = true;\n onOpenChange(false, event, 'focus-out');\n }\n });\n }\n const shouldHandleBlurCapture = Boolean(!tree && portalContext);\n function markInsideReactTree() {\n clearTimeoutIfSet(blurTimeoutRef);\n dataRef.current.insideReactTree = true;\n blurTimeoutRef.current = window.setTimeout(() => {\n dataRef.current.insideReactTree = false;\n });\n }\n if (floating && isHTMLElement(domReference)) {\n domReference.addEventListener('focusout', handleFocusOutside);\n domReference.addEventListener('pointerdown', handlePointerDown);\n floating.addEventListener('focusout', handleFocusOutside);\n if (shouldHandleBlurCapture) {\n floating.addEventListener('focusout', markInsideReactTree, true);\n }\n return () => {\n domReference.removeEventListener('focusout', handleFocusOutside);\n domReference.removeEventListener('pointerdown', handlePointerDown);\n floating.removeEventListener('focusout', handleFocusOutside);\n if (shouldHandleBlurCapture) {\n floating.removeEventListener('focusout', markInsideReactTree, true);\n }\n };\n }\n }, [disabled, domReference, floating, floatingFocusElement, modal, tree, portalContext, onOpenChange, closeOnFocusOut, restoreFocus, getTabbableContent, isUntrappedTypeableCombobox, getNodeId, orderRef, dataRef]);\n const beforeGuardRef = React.useRef(null);\n const afterGuardRef = React.useRef(null);\n const mergedBeforeGuardRef = useLiteMergeRefs([beforeGuardRef, portalContext == null ? void 0 : portalContext.beforeInsideRef]);\n const mergedAfterGuardRef = useLiteMergeRefs([afterGuardRef, portalContext == null ? void 0 : portalContext.afterInsideRef]);\n React.useEffect(() => {\n var _portalContext$portal, _ancestors$find;\n if (disabled) return;\n if (!floating) return;\n\n // Don't hide portals nested within the parent portal.\n const portalNodes = Array.from((portalContext == null || (_portalContext$portal = portalContext.portalNode) == null ? void 0 : _portalContext$portal.querySelectorAll(\"[\" + createAttribute('portal') + \"]\")) || []);\n const ancestors = tree ? getNodeAncestors(tree.nodesRef.current, getNodeId()) : [];\n const rootAncestorComboboxDomReference = (_ancestors$find = ancestors.find(node => {\n var _node$context6;\n return isTypeableCombobox(((_node$context6 = node.context) == null ? void 0 : _node$context6.elements.domReference) || null);\n })) == null || (_ancestors$find = _ancestors$find.context) == null ? void 0 : _ancestors$find.elements.domReference;\n const insideElements = [floating, rootAncestorComboboxDomReference, ...portalNodes, ...getInsideElements(), startDismissButtonRef.current, endDismissButtonRef.current, beforeGuardRef.current, afterGuardRef.current, portalContext == null ? void 0 : portalContext.beforeOutsideRef.current, portalContext == null ? void 0 : portalContext.afterOutsideRef.current, orderRef.current.includes('reference') || isUntrappedTypeableCombobox ? domReference : null].filter(x => x != null);\n const cleanup = modal || isUntrappedTypeableCombobox ? markOthers(insideElements, !useInert, useInert) : markOthers(insideElements);\n return () => {\n cleanup();\n };\n }, [disabled, domReference, floating, modal, orderRef, portalContext, isUntrappedTypeableCombobox, guards, useInert, tree, getNodeId, getInsideElements]);\n useModernLayoutEffect(() => {\n if (disabled || !isHTMLElement(floatingFocusElement)) return;\n const doc = getDocument$1(floatingFocusElement);\n const previouslyFocusedElement = activeElement(doc);\n\n // Wait for any layout effect state setters to execute to set `tabIndex`.\n queueMicrotask(() => {\n const focusableElements = getTabbableElements(floatingFocusElement);\n const initialFocusValue = initialFocusRef.current;\n const elToFocus = (typeof initialFocusValue === 'number' ? focusableElements[initialFocusValue] : initialFocusValue.current) || floatingFocusElement;\n const focusAlreadyInsideFloatingEl = contains$1(floatingFocusElement, previouslyFocusedElement);\n if (!ignoreInitialFocus && !focusAlreadyInsideFloatingEl && open) {\n enqueueFocus(elToFocus, {\n preventScroll: elToFocus === floatingFocusElement\n });\n }\n });\n }, [disabled, open, floatingFocusElement, ignoreInitialFocus, getTabbableElements, initialFocusRef]);\n useModernLayoutEffect(() => {\n if (disabled || !floatingFocusElement) return;\n const doc = getDocument$1(floatingFocusElement);\n const previouslyFocusedElement = activeElement(doc);\n addPreviouslyFocusedElement(previouslyFocusedElement);\n\n // Dismissing via outside press should always ignore `returnFocus` to\n // prevent unwanted scrolling.\n function onOpenChange(_ref) {\n let {\n reason,\n event,\n nested\n } = _ref;\n if (['hover', 'safe-polygon'].includes(reason) && event.type === 'mouseleave') {\n preventReturnFocusRef.current = true;\n }\n if (reason !== 'outside-press') return;\n if (nested) {\n preventReturnFocusRef.current = false;\n } else if (isVirtualClick(event) || isVirtualPointerEvent(event)) {\n preventReturnFocusRef.current = false;\n } else {\n let isPreventScrollSupported = false;\n document.createElement('div').focus({\n get preventScroll() {\n isPreventScrollSupported = true;\n return false;\n }\n });\n if (isPreventScrollSupported) {\n preventReturnFocusRef.current = false;\n } else {\n preventReturnFocusRef.current = true;\n }\n }\n }\n events.on('openchange', onOpenChange);\n const fallbackEl = doc.createElement('span');\n fallbackEl.setAttribute('tabindex', '-1');\n fallbackEl.setAttribute('aria-hidden', 'true');\n Object.assign(fallbackEl.style, HIDDEN_STYLES);\n if (isInsidePortal && domReference) {\n domReference.insertAdjacentElement('afterend', fallbackEl);\n }\n function getReturnElement() {\n if (typeof returnFocusRef.current === 'boolean') {\n const el = domReference || getPreviouslyFocusedElement();\n return el && el.isConnected ? el : fallbackEl;\n }\n return returnFocusRef.current.current || fallbackEl;\n }\n return () => {\n events.off('openchange', onOpenChange);\n const activeEl = activeElement(doc);\n const isFocusInsideFloatingTree = contains$1(floating, activeEl) || tree && getNodeChildren$1(tree.nodesRef.current, getNodeId(), false).some(node => {\n var _node$context7;\n return contains$1((_node$context7 = node.context) == null ? void 0 : _node$context7.elements.floating, activeEl);\n });\n const returnElement = getReturnElement();\n queueMicrotask(() => {\n // This is `returnElement`, if it's tabbable, or its first tabbable child.\n const tabbableReturnElement = getFirstTabbableElement(returnElement);\n if (\n // eslint-disable-next-line react-hooks/exhaustive-deps\n returnFocusRef.current && !preventReturnFocusRef.current && isHTMLElement(tabbableReturnElement) && (\n // If the focus moved somewhere else after mount, avoid returning focus\n // since it likely entered a different element which should be\n // respected: https://github.com/floating-ui/floating-ui/issues/2607\n tabbableReturnElement !== activeEl && activeEl !== doc.body ? isFocusInsideFloatingTree : true)) {\n tabbableReturnElement.focus({\n preventScroll: true\n });\n }\n fallbackEl.remove();\n });\n };\n }, [disabled, floating, floatingFocusElement, returnFocusRef, dataRef, events, tree, isInsidePortal, domReference, getNodeId]);\n React.useEffect(() => {\n // The `returnFocus` cleanup behavior is inside a microtask; ensure we\n // wait for it to complete before resetting the flag.\n queueMicrotask(() => {\n preventReturnFocusRef.current = false;\n });\n return () => {\n queueMicrotask(clearDisconnectedPreviouslyFocusedElements);\n };\n }, [disabled]);\n\n // Synchronize the `context` & `modal` value to the FloatingPortal context.\n // It will decide whether or not it needs to render its own guards.\n useModernLayoutEffect(() => {\n if (disabled) return;\n if (!portalContext) return;\n portalContext.setFocusManagerState({\n modal,\n closeOnFocusOut,\n open,\n onOpenChange,\n domReference\n });\n return () => {\n portalContext.setFocusManagerState(null);\n };\n }, [disabled, portalContext, modal, open, onOpenChange, closeOnFocusOut, domReference]);\n useModernLayoutEffect(() => {\n if (disabled) return;\n if (!floatingFocusElement) return;\n handleTabIndex(floatingFocusElement, orderRef);\n }, [disabled, floatingFocusElement, orderRef]);\n function renderDismissButton(location) {\n if (disabled || !visuallyHiddenDismiss || !modal) {\n return null;\n }\n return /*#__PURE__*/jsx(VisuallyHiddenDismiss, {\n ref: location === 'start' ? startDismissButtonRef : endDismissButtonRef,\n onClick: event => onOpenChange(false, event.nativeEvent),\n children: typeof visuallyHiddenDismiss === 'string' ? visuallyHiddenDismiss : 'Dismiss'\n });\n }\n const shouldRenderGuards = !disabled && guards && (modal ? !isUntrappedTypeableCombobox : true) && (isInsidePortal || modal);\n return /*#__PURE__*/jsxs(Fragment, {\n children: [shouldRenderGuards && /*#__PURE__*/jsx(FocusGuard, {\n \"data-type\": \"inside\",\n ref: mergedBeforeGuardRef,\n onFocus: event => {\n if (modal) {\n const els = getTabbableElements();\n enqueueFocus(order[0] === 'reference' ? els[0] : els[els.length - 1]);\n } else if (portalContext != null && portalContext.preserveTabOrder && portalContext.portalNode) {\n preventReturnFocusRef.current = false;\n if (isOutsideEvent(event, portalContext.portalNode)) {\n const nextTabbable = getNextTabbable(domReference);\n nextTabbable == null || nextTabbable.focus();\n } else {\n var _portalContext$before;\n (_portalContext$before = portalContext.beforeOutsideRef.current) == null || _portalContext$before.focus();\n }\n }\n }\n }), !isUntrappedTypeableCombobox && renderDismissButton('start'), children, renderDismissButton('end'), shouldRenderGuards && /*#__PURE__*/jsx(FocusGuard, {\n \"data-type\": \"inside\",\n ref: mergedAfterGuardRef,\n onFocus: event => {\n if (modal) {\n enqueueFocus(getTabbableElements()[0]);\n } else if (portalContext != null && portalContext.preserveTabOrder && portalContext.portalNode) {\n if (closeOnFocusOut) {\n preventReturnFocusRef.current = true;\n }\n if (isOutsideEvent(event, portalContext.portalNode)) {\n const prevTabbable = getPreviousTabbable(domReference);\n prevTabbable == null || prevTabbable.focus();\n } else {\n var _portalContext$afterO;\n (_portalContext$afterO = portalContext.afterOutsideRef.current) == null || _portalContext$afterO.focus();\n }\n }\n }\n })]\n });\n}\n\nlet lockCount = 0;\nconst scrollbarProperty = '--floating-ui-scrollbar-width';\nfunction enableScrollLock() {\n const platform = getPlatform();\n const isIOS = /iP(hone|ad|od)|iOS/.test(platform) ||\n // iPads can claim to be MacIntel\n platform === 'MacIntel' && navigator.maxTouchPoints > 1;\n const bodyStyle = document.body.style;\n // RTL <body> scrollbar\n const scrollbarX = Math.round(document.documentElement.getBoundingClientRect().left) + document.documentElement.scrollLeft;\n const paddingProp = scrollbarX ? 'paddingLeft' : 'paddingRight';\n const scrollbarWidth = window.innerWidth - document.documentElement.clientWidth;\n const scrollX = bodyStyle.left ? parseFloat(bodyStyle.left) : window.scrollX;\n const scrollY = bodyStyle.top ? parseFloat(bodyStyle.top) : window.scrollY;\n bodyStyle.overflow = 'hidden';\n bodyStyle.setProperty(scrollbarProperty, scrollbarWidth + \"px\");\n if (scrollbarWidth) {\n bodyStyle[paddingProp] = scrollbarWidth + \"px\";\n }\n\n // Only iOS doesn't respect `overflow: hidden` on document.body, and this\n // technique has fewer side effects.\n if (isIOS) {\n var _window$visualViewpor, _window$visualViewpor2;\n // iOS 12 does not support `visualViewport`.\n const offsetLeft = ((_window$visualViewpor = window.visualViewport) == null ? void 0 : _window$visualViewpor.offsetLeft) || 0;\n const offsetTop = ((_window$visualViewpor2 = window.visualViewport) == null ? void 0 : _window$visualViewpor2.offsetTop) || 0;\n Object.assign(bodyStyle, {\n position: 'fixed',\n top: -(scrollY - Math.floor(offsetTop)) + \"px\",\n left: -(scrollX - Math.floor(offsetLeft)) + \"px\",\n right: '0'\n });\n }\n return () => {\n Object.assign(bodyStyle, {\n overflow: '',\n [paddingProp]: ''\n });\n bodyStyle.removeProperty(scrollbarProperty);\n if (isIOS) {\n Object.assign(bodyStyle, {\n position: '',\n top: '',\n left: '',\n right: ''\n });\n window.scrollTo(scrollX, scrollY);\n }\n };\n}\nlet cleanup = () => {};\n\n/**\n * Provides base styling for a fixed overlay element to dim content or block\n * pointer events behind a floating element.\n * It's a regular `<div>`, so it can be styled via any CSS solution you prefer.\n * @see https://floating-ui.com/docs/FloatingOverlay\n */\nconst FloatingOverlay = /*#__PURE__*/React.forwardRef(function FloatingOverlay(props, ref) {\n const {\n lockScroll = false,\n ...rest\n } = props;\n useModernLayoutEffect(() => {\n if (!lockScroll) return;\n lockCount++;\n if (lockCount === 1) {\n cleanup = enableScrollLock();\n }\n return () => {\n lockCount--;\n if (lockCount === 0) {\n cleanup();\n }\n };\n }, [lockScroll]);\n return /*#__PURE__*/jsx(\"div\", {\n ref: ref,\n ...rest,\n style: {\n position: 'fixed',\n overflow: 'auto',\n top: 0,\n right: 0,\n bottom: 0,\n left: 0,\n ...rest.style\n }\n });\n});\n\nfunction isButtonTarget(event) {\n return isHTMLElement(event.target) && event.target.tagName === 'BUTTON';\n}\nfunction isAnchorTarget(event) {\n return isHTMLElement(event.target) && event.target.tagName === 'A';\n}\nfunction isSpaceIgnored(element) {\n return isTypeableElement(element);\n}\n/**\n * Opens or closes the floating element when clicking the reference element.\n * @see https://floating-ui.com/docs/useClick\n */\nfunction useClick(context, props) {\n if (props === void 0) {\n props = {};\n }\n const {\n open,\n onOpenChange,\n dataRef,\n elements: {\n domReference\n }\n } = context;\n const {\n enabled = true,\n event: eventOption = 'click',\n toggle = true,\n ignoreMouse = false,\n keyboardHandlers = true,\n stickIfOpen = true\n } = props;\n const pointerTypeRef = React.useRef();\n const didKeyDownRef = React.useRef(false);\n const reference = React.useMemo(() => ({\n onPointerDown(event) {\n pointerTypeRef.current = event.pointerType;\n },\n onMouseDown(event) {\n const pointerType = pointerTypeRef.current;\n\n // Ignore all buttons except for the \"main\" button.\n // https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button\n if (event.button !== 0) return;\n if (eventOption === 'click') return;\n if (isMouseLikePointerType(pointerType, true) && ignoreMouse) return;\n if (open && toggle && (dataRef.current.openEvent && stickIfOpen ? dataRef.current.openEvent.type === 'mousedown' : true)) {\n onOpenChange(false, event.nativeEvent, 'click');\n } else {\n // Prevent stealing focus from the floating element\n event.preventDefault();\n onOpenChange(true, event.nativeEvent, 'click');\n }\n },\n onClick(event) {\n const pointerType = pointerTypeRef.current;\n if (eventOption === 'mousedown' && pointerTypeRef.current) {\n pointerTypeRef.current = undefined;\n return;\n }\n if (isMouseLikePointerType(pointerType, true) && ignoreMouse) return;\n if (open && toggle && (dataRef.current.openEvent && stickIfOpen ? dataRef.current.openEvent.type === 'click' : true)) {\n onOpenChange(false, event.nativeEvent, 'click');\n } else {\n onOpenChange(true, event.nativeEvent, 'click');\n }\n },\n onKeyDown(event) {\n pointerTypeRef.current = undefined;\n if (event.defaultPrevented || !keyboardHandlers || isButtonTarget(event)) {\n return;\n }\n if (event.key === ' ' && !isSpaceIgnored(domReference)) {\n // Prevent scrolling\n event.preventDefault();\n didKeyDownRef.current = true;\n }\n if (isAnchorTarget(event)) {\n return;\n }\n if (event.key === 'Enter') {\n if (open && toggle) {\n onOpenChange(false, event.nativeEvent, 'click');\n } else {\n onOpenChange(true, event.nativeEvent, 'click');\n }\n }\n },\n onKeyUp(event) {\n if (event.defaultPrevented || !keyboardHandlers || isButtonTarget(event) || isSpaceIgnored(domReference)) {\n return;\n }\n if (event.key === ' ' && didKeyDownRef.current) {\n didKeyDownRef.current = false;\n if (open && toggle) {\n onOpenChange(false, event.nativeEvent, 'click');\n } else {\n onOpenChange(true, event.nativeEvent, 'click');\n }\n }\n }\n }), [dataRef, domReference, eventOption, ignoreMouse, keyboardHandlers, onOpenChange, open, stickIfOpen, toggle]);\n return React.useMemo(() => enabled ? {\n reference\n } : {}, [enabled, reference]);\n}\n\nfunction createVirtualElement(domElement, data) {\n let offsetX = null;\n let offsetY = null;\n let isAutoUpdateEvent = false;\n return {\n contextElement: domElement || undefined,\n getBoundingClientRect() {\n var _data$dataRef$current;\n const domRect = (domElement == null ? void 0 : domElement.getBoundingClientRect()) || {\n width: 0,\n height: 0,\n x: 0,\n y: 0\n };\n const isXAxis = data.axis === 'x' || data.axis === 'both';\n const isYAxis = data.axis === 'y' || data.axis === 'both';\n const canTrackCursorOnAutoUpdate = ['mouseenter', 'mousemove'].includes(((_data$dataRef$current = data.dataRef.current.openEvent) == null ? void 0 : _data$dataRef$current.type) || '') && data.pointerType !== 'touch';\n let width = domRect.width;\n let height = domRect.height;\n let x = domRect.x;\n let y = domRect.y;\n if (offsetX == null && data.x && isXAxis) {\n offsetX = domRect.x - data.x;\n }\n if (offsetY == null && data.y && isYAxis) {\n offsetY = domRect.y - data.y;\n }\n x -= offsetX || 0;\n y -= offsetY || 0;\n width = 0;\n height = 0;\n if (!isAutoUpdateEvent || canTrackCursorOnAutoUpdate) {\n width = data.axis === 'y' ? domRect.width : 0;\n height = data.axis === 'x' ? domRect.height : 0;\n x = isXAxis && data.x != null ? data.x : x;\n y = isYAxis && data.y != null ? data.y : y;\n } else if (isAutoUpdateEvent && !canTrackCursorOnAutoUpdate) {\n height = data.axis === 'x' ? domRect.height : height;\n width = data.axis === 'y' ? domRect.width : width;\n }\n isAutoUpdateEvent = true;\n return {\n width,\n height,\n x,\n y,\n top: y,\n right: x + width,\n bottom: y + height,\n left: x\n };\n }\n };\n}\nfunction isMouseBasedEvent(event) {\n return event != null && event.clientX != null;\n}\n/**\n * Positions the floating element relative to a client point (in the viewport),\n * such as the mouse position. By default, it follows the mouse cursor.\n * @see https://floating-ui.com/docs/useClientPoint\n */\nfunction useClientPoint(context, props) {\n if (props === void 0) {\n props = {};\n }\n const {\n open,\n dataRef,\n elements: {\n floating,\n domReference\n },\n refs\n } = context;\n const {\n enabled = true,\n axis = 'both',\n x = null,\n y = null\n } = props;\n const initialRef = React.useRef(false);\n const cleanupListenerRef = React.useRef(null);\n const [pointerType, setPointerType] = React.useState();\n const [reactive, setReactive] = React.useState([]);\n const setReference = useEffectEvent((x, y) => {\n if (initialRef.current) return;\n\n // Prevent setting if the open event was not a mouse-like one\n // (e.g. focus to open, then hover over the reference element).\n // Only apply if the event exists.\n if (dataRef.current.openEvent && !isMouseBasedEvent(dataRef.current.openEvent)) {\n return;\n }\n refs.setPositionReference(createVirtualElement(domReference, {\n x,\n y,\n axis,\n dataRef,\n pointerType\n }));\n });\n const handleReferenceEnterOrMove = useEffectEvent(event => {\n if (x != null || y != null) return;\n if (!open) {\n setReference(event.clientX, event.clientY);\n } else if (!cleanupListenerRef.current) {\n // If there's no cleanup, there's no listener, but we want to ensure\n // we add the listener if the cursor landed on the floating element and\n // then back on the reference (i.e. it's interactive).\n setReactive([]);\n }\n });\n\n // If the pointer is a mouse-like pointer, we want to continue following the\n // mouse even if the floating element is transitioning out. On touch\n // devices, this is undesirable because the floating element will move to\n // the dismissal touch point.\n const openCheck = isMouseLikePointerType(pointerType) ? floating : open;\n const addListener = React.useCallback(() => {\n // Explicitly specified `x`/`y` coordinates shouldn't add a listener.\n if (!openCheck || !enabled || x != null || y != null) return;\n const win = getWindow(floating);\n function handleMouseMove(event) {\n const target = getTarget$1(event);\n if (!contains$1(floating, target)) {\n setReference(event.clientX, event.clientY);\n } else {\n win.removeEventListener('mousemove', handleMouseMove);\n cleanupListenerRef.current = null;\n }\n }\n if (!dataRef.current.openEvent || isMouseBasedEvent(dataRef.current.openEvent)) {\n win.addEventListener('mousemove', handleMouseMove);\n const cleanup = () => {\n win.removeEventListener('mousemove', handleMouseMove);\n cleanupListenerRef.current = null;\n };\n cleanupListenerRef.current = cleanup;\n return cleanup;\n }\n refs.setPositionReference(domReference);\n }, [openCheck, enabled, x, y, floating, dataRef, refs, domReference, setReference]);\n React.useEffect(() => {\n return addListener();\n }, [addListener, reactive]);\n React.useEffect(() => {\n if (enabled && !floating) {\n initialRef.current = false;\n }\n }, [enabled, floating]);\n React.useEffect(() => {\n if (!enabled && open) {\n initialRef.current = true;\n }\n }, [enabled, open]);\n useModernLayoutEffect(() => {\n if (enabled && (x != null || y != null)) {\n initialRef.current = false;\n setReference(x, y);\n }\n }, [enabled, x, y, setReference]);\n const reference = React.useMemo(() => {\n function setPointerTypeRef(_ref) {\n let {\n pointerType\n } = _ref;\n setPointerType(pointerType);\n }\n return {\n onPointerDown: setPointerTypeRef,\n onPointerEnter: setPointerTypeRef,\n onMouseMove: handleReferenceEnterOrMove,\n onMouseEnter: handleReferenceEnterOrMove\n };\n }, [handleReferenceEnterOrMove]);\n return React.useMemo(() => enabled ? {\n reference\n } : {}, [enabled, reference]);\n}\n\nconst bubbleHandlerKeys = {\n pointerdown: 'onPointerDown',\n mousedown: 'onMouseDown',\n click: 'onClick'\n};\nconst captureHandlerKeys = {\n pointerdown: 'onPointerDownCapture',\n mousedown: 'onMouseDownCapture',\n click: 'onClickCapture'\n};\nconst normalizeProp = normalizable => {\n var _normalizable$escapeK, _normalizable$outside;\n return {\n escapeKey: typeof normalizable === 'boolean' ? normalizable : (_normalizable$escapeK = normalizable == null ? void 0 : normalizable.escapeKey) != null ? _normalizable$escapeK : false,\n outsidePress: typeof normalizable === 'boolean' ? normalizable : (_normalizable$outside = normalizable == null ? void 0 : normalizable.outsidePress) != null ? _normalizable$outside : true\n };\n};\n/**\n * Closes the floating element when a dismissal is requested — by default, when\n * the user presses the `escape` key or outside of the floating element.\n * @see https://floating-ui.com/docs/useDismiss\n */\nfunction useDismiss(context, props) {\n if (props === void 0) {\n props = {};\n }\n const {\n open,\n onOpenChange,\n elements,\n dataRef\n } = context;\n const {\n enabled = true,\n escapeKey = true,\n outsidePress: unstable_outsidePress = true,\n outsidePressEvent = 'pointerdown',\n referencePress = false,\n referencePressEvent = 'pointerdown',\n ancestorScroll = false,\n bubbles,\n capture\n } = props;\n const tree = useFloatingTree();\n const outsidePressFn = useEffectEvent(typeof unstable_outsidePress === 'function' ? unstable_outsidePress : () => false);\n const outsidePress = typeof unstable_outsidePress === 'function' ? outsidePressFn : unstable_outsidePress;\n const endedOrStartedInsideRef = React.useRef(false);\n const {\n escapeKey: escapeKeyBubbles,\n outsidePress: outsidePressBubbles\n } = normalizeProp(bubbles);\n const {\n escapeKey: escapeKeyCapture,\n outsidePress: outsidePressCapture\n } = normalizeProp(capture);\n const isComposingRef = React.useRef(false);\n const closeOnEscapeKeyDown = useEffectEvent(event => {\n var _dataRef$current$floa;\n if (!open || !enabled || !escapeKey || event.key !== 'Escape') {\n return;\n }\n\n // Wait until IME is settled. Pressing `Escape` while composing should\n // close the compose menu, but not the floating element.\n if (isComposingRef.current) {\n return;\n }\n const nodeId = (_dataRef$current$floa = dataRef.current.floatingContext) == null ? void 0 : _dataRef$current$floa.nodeId;\n const children = tree ? getNodeChildren$1(tree.nodesRef.current, nodeId) : [];\n if (!escapeKeyBubbles) {\n event.stopPropagation();\n if (children.length > 0) {\n let shouldDismiss = true;\n children.forEach(child => {\n var _child$context;\n if ((_child$context = child.context) != null && _child$context.open && !child.context.dataRef.current.__escapeKeyBubbles) {\n shouldDismiss = false;\n return;\n }\n });\n if (!shouldDismiss) {\n return;\n }\n }\n }\n onOpenChange(false, isReactEvent(event) ? event.nativeEvent : event, 'escape-key');\n });\n const closeOnEscapeKeyDownCapture = useEffectEvent(event => {\n var _getTarget2;\n const callback = () => {\n var _getTarget;\n closeOnEscapeKeyDown(event);\n (_getTarget = getTarget$1(event)) == null || _getTarget.removeEventListener('keydown', callback);\n };\n (_getTarget2 = getTarget$1(event)) == null || _getTarget2.addEventListener('keydown', callback);\n });\n const closeOnPressOutside = useEffectEvent(event => {\n var _dataRef$current$floa2;\n // Given developers can stop the propagation of the synthetic event,\n // we can only be confident with a positive value.\n const insideReactTree = dataRef.current.insideReactTree;\n dataRef.current.insideReactTree = false;\n\n // When click outside is lazy (`click` event), handle dragging.\n // Don't close if:\n // - The click started inside the floating element.\n // - The click ended inside the floating element.\n const endedOrStartedInside = endedOrStartedInsideRef.current;\n endedOrStartedInsideRef.current = false;\n if (outsidePressEvent === 'click' && endedOrStartedInside) {\n return;\n }\n if (insideReactTree) {\n return;\n }\n if (typeof outsidePress === 'function' && !outsidePress(event)) {\n return;\n }\n const target = getTarget$1(event);\n const inertSelector = \"[\" + createAttribute('inert') + \"]\";\n const markers = getDocument$1(elements.floating).querySelectorAll(inertSelector);\n let targetRootAncestor = isElement(target) ? target : null;\n while (targetRootAncestor && !isLastTraversableNode(targetRootAncestor)) {\n const nextParent = getParentNode(targetRootAncestor);\n if (isLastTraversableNode(nextParent) || !isElement(nextParent)) {\n break;\n }\n targetRootAncestor = nextParent;\n }\n\n // Check if the click occurred on a third-party element injected after the\n // floating element rendered.\n if (markers.length && isElement(target) && !isRootElement(target) &&\n // Clicked on a direct ancestor (e.g. FloatingOverlay).\n !contains$1(target, elements.floating) &&\n // If the target root element contains none of the markers, then the\n // element was injected after the floating element rendered.\n Array.from(markers).every(marker => !contains$1(targetRootAncestor, marker))) {\n return;\n }\n\n // Check if the click occurred on the scrollbar\n if (isHTMLElement(target) && floating) {\n const lastTraversableNode = isLastTraversableNode(target);\n const style = getComputedStyle(target);\n const scrollRe = /auto|scroll/;\n const isScrollableX = lastTraversableNode || scrollRe.test(style.overflowX);\n const isScrollableY = lastTraversableNode || scrollRe.test(style.overflowY);\n const canScrollX = isScrollableX && target.clientWidth > 0 && target.scrollWidth > target.clientWidth;\n const canScrollY = isScrollableY && target.clientHeight > 0 && target.scrollHeight > target.clientHeight;\n const isRTL = style.direction === 'rtl';\n\n // Check click position relative to scrollbar.\n // In some browsers it is possible to change the <body> (or window)\n // scrollbar to the left side, but is very rare and is difficult to\n // check for. Plus, for modal dialogs with backdrops, it is more\n // important that the backdrop is checked but not so much the window.\n const pressedVerticalScrollbar = canScrollY && (isRTL ? event.offsetX <= target.offsetWidth - target.clientWidth : event.offsetX > target.clientWidth);\n const pressedHorizontalScrollbar = canScrollX && event.offsetY > target.clientHeight;\n if (pressedVerticalScrollbar || pressedHorizontalScrollbar) {\n return;\n }\n }\n const nodeId = (_dataRef$current$floa2 = dataRef.current.floatingContext) == null ? void 0 : _dataRef$current$floa2.nodeId;\n const targetIsInsideChildren = tree && getNodeChildren$1(tree.nodesRef.current, nodeId).some(node => {\n var _node$context;\n return isEventTargetWithin(event, (_node$context = node.context) == null ? void 0 : _node$context.elements.floating);\n });\n if (isEventTargetWithin(event, elements.floating) || isEventTargetWithin(event, elements.domReference) || targetIsInsideChildren) {\n return;\n }\n const children = tree ? getNodeChildren$1(tree.nodesRef.current, nodeId) : [];\n if (children.length > 0) {\n let shouldDismiss = true;\n children.forEach(child => {\n var _child$context2;\n if ((_child$context2 = child.context) != null && _child$context2.open && !child.context.dataRef.current.__outsidePressBubbles) {\n shouldDismiss = false;\n return;\n }\n });\n if (!shouldDismiss) {\n return;\n }\n }\n onOpenChange(false, event, 'outside-press');\n });\n const closeOnPressOutsideCapture = useEffectEvent(event => {\n var _getTarget4;\n const callback = () => {\n var _getTarget3;\n closeOnPressOutside(event);\n (_getTarget3 = getTarget$1(event)) == null || _getTarget3.removeEventListener(outsidePressEvent, callback);\n };\n (_getTarget4 = getTarget$1(event)) == null || _getTarget4.addEventListener(outsidePressEvent, callback);\n });\n React.useEffect(() => {\n if (!open || !enabled) {\n return;\n }\n dataRef.current.__escapeKeyBubbles = escapeKeyBubbles;\n dataRef.current.__outsidePressBubbles = outsidePressBubbles;\n let compositionTimeout = -1;\n function onScroll(event) {\n onOpenChange(false, event, 'ancestor-scroll');\n }\n function handleCompositionStart() {\n window.clearTimeout(compositionTimeout);\n isComposingRef.current = true;\n }\n function handleCompositionEnd() {\n // Safari fires `compositionend` before `keydown`, so we need to wait\n // until the next tick to set `isComposing` to `false`.\n // https://bugs.webkit.org/show_bug.cgi?id=165004\n compositionTimeout = window.setTimeout(() => {\n isComposingRef.current = false;\n },\n // 0ms or 1ms don't work in Safari. 5ms appears to consistently work.\n // Only apply to WebKit for the test to remain 0ms.\n isWebKit() ? 5 : 0);\n }\n const doc = getDocument$1(elements.floating);\n if (escapeKey) {\n doc.addEventListener('keydown', escapeKeyCapture ? closeOnEscapeKeyDownCapture : closeOnEscapeKeyDown, escapeKeyCapture);\n doc.addEventListener('compositionstart', handleCompositionStart);\n doc.addEventListener('compositionend', handleCompositionEnd);\n }\n outsidePress && doc.addEventListener(outsidePressEvent, outsidePressCapture ? closeOnPressOutsideCapture : closeOnPressOutside, outsidePressCapture);\n let ancestors = [];\n if (ancestorScroll) {\n if (isElement(elements.domReference)) {\n ancestors = getOverflowAncestors(elements.domReference);\n }\n if (isElement(elements.floating)) {\n ancestors = ancestors.concat(getOverflowAncestors(elements.floating));\n }\n if (!isElement(elements.reference) && elements.reference && elements.reference.contextElement) {\n ancestors = ancestors.concat(getOverflowAncestors(elements.reference.contextElement));\n }\n }\n\n // Ignore the visual viewport for scrolling dismissal (allow pinch-zoom)\n ancestors = ancestors.filter(ancestor => {\n var _doc$defaultView;\n return ancestor !== ((_doc$defaultView = doc.defaultView) == null ? void 0 : _doc$defaultView.visualViewport);\n });\n ancestors.forEach(ancestor => {\n ancestor.addEventListener('scroll', onScroll, {\n passive: true\n });\n });\n return () => {\n if (escapeKey) {\n doc.removeEventListener('keydown', escapeKeyCapture ? closeOnEscapeKeyDownCapture : closeOnEscapeKeyDown, escapeKeyCapture);\n doc.removeEventListener('compositionstart', handleCompositionStart);\n doc.removeEventListener('compositionend', handleCompositionEnd);\n }\n outsidePress && doc.removeEventListener(outsidePressEvent, outsidePressCapture ? closeOnPressOutsideCapture : closeOnPressOutside, outsidePressCapture);\n ancestors.forEach(ancestor => {\n ancestor.removeEventListener('scroll', onScroll);\n });\n window.clearTimeout(compositionTimeout);\n };\n }, [dataRef, elements, escapeKey, outsidePress, outsidePressEvent, open, onOpenChange, ancestorScroll, enabled, escapeKeyBubbles, outsidePressBubbles, closeOnEscapeKeyDown, escapeKeyCapture, closeOnEscapeKeyDownCapture, closeOnPressOutside, outsidePressCapture, closeOnPressOutsideCapture]);\n React.useEffect(() => {\n dataRef.current.insideReactTree = false;\n }, [dataRef, outsidePress, outsidePressEvent]);\n const reference = React.useMemo(() => ({\n onKeyDown: closeOnEscapeKeyDown,\n ...(referencePress && {\n [bubbleHandlerKeys[referencePressEvent]]: event => {\n onOpenChange(false, event.nativeEvent, 'reference-press');\n },\n ...(referencePressEvent !== 'click' && {\n onClick(event) {\n onOpenChange(false, event.nativeEvent, 'reference-press');\n }\n })\n })\n }), [closeOnEscapeKeyDown, onOpenChange, referencePress, referencePressEvent]);\n const floating = React.useMemo(() => ({\n onKeyDown: closeOnEscapeKeyDown,\n onMouseDown() {\n endedOrStartedInsideRef.current = true;\n },\n onMouseUp() {\n endedOrStartedInsideRef.current = true;\n },\n [captureHandlerKeys[outsidePressEvent]]: () => {\n dataRef.current.insideReactTree = true;\n }\n }), [closeOnEscapeKeyDown, outsidePressEvent, dataRef]);\n return React.useMemo(() => enabled ? {\n reference,\n floating\n } : {}, [enabled, reference, floating]);\n}\n\nfunction useFloatingRootContext(options) {\n const {\n open = false,\n onOpenChange: onOpenChangeProp,\n elements: elementsProp\n } = options;\n const floatingId = useId();\n const dataRef = React.useRef({});\n const [events] = React.useState(() => createEventEmitter());\n const nested = useFloatingParentNodeId() != null;\n if (process.env.NODE_ENV !== \"production\") {\n const optionDomReference = elementsProp.reference;\n if (optionDomReference && !isElement(optionDomReference)) {\n error('Cannot pass a virtual element to the `elements.reference` option,', 'as it must be a real DOM element. Use `refs.setPositionReference()`', 'instead.');\n }\n }\n const [positionReference, setPositionReference] = React.useState(elementsProp.reference);\n const onOpenChange = useEffectEvent((open, event, reason) => {\n dataRef.current.openEvent = open ? event : undefined;\n events.emit('openchange', {\n open,\n event,\n reason,\n nested\n });\n onOpenChangeProp == null || onOpenChangeProp(open, event, reason);\n });\n const refs = React.useMemo(() => ({\n setPositionReference\n }), []);\n const elements = React.useMemo(() => ({\n reference: positionReference || elementsProp.reference || null,\n floating: elementsProp.floating || null,\n domReference: elementsProp.reference\n }), [positionReference, elementsProp.reference, elementsProp.floating]);\n return React.useMemo(() => ({\n dataRef,\n open,\n onOpenChange,\n elements,\n events,\n floatingId,\n refs\n }), [open, onOpenChange, elements, events, floatingId, refs]);\n}\n\n/**\n * Provides data to position a floating element and context to add interactions.\n * @see https://floating-ui.com/docs/useFloating\n */\nfunction useFloating(options) {\n if (options === void 0) {\n options = {};\n }\n const {\n nodeId\n } = options;\n const internalRootContext = useFloatingRootContext({\n ...options,\n elements: {\n reference: null,\n floating: null,\n ...options.elements\n }\n });\n const rootContext = options.rootContext || internalRootContext;\n const computedElements = rootContext.elements;\n const [_domReference, setDomReference] = React.useState(null);\n const [positionReference, _setPositionReference] = React.useState(null);\n const optionDomReference = computedElements == null ? void 0 : computedElements.domReference;\n const domReference = optionDomReference || _domReference;\n const domReferenceRef = React.useRef(null);\n const tree = useFloatingTree();\n useModernLayoutEffect(() => {\n if (domReference) {\n domReferenceRef.current = domReference;\n }\n }, [domReference]);\n const position = useFloating$1({\n ...options,\n elements: {\n ...computedElements,\n ...(positionReference && {\n reference: positionReference\n })\n }\n });\n const setPositionReference = React.useCallback(node => {\n const computedPositionReference = isElement(node) ? {\n getBoundingClientRect: () => node.getBoundingClientRect(),\n getClientRects: () => node.getClientRects(),\n contextElement: node\n } : node;\n // Store the positionReference in state if the DOM reference is specified externally via the\n // `elements.reference` option. This ensures that it won't be overridden on future renders.\n _setPositionReference(computedPositionReference);\n position.refs.setReference(computedPositionReference);\n }, [position.refs]);\n const setReference = React.useCallback(node => {\n if (isElement(node) || node === null) {\n domReferenceRef.current = node;\n setDomReference(node);\n }\n\n // Backwards-compatibility for passing a virtual element to `reference`\n // after it has set the DOM reference.\n if (isElement(position.refs.reference.current) || position.refs.reference.current === null ||\n // Don't allow setting virtual elements using the old technique back to\n // `null` to support `positionReference` + an unstable `reference`\n // callback ref.\n node !== null && !isElement(node)) {\n position.refs.setReference(node);\n }\n }, [position.refs]);\n const refs = React.useMemo(() => ({\n ...position.refs,\n setReference,\n setPositionReference,\n domReference: domReferenceRef\n }), [position.refs, setReference, setPositionReference]);\n const elements = React.useMemo(() => ({\n ...position.elements,\n domReference: domReference\n }), [position.elements, domReference]);\n const context = React.useMemo(() => ({\n ...position,\n ...rootContext,\n refs,\n elements,\n nodeId\n }), [position, refs, elements, nodeId, rootContext]);\n useModernLayoutEffect(() => {\n rootContext.dataRef.current.floatingContext = context;\n const node = tree == null ? void 0 : tree.nodesRef.current.find(node => node.id === nodeId);\n if (node) {\n node.context = context;\n }\n });\n return React.useMemo(() => ({\n ...position,\n context,\n refs,\n elements\n }), [position, refs, elements, context]);\n}\n\nfunction isMacSafari() {\n return isMac() && isSafari();\n}\n/**\n * Opens the floating element while the reference element has focus, like CSS\n * `:focus`.\n * @see https://floating-ui.com/docs/useFocus\n */\nfunction useFocus(context, props) {\n if (props === void 0) {\n props = {};\n }\n const {\n open,\n onOpenChange,\n events,\n dataRef,\n elements\n } = context;\n const {\n enabled = true,\n visibleOnly = true\n } = props;\n const blockFocusRef = React.useRef(false);\n const timeoutRef = React.useRef(-1);\n const keyboardModalityRef = React.useRef(true);\n React.useEffect(() => {\n if (!enabled) return;\n const win = getWindow(elements.domReference);\n\n // If the reference was focused and the user left the tab/window, and the\n // floating element was not open, the focus should be blocked when they\n // return to the tab/window.\n function onBlur() {\n if (!open && isHTMLElement(elements.domReference) && elements.domReference === activeElement(getDocument$1(elements.domReference))) {\n blockFocusRef.current = true;\n }\n }\n function onKeyDown() {\n keyboardModalityRef.current = true;\n }\n function onPointerDown() {\n keyboardModalityRef.current = false;\n }\n win.addEventListener('blur', onBlur);\n if (isMacSafari()) {\n win.addEventListener('keydown', onKeyDown, true);\n win.addEventListener('pointerdown', onPointerDown, true);\n }\n return () => {\n win.removeEventListener('blur', onBlur);\n if (isMacSafari()) {\n win.removeEventListener('keydown', onKeyDown, true);\n win.removeEventListener('pointerdown', onPointerDown, true);\n }\n };\n }, [elements.domReference, open, enabled]);\n React.useEffect(() => {\n if (!enabled) return;\n function onOpenChange(_ref) {\n let {\n reason\n } = _ref;\n if (reason === 'reference-press' || reason === 'escape-key') {\n blockFocusRef.current = true;\n }\n }\n events.on('openchange', onOpenChange);\n return () => {\n events.off('openchange', onOpenChange);\n };\n }, [events, enabled]);\n React.useEffect(() => {\n return () => {\n clearTimeoutIfSet(timeoutRef);\n };\n }, []);\n const reference = React.useMemo(() => ({\n onMouseLeave() {\n blockFocusRef.current = false;\n },\n onFocus(event) {\n if (blockFocusRef.current) return;\n const target = getTarget$1(event.nativeEvent);\n if (visibleOnly && isElement(target)) {\n // Safari fails to match `:focus-visible` if focus was initially\n // outside the document.\n if (isMacSafari() && !event.relatedTarget) {\n if (!keyboardModalityRef.current && !isTypeableElement(target)) {\n return;\n }\n } else if (!matchesFocusVisible(target)) {\n return;\n }\n }\n onOpenChange(true, event.nativeEvent, 'focus');\n },\n onBlur(event) {\n blockFocusRef.current = false;\n const relatedTarget = event.relatedTarget;\n const nativeEvent = event.nativeEvent;\n\n // Hit the non-modal focus management portal guard. Focus will be\n // moved into the floating element immediately after.\n const movedToFocusGuard = isElement(relatedTarget) && relatedTarget.hasAttribute(createAttribute('focus-guard')) && relatedTarget.getAttribute('data-type') === 'outside';\n\n // Wait for the window blur listener to fire.\n timeoutRef.current = window.setTimeout(() => {\n var _dataRef$current$floa;\n const activeEl = activeElement(elements.domReference ? elements.domReference.ownerDocument : document);\n\n // Focus left the page, keep it open.\n if (!relatedTarget && activeEl === elements.domReference) return;\n\n // When focusing the reference element (e.g. regular click), then\n // clicking into the floating element, prevent it from hiding.\n // Note: it must be focusable, e.g. `tabindex=\"-1\"`.\n // We can not rely on relatedTarget to point to the correct element\n // as it will only point to the shadow host of the newly focused element\n // and not the element that actually has received focus if it is located\n // inside a shadow root.\n if (contains$1((_dataRef$current$floa = dataRef.current.floatingContext) == null ? void 0 : _dataRef$current$floa.refs.floating.current, activeEl) || contains$1(elements.domReference, activeEl) || movedToFocusGuard) {\n return;\n }\n onOpenChange(false, nativeEvent, 'focus');\n });\n }\n }), [dataRef, elements.domReference, onOpenChange, visibleOnly]);\n return React.useMemo(() => enabled ? {\n reference\n } : {}, [enabled, reference]);\n}\n\nfunction mergeProps(userProps, propsList, elementKey) {\n const map = new Map();\n const isItem = elementKey === 'item';\n let domUserProps = userProps;\n if (isItem && userProps) {\n const {\n [ACTIVE_KEY]: _,\n [SELECTED_KEY]: __,\n ...validProps\n } = userProps;\n domUserProps = validProps;\n }\n return {\n ...(elementKey === 'floating' && {\n tabIndex: -1,\n [FOCUSABLE_ATTRIBUTE]: ''\n }),\n ...domUserProps,\n ...propsList.map(value => {\n const propsOrGetProps = value ? value[elementKey] : null;\n if (typeof propsOrGetProps === 'function') {\n return userProps ? propsOrGetProps(userProps) : null;\n }\n return propsOrGetProps;\n }).concat(userProps).reduce((acc, props) => {\n if (!props) {\n return acc;\n }\n Object.entries(props).forEach(_ref => {\n let [key, value] = _ref;\n if (isItem && [ACTIVE_KEY, SELECTED_KEY].includes(key)) {\n return;\n }\n if (key.indexOf('on') === 0) {\n if (!map.has(key)) {\n map.set(key, []);\n }\n if (typeof value === 'function') {\n var _map$get;\n (_map$get = map.get(key)) == null || _map$get.push(value);\n acc[key] = function () {\n var _map$get2;\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n return (_map$get2 = map.get(key)) == null ? void 0 : _map$get2.map(fn => fn(...args)).find(val => val !== undefined);\n };\n }\n } else {\n acc[key] = value;\n }\n });\n return acc;\n }, {})\n };\n}\n/**\n * Merges an array of interaction hooks' props into prop getters, allowing\n * event handler functions to be composed together without overwriting one\n * another.\n * @see https://floating-ui.com/docs/useInteractions\n */\nfunction useInteractions(propsList) {\n if (propsList === void 0) {\n propsList = [];\n }\n const referenceDeps = propsList.map(key => key == null ? void 0 : key.reference);\n const floatingDeps = propsList.map(key => key == null ? void 0 : key.floating);\n const itemDeps = propsList.map(key => key == null ? void 0 : key.item);\n const getReferenceProps = React.useCallback(userProps => mergeProps(userProps, propsList, 'reference'),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n referenceDeps);\n const getFloatingProps = React.useCallback(userProps => mergeProps(userProps, propsList, 'floating'),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n floatingDeps);\n const getItemProps = React.useCallback(userProps => mergeProps(userProps, propsList, 'item'),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n itemDeps);\n return React.useMemo(() => ({\n getReferenceProps,\n getFloatingProps,\n getItemProps\n }), [getReferenceProps, getFloatingProps, getItemProps]);\n}\n\nconst ESCAPE = 'Escape';\nfunction doSwitch(orientation, vertical, horizontal) {\n switch (orientation) {\n case 'vertical':\n return vertical;\n case 'horizontal':\n return horizontal;\n default:\n return vertical || horizontal;\n }\n}\nfunction isMainOrientationKey(key, orientation) {\n const vertical = key === ARROW_UP || key === ARROW_DOWN;\n const horizontal = key === ARROW_LEFT || key === ARROW_RIGHT;\n return doSwitch(orientation, vertical, horizontal);\n}\nfunction isMainOrientationToEndKey(key, orientation, rtl) {\n const vertical = key === ARROW_DOWN;\n const horizontal = rtl ? key === ARROW_LEFT : key === ARROW_RIGHT;\n return doSwitch(orientation, vertical, horizontal) || key === 'Enter' || key === ' ' || key === '';\n}\nfunction isCrossOrientationOpenKey(key, orientation, rtl) {\n const vertical = rtl ? key === ARROW_LEFT : key === ARROW_RIGHT;\n const horizontal = key === ARROW_DOWN;\n return doSwitch(orientation, vertical, horizontal);\n}\nfunction isCrossOrientationCloseKey(key, orientation, rtl, cols) {\n const vertical = rtl ? key === ARROW_RIGHT : key === ARROW_LEFT;\n const horizontal = key === ARROW_UP;\n if (orientation === 'both' || orientation === 'horizontal' && cols && cols > 1) {\n return key === ESCAPE;\n }\n return doSwitch(orientation, vertical, horizontal);\n}\n/**\n * Adds arrow key-based navigation of a list of items, either using real DOM\n * focus or virtual focus.\n * @see https://floating-ui.com/docs/useListNavigation\n */\nfunction useListNavigation(context, props) {\n const {\n open,\n onOpenChange,\n elements,\n floatingId\n } = context;\n const {\n listRef,\n activeIndex,\n onNavigate: unstable_onNavigate = () => {},\n enabled = true,\n selectedIndex = null,\n allowEscape = false,\n loop = false,\n nested = false,\n rtl = false,\n virtual = false,\n focusItemOnOpen = 'auto',\n focusItemOnHover = true,\n openOnArrowKeyDown = true,\n disabledIndices = undefined,\n orientation = 'vertical',\n parentOrientation,\n cols = 1,\n scrollItemIntoView = true,\n virtualItemRef,\n itemSizes,\n dense = false\n } = props;\n if (process.env.NODE_ENV !== \"production\") {\n if (allowEscape) {\n if (!loop) {\n warn('`useListNavigation` looping must be enabled to allow escaping.');\n }\n if (!virtual) {\n warn('`useListNavigation` must be virtual to allow escaping.');\n }\n }\n if (orientation === 'vertical' && cols > 1) {\n warn('In grid list navigation mode (`cols` > 1), the `orientation` should', 'be either \"horizontal\" or \"both\".');\n }\n }\n const floatingFocusElement = getFloatingFocusElement(elements.floating);\n const floatingFocusElementRef = useLatestRef(floatingFocusElement);\n const parentId = useFloatingParentNodeId();\n const tree = useFloatingTree();\n useModernLayoutEffect(() => {\n context.dataRef.current.orientation = orientation;\n }, [context, orientation]);\n const onNavigate = useEffectEvent(() => {\n unstable_onNavigate(indexRef.current === -1 ? null : indexRef.current);\n });\n const typeableComboboxReference = isTypeableCombobox(elements.domReference);\n const focusItemOnOpenRef = React.useRef(focusItemOnOpen);\n const indexRef = React.useRef(selectedIndex != null ? selectedIndex : -1);\n const keyRef = React.useRef(null);\n const isPointerModalityRef = React.useRef(true);\n const previousOnNavigateRef = React.useRef(onNavigate);\n const previousMountedRef = React.useRef(!!elements.floating);\n const previousOpenRef = React.useRef(open);\n const forceSyncFocusRef = React.useRef(false);\n const forceScrollIntoViewRef = React.useRef(false);\n const disabledIndicesRef = useLatestRef(disabledIndices);\n const latestOpenRef = useLatestRef(open);\n const scrollItemIntoViewRef = useLatestRef(scrollItemIntoView);\n const selectedIndexRef = useLatestRef(selectedIndex);\n const [activeId, setActiveId] = React.useState();\n const [virtualId, setVirtualId] = React.useState();\n const focusItem = useEffectEvent(() => {\n function runFocus(item) {\n if (virtual) {\n var _item$id;\n if ((_item$id = item.id) != null && _item$id.endsWith('-fui-option')) {\n item.id = floatingId + \"-\" + Math.random().toString(16).slice(2, 10);\n }\n setActiveId(item.id);\n tree == null || tree.events.emit('virtualfocus', item);\n if (virtualItemRef) {\n virtualItemRef.current = item;\n }\n } else {\n enqueueFocus(item, {\n sync: forceSyncFocusRef.current,\n preventScroll: true\n });\n }\n }\n const initialItem = listRef.current[indexRef.current];\n const forceScrollIntoView = forceScrollIntoViewRef.current;\n if (initialItem) {\n runFocus(initialItem);\n }\n const scheduler = forceSyncFocusRef.current ? v => v() : requestAnimationFrame;\n scheduler(() => {\n const waitedItem = listRef.current[indexRef.current] || initialItem;\n if (!waitedItem) return;\n if (!initialItem) {\n runFocus(waitedItem);\n }\n const scrollIntoViewOptions = scrollItemIntoViewRef.current;\n const shouldScrollIntoView = scrollIntoViewOptions && item && (forceScrollIntoView || !isPointerModalityRef.current);\n if (shouldScrollIntoView) {\n // JSDOM doesn't support `.scrollIntoView()` but it's widely supported\n // by all browsers.\n waitedItem.scrollIntoView == null || waitedItem.scrollIntoView(typeof scrollIntoViewOptions === 'boolean' ? {\n block: 'nearest',\n inline: 'nearest'\n } : scrollIntoViewOptions);\n }\n });\n });\n\n // Sync `selectedIndex` to be the `activeIndex` upon opening the floating\n // element. Also, reset `activeIndex` upon closing the floating element.\n useModernLayoutEffect(() => {\n if (!enabled) return;\n if (open && elements.floating) {\n if (focusItemOnOpenRef.current && selectedIndex != null) {\n // Regardless of the pointer modality, we want to ensure the selected\n // item comes into view when the floating element is opened.\n forceScrollIntoViewRef.current = true;\n indexRef.current = selectedIndex;\n onNavigate();\n }\n } else if (previousMountedRef.current) {\n // Since the user can specify `onNavigate` conditionally\n // (onNavigate: open ? setActiveIndex : setSelectedIndex),\n // we store and call the previous function.\n indexRef.current = -1;\n previousOnNavigateRef.current();\n }\n }, [enabled, open, elements.floating, selectedIndex, onNavigate]);\n\n // Sync `activeIndex` to be the focused item while the floating element is\n // open.\n useModernLayoutEffect(() => {\n if (!enabled) return;\n if (!open) return;\n if (!elements.floating) return;\n if (activeIndex == null) {\n forceSyncFocusRef.current = false;\n if (selectedIndexRef.current != null) {\n return;\n }\n\n // Reset while the floating element was open (e.g. the list changed).\n if (previousMountedRef.current) {\n indexRef.current = -1;\n focusItem();\n }\n\n // Initial sync.\n if ((!previousOpenRef.current || !previousMountedRef.current) && focusItemOnOpenRef.current && (keyRef.current != null || focusItemOnOpenRef.current === true && keyRef.current == null)) {\n let runs = 0;\n const waitForListPopulated = () => {\n if (listRef.current[0] == null) {\n // Avoid letting the browser paint if possible on the first try,\n // otherwise use rAF. Don't try more than twice, since something\n // is wrong otherwise.\n if (runs < 2) {\n const scheduler = runs ? requestAnimationFrame : queueMicrotask;\n scheduler(waitForListPopulated);\n }\n runs++;\n } else {\n indexRef.current = keyRef.current == null || isMainOrientationToEndKey(keyRef.current, orientation, rtl) || nested ? getMinListIndex(listRef, disabledIndicesRef.current) : getMaxListIndex(listRef, disabledIndicesRef.current);\n keyRef.current = null;\n onNavigate();\n }\n };\n waitForListPopulated();\n }\n } else if (!isIndexOutOfListBounds(listRef, activeIndex)) {\n indexRef.current = activeIndex;\n focusItem();\n forceScrollIntoViewRef.current = false;\n }\n }, [enabled, open, elements.floating, activeIndex, selectedIndexRef, nested, listRef, orientation, rtl, onNavigate, focusItem, disabledIndicesRef]);\n\n // Ensure the parent floating element has focus when a nested child closes\n // to allow arrow key navigation to work after the pointer leaves the child.\n useModernLayoutEffect(() => {\n var _nodes$find;\n if (!enabled || elements.floating || !tree || virtual || !previousMountedRef.current) {\n return;\n }\n const nodes = tree.nodesRef.current;\n const parent = (_nodes$find = nodes.find(node => node.id === parentId)) == null || (_nodes$find = _nodes$find.context) == null ? void 0 : _nodes$find.elements.floating;\n const activeEl = activeElement(getDocument$1(elements.floating));\n const treeContainsActiveEl = nodes.some(node => node.context && contains$1(node.context.elements.floating, activeEl));\n if (parent && !treeContainsActiveEl && isPointerModalityRef.current) {\n parent.focus({\n preventScroll: true\n });\n }\n }, [enabled, elements.floating, tree, parentId, virtual]);\n useModernLayoutEffect(() => {\n if (!enabled) return;\n if (!tree) return;\n if (!virtual) return;\n if (parentId) return;\n function handleVirtualFocus(item) {\n setVirtualId(item.id);\n if (virtualItemRef) {\n virtualItemRef.current = item;\n }\n }\n tree.events.on('virtualfocus', handleVirtualFocus);\n return () => {\n tree.events.off('virtualfocus', handleVirtualFocus);\n };\n }, [enabled, tree, virtual, parentId, virtualItemRef]);\n useModernLayoutEffect(() => {\n previousOnNavigateRef.current = onNavigate;\n previousOpenRef.current = open;\n previousMountedRef.current = !!elements.floating;\n });\n useModernLayoutEffect(() => {\n if (!open) {\n keyRef.current = null;\n focusItemOnOpenRef.current = focusItemOnOpen;\n }\n }, [open, focusItemOnOpen]);\n const hasActiveIndex = activeIndex != null;\n const item = React.useMemo(() => {\n function syncCurrentTarget(currentTarget) {\n if (!latestOpenRef.current) return;\n const index = listRef.current.indexOf(currentTarget);\n if (index !== -1 && indexRef.current !== index) {\n indexRef.current = index;\n onNavigate();\n }\n }\n const props = {\n onFocus(_ref) {\n let {\n currentTarget\n } = _ref;\n forceSyncFocusRef.current = true;\n syncCurrentTarget(currentTarget);\n },\n onClick: _ref2 => {\n let {\n currentTarget\n } = _ref2;\n return currentTarget.focus({\n preventScroll: true\n });\n },\n // Safari\n onMouseMove(_ref3) {\n let {\n currentTarget\n } = _ref3;\n forceSyncFocusRef.current = true;\n forceScrollIntoViewRef.current = false;\n if (focusItemOnHover) {\n syncCurrentTarget(currentTarget);\n }\n },\n onPointerLeave(_ref4) {\n let {\n pointerType\n } = _ref4;\n if (!isPointerModalityRef.current || pointerType === 'touch') {\n return;\n }\n forceSyncFocusRef.current = true;\n if (!focusItemOnHover) {\n return;\n }\n indexRef.current = -1;\n onNavigate();\n if (!virtual) {\n var _floatingFocusElement;\n (_floatingFocusElement = floatingFocusElementRef.current) == null || _floatingFocusElement.focus({\n preventScroll: true\n });\n }\n }\n };\n return props;\n }, [latestOpenRef, floatingFocusElementRef, focusItemOnHover, listRef, onNavigate, virtual]);\n const getParentOrientation = React.useCallback(() => {\n var _tree$nodesRef$curren;\n return parentOrientation != null ? parentOrientation : tree == null || (_tree$nodesRef$curren = tree.nodesRef.current.find(node => node.id === parentId)) == null || (_tree$nodesRef$curren = _tree$nodesRef$curren.context) == null || (_tree$nodesRef$curren = _tree$nodesRef$curren.dataRef) == null ? void 0 : _tree$nodesRef$curren.current.orientation;\n }, [parentId, tree, parentOrientation]);\n const commonOnKeyDown = useEffectEvent(event => {\n isPointerModalityRef.current = false;\n forceSyncFocusRef.current = true;\n\n // When composing a character, Chrome fires ArrowDown twice. Firefox/Safari\n // don't appear to suffer from this. `event.isComposing` is avoided due to\n // Safari not supporting it properly (although it's not needed in the first\n // place for Safari, just avoiding any possible issues).\n if (event.which === 229) {\n return;\n }\n\n // If the floating element is animating out, ignore navigation. Otherwise,\n // the `activeIndex` gets set to 0 despite not being open so the next time\n // the user ArrowDowns, the first item won't be focused.\n if (!latestOpenRef.current && event.currentTarget === floatingFocusElementRef.current) {\n return;\n }\n if (nested && isCrossOrientationCloseKey(event.key, orientation, rtl, cols)) {\n // If the nested list's close key is also the parent navigation key,\n // let the parent navigate. Otherwise, stop propagating the event.\n if (!isMainOrientationKey(event.key, getParentOrientation())) {\n stopEvent(event);\n }\n onOpenChange(false, event.nativeEvent, 'list-navigation');\n if (isHTMLElement(elements.domReference)) {\n if (virtual) {\n tree == null || tree.events.emit('virtualfocus', elements.domReference);\n } else {\n elements.domReference.focus();\n }\n }\n return;\n }\n const currentIndex = indexRef.current;\n const minIndex = getMinListIndex(listRef, disabledIndices);\n const maxIndex = getMaxListIndex(listRef, disabledIndices);\n if (!typeableComboboxReference) {\n if (event.key === 'Home') {\n stopEvent(event);\n indexRef.current = minIndex;\n onNavigate();\n }\n if (event.key === 'End') {\n stopEvent(event);\n indexRef.current = maxIndex;\n onNavigate();\n }\n }\n\n // Grid navigation.\n if (cols > 1) {\n const sizes = itemSizes || Array.from({\n length: listRef.current.length\n }, () => ({\n width: 1,\n height: 1\n }));\n // To calculate movements on the grid, we use hypothetical cell indices\n // as if every item was 1x1, then convert back to real indices.\n const cellMap = createGridCellMap(sizes, cols, dense);\n const minGridIndex = cellMap.findIndex(index => index != null && !isListIndexDisabled(listRef, index, disabledIndices));\n // last enabled index\n const maxGridIndex = cellMap.reduce((foundIndex, index, cellIndex) => index != null && !isListIndexDisabled(listRef, index, disabledIndices) ? cellIndex : foundIndex, -1);\n const index = cellMap[getGridNavigatedIndex({\n current: cellMap.map(itemIndex => itemIndex != null ? listRef.current[itemIndex] : null)\n }, {\n event,\n orientation,\n loop,\n rtl,\n cols,\n // treat undefined (empty grid spaces) as disabled indices so we\n // don't end up in them\n disabledIndices: getGridCellIndices([...((typeof disabledIndices !== 'function' ? disabledIndices : null) || listRef.current.map((_, index) => isListIndexDisabled(listRef, index, disabledIndices) ? index : undefined)), undefined], cellMap),\n minIndex: minGridIndex,\n maxIndex: maxGridIndex,\n prevIndex: getGridCellIndexOfCorner(indexRef.current > maxIndex ? minIndex : indexRef.current, sizes, cellMap, cols,\n // use a corner matching the edge closest to the direction\n // we're moving in so we don't end up in the same item. Prefer\n // top/left over bottom/right.\n event.key === ARROW_DOWN ? 'bl' : event.key === (rtl ? ARROW_LEFT : ARROW_RIGHT) ? 'tr' : 'tl'),\n stopEvent: true\n })];\n if (index != null) {\n indexRef.current = index;\n onNavigate();\n }\n if (orientation === 'both') {\n return;\n }\n }\n if (isMainOrientationKey(event.key, orientation)) {\n stopEvent(event);\n\n // Reset the index if no item is focused.\n if (open && !virtual && activeElement(event.currentTarget.ownerDocument) === event.currentTarget) {\n indexRef.current = isMainOrientationToEndKey(event.key, orientation, rtl) ? minIndex : maxIndex;\n onNavigate();\n return;\n }\n if (isMainOrientationToEndKey(event.key, orientation, rtl)) {\n if (loop) {\n indexRef.current = currentIndex >= maxIndex ? allowEscape && currentIndex !== listRef.current.length ? -1 : minIndex : findNonDisabledListIndex(listRef, {\n startingIndex: currentIndex,\n disabledIndices\n });\n } else {\n indexRef.current = Math.min(maxIndex, findNonDisabledListIndex(listRef, {\n startingIndex: currentIndex,\n disabledIndices\n }));\n }\n } else {\n if (loop) {\n indexRef.current = currentIndex <= minIndex ? allowEscape && currentIndex !== -1 ? listRef.current.length : maxIndex : findNonDisabledListIndex(listRef, {\n startingIndex: currentIndex,\n decrement: true,\n disabledIndices\n });\n } else {\n indexRef.current = Math.max(minIndex, findNonDisabledListIndex(listRef, {\n startingIndex: currentIndex,\n decrement: true,\n disabledIndices\n }));\n }\n }\n if (isIndexOutOfListBounds(listRef, indexRef.current)) {\n indexRef.current = -1;\n }\n onNavigate();\n }\n });\n const ariaActiveDescendantProp = React.useMemo(() => {\n return virtual && open && hasActiveIndex && {\n 'aria-activedescendant': virtualId || activeId\n };\n }, [virtual, open, hasActiveIndex, virtualId, activeId]);\n const floating = React.useMemo(() => {\n return {\n 'aria-orientation': orientation === 'both' ? undefined : orientation,\n ...(!typeableComboboxReference ? ariaActiveDescendantProp : {}),\n onKeyDown: commonOnKeyDown,\n onPointerMove() {\n isPointerModalityRef.current = true;\n }\n };\n }, [ariaActiveDescendantProp, commonOnKeyDown, orientation, typeableComboboxReference]);\n const reference = React.useMemo(() => {\n function checkVirtualMouse(event) {\n if (focusItemOnOpen === 'auto' && isVirtualClick(event.nativeEvent)) {\n focusItemOnOpenRef.current = true;\n }\n }\n function checkVirtualPointer(event) {\n // `pointerdown` fires first, reset the state then perform the checks.\n focusItemOnOpenRef.current = focusItemOnOpen;\n if (focusItemOnOpen === 'auto' && isVirtualPointerEvent(event.nativeEvent)) {\n focusItemOnOpenRef.current = true;\n }\n }\n return {\n ...ariaActiveDescendantProp,\n onKeyDown(event) {\n isPointerModalityRef.current = false;\n const isArrowKey = event.key.startsWith('Arrow');\n const isHomeOrEndKey = ['Home', 'End'].includes(event.key);\n const isMoveKey = isArrowKey || isHomeOrEndKey;\n const isCrossOpenKey = isCrossOrientationOpenKey(event.key, orientation, rtl);\n const isCrossCloseKey = isCrossOrientationCloseKey(event.key, orientation, rtl, cols);\n const isParentCrossOpenKey = isCrossOrientationOpenKey(event.key, getParentOrientation(), rtl);\n const isMainKey = isMainOrientationKey(event.key, orientation);\n const isNavigationKey = (nested ? isParentCrossOpenKey : isMainKey) || event.key === 'Enter' || event.key.trim() === '';\n if (virtual && open) {\n const rootNode = tree == null ? void 0 : tree.nodesRef.current.find(node => node.parentId == null);\n const deepestNode = tree && rootNode ? getDeepestNode(tree.nodesRef.current, rootNode.id) : null;\n if (isMoveKey && deepestNode && virtualItemRef) {\n const eventObject = new KeyboardEvent('keydown', {\n key: event.key,\n bubbles: true\n });\n if (isCrossOpenKey || isCrossCloseKey) {\n var _deepestNode$context, _deepestNode$context2;\n const isCurrentTarget = ((_deepestNode$context = deepestNode.context) == null ? void 0 : _deepestNode$context.elements.domReference) === event.currentTarget;\n const dispatchItem = isCrossCloseKey && !isCurrentTarget ? (_deepestNode$context2 = deepestNode.context) == null ? void 0 : _deepestNode$context2.elements.domReference : isCrossOpenKey ? listRef.current.find(item => (item == null ? void 0 : item.id) === activeId) : null;\n if (dispatchItem) {\n stopEvent(event);\n dispatchItem.dispatchEvent(eventObject);\n setVirtualId(undefined);\n }\n }\n if ((isMainKey || isHomeOrEndKey) && deepestNode.context) {\n if (deepestNode.context.open && deepestNode.parentId && event.currentTarget !== deepestNode.context.elements.domReference) {\n var _deepestNode$context$;\n stopEvent(event);\n (_deepestNode$context$ = deepestNode.context.elements.domReference) == null || _deepestNode$context$.dispatchEvent(eventObject);\n return;\n }\n }\n }\n return commonOnKeyDown(event);\n }\n // If a floating element should not open on arrow key down, avoid\n // setting `activeIndex` while it's closed.\n if (!open && !openOnArrowKeyDown && isArrowKey) {\n return;\n }\n if (isNavigationKey) {\n const isParentMainKey = isMainOrientationKey(event.key, getParentOrientation());\n keyRef.current = nested && isParentMainKey ? null : event.key;\n }\n if (nested) {\n if (isParentCrossOpenKey) {\n stopEvent(event);\n if (open) {\n indexRef.current = getMinListIndex(listRef, disabledIndicesRef.current);\n onNavigate();\n } else {\n onOpenChange(true, event.nativeEvent, 'list-navigation');\n }\n }\n return;\n }\n if (isMainKey) {\n if (selectedIndex != null) {\n indexRef.current = selectedIndex;\n }\n stopEvent(event);\n if (!open && openOnArrowKeyDown) {\n onOpenChange(true, event.nativeEvent, 'list-navigation');\n } else {\n commonOnKeyDown(event);\n }\n if (open) {\n onNavigate();\n }\n }\n },\n onFocus() {\n if (open && !virtual) {\n indexRef.current = -1;\n onNavigate();\n }\n },\n onPointerDown: checkVirtualPointer,\n onPointerEnter: checkVirtualPointer,\n onMouseDown: checkVirtualMouse,\n onClick: checkVirtualMouse\n };\n }, [activeId, ariaActiveDescendantProp, cols, commonOnKeyDown, disabledIndicesRef, focusItemOnOpen, listRef, nested, onNavigate, onOpenChange, open, openOnArrowKeyDown, orientation, getParentOrientation, rtl, selectedIndex, tree, virtual, virtualItemRef]);\n return React.useMemo(() => enabled ? {\n reference,\n floating,\n item\n } : {}, [enabled, reference, floating, item]);\n}\n\nconst componentRoleToAriaRoleMap = /*#__PURE__*/new Map([['select', 'listbox'], ['combobox', 'listbox'], ['label', false]]);\n\n/**\n * Adds base screen reader props to the reference and floating elements for a\n * given floating element `role`.\n * @see https://floating-ui.com/docs/useRole\n */\nfunction useRole(context, props) {\n var _elements$domReferenc, _componentRoleToAriaR;\n if (props === void 0) {\n props = {};\n }\n const {\n open,\n elements,\n floatingId: defaultFloatingId\n } = context;\n const {\n enabled = true,\n role = 'dialog'\n } = props;\n const defaultReferenceId = useId();\n const referenceId = ((_elements$domReferenc = elements.domReference) == null ? void 0 : _elements$domReferenc.id) || defaultReferenceId;\n const floatingId = React.useMemo(() => {\n var _getFloatingFocusElem;\n return ((_getFloatingFocusElem = getFloatingFocusElement(elements.floating)) == null ? void 0 : _getFloatingFocusElem.id) || defaultFloatingId;\n }, [elements.floating, defaultFloatingId]);\n const ariaRole = (_componentRoleToAriaR = componentRoleToAriaRoleMap.get(role)) != null ? _componentRoleToAriaR : role;\n const parentId = useFloatingParentNodeId();\n const isNested = parentId != null;\n const reference = React.useMemo(() => {\n if (ariaRole === 'tooltip' || role === 'label') {\n return {\n [\"aria-\" + (role === 'label' ? 'labelledby' : 'describedby')]: open ? floatingId : undefined\n };\n }\n return {\n 'aria-expanded': open ? 'true' : 'false',\n 'aria-haspopup': ariaRole === 'alertdialog' ? 'dialog' : ariaRole,\n 'aria-controls': open ? floatingId : undefined,\n ...(ariaRole === 'listbox' && {\n role: 'combobox'\n }),\n ...(ariaRole === 'menu' && {\n id: referenceId\n }),\n ...(ariaRole === 'menu' && isNested && {\n role: 'menuitem'\n }),\n ...(role === 'select' && {\n 'aria-autocomplete': 'none'\n }),\n ...(role === 'combobox' && {\n 'aria-autocomplete': 'list'\n })\n };\n }, [ariaRole, floatingId, isNested, open, referenceId, role]);\n const floating = React.useMemo(() => {\n const floatingProps = {\n id: floatingId,\n ...(ariaRole && {\n role: ariaRole\n })\n };\n if (ariaRole === 'tooltip' || role === 'label') {\n return floatingProps;\n }\n return {\n ...floatingProps,\n ...(ariaRole === 'menu' && {\n 'aria-labelledby': referenceId\n })\n };\n }, [ariaRole, floatingId, referenceId, role]);\n const item = React.useCallback(_ref => {\n let {\n active,\n selected\n } = _ref;\n const commonProps = {\n role: 'option',\n ...(active && {\n id: floatingId + \"-fui-option\"\n })\n };\n\n // For `menu`, we are unable to tell if the item is a `menuitemradio`\n // or `menuitemcheckbox`. For backwards-compatibility reasons, also\n // avoid defaulting to `menuitem` as it may overwrite custom role props.\n switch (role) {\n case 'select':\n case 'combobox':\n return {\n ...commonProps,\n 'aria-selected': selected\n };\n }\n return {};\n }, [floatingId, role]);\n return React.useMemo(() => enabled ? {\n reference,\n floating,\n item\n } : {}, [enabled, reference, floating, item]);\n}\n\n// Converts a JS style key like `backgroundColor` to a CSS transition-property\n// like `background-color`.\nconst camelCaseToKebabCase = str => str.replace(/[A-Z]+(?![a-z])|[A-Z]/g, ($, ofs) => (ofs ? '-' : '') + $.toLowerCase());\nfunction execWithArgsOrReturn(valueOrFn, args) {\n return typeof valueOrFn === 'function' ? valueOrFn(args) : valueOrFn;\n}\nfunction useDelayUnmount(open, durationMs) {\n const [isMounted, setIsMounted] = React.useState(open);\n if (open && !isMounted) {\n setIsMounted(true);\n }\n React.useEffect(() => {\n if (!open && isMounted) {\n const timeout = setTimeout(() => setIsMounted(false), durationMs);\n return () => clearTimeout(timeout);\n }\n }, [open, isMounted, durationMs]);\n return isMounted;\n}\n/**\n * Provides a status string to apply CSS transitions to a floating element,\n * correctly handling placement-aware transitions.\n * @see https://floating-ui.com/docs/useTransition#usetransitionstatus\n */\nfunction useTransitionStatus(context, props) {\n if (props === void 0) {\n props = {};\n }\n const {\n open,\n elements: {\n floating\n }\n } = context;\n const {\n duration = 250\n } = props;\n const isNumberDuration = typeof duration === 'number';\n const closeDuration = (isNumberDuration ? duration : duration.close) || 0;\n const [status, setStatus] = React.useState('unmounted');\n const isMounted = useDelayUnmount(open, closeDuration);\n if (!isMounted && status === 'close') {\n setStatus('unmounted');\n }\n useModernLayoutEffect(() => {\n if (!floating) return;\n if (open) {\n setStatus('initial');\n const frame = requestAnimationFrame(() => {\n // Ensure it opens before paint. With `FloatingDelayGroup`,\n // this avoids a flicker when moving between floating elements\n // to ensure one is always open with no missing frames.\n ReactDOM.flushSync(() => {\n setStatus('open');\n });\n });\n return () => {\n cancelAnimationFrame(frame);\n };\n }\n setStatus('close');\n }, [open, floating]);\n return {\n isMounted,\n status\n };\n}\n/**\n * Provides styles to apply CSS transitions to a floating element, correctly\n * handling placement-aware transitions. Wrapper around `useTransitionStatus`.\n * @see https://floating-ui.com/docs/useTransition#usetransitionstyles\n */\nfunction useTransitionStyles(context, props) {\n if (props === void 0) {\n props = {};\n }\n const {\n initial: unstable_initial = {\n opacity: 0\n },\n open: unstable_open,\n close: unstable_close,\n common: unstable_common,\n duration = 250\n } = props;\n const placement = context.placement;\n const side = placement.split('-')[0];\n const fnArgs = React.useMemo(() => ({\n side,\n placement\n }), [side, placement]);\n const isNumberDuration = typeof duration === 'number';\n const openDuration = (isNumberDuration ? duration : duration.open) || 0;\n const closeDuration = (isNumberDuration ? duration : duration.close) || 0;\n const [styles, setStyles] = React.useState(() => ({\n ...execWithArgsOrReturn(unstable_common, fnArgs),\n ...execWithArgsOrReturn(unstable_initial, fnArgs)\n }));\n const {\n isMounted,\n status\n } = useTransitionStatus(context, {\n duration\n });\n const initialRef = useLatestRef(unstable_initial);\n const openRef = useLatestRef(unstable_open);\n const closeRef = useLatestRef(unstable_close);\n const commonRef = useLatestRef(unstable_common);\n useModernLayoutEffect(() => {\n const initialStyles = execWithArgsOrReturn(initialRef.current, fnArgs);\n const closeStyles = execWithArgsOrReturn(closeRef.current, fnArgs);\n const commonStyles = execWithArgsOrReturn(commonRef.current, fnArgs);\n const openStyles = execWithArgsOrReturn(openRef.current, fnArgs) || Object.keys(initialStyles).reduce((acc, key) => {\n acc[key] = '';\n return acc;\n }, {});\n if (status === 'initial') {\n setStyles(styles => ({\n transitionProperty: styles.transitionProperty,\n ...commonStyles,\n ...initialStyles\n }));\n }\n if (status === 'open') {\n setStyles({\n transitionProperty: Object.keys(openStyles).map(camelCaseToKebabCase).join(','),\n transitionDuration: openDuration + \"ms\",\n ...commonStyles,\n ...openStyles\n });\n }\n if (status === 'close') {\n const styles = closeStyles || initialStyles;\n setStyles({\n transitionProperty: Object.keys(styles).map(camelCaseToKebabCase).join(','),\n transitionDuration: closeDuration + \"ms\",\n ...commonStyles,\n ...styles\n });\n }\n }, [closeDuration, closeRef, initialRef, openRef, commonRef, openDuration, status, fnArgs]);\n return {\n isMounted,\n styles\n };\n}\n\n/**\n * Provides a matching callback that can be used to focus an item as the user\n * types, often used in tandem with `useListNavigation()`.\n * @see https://floating-ui.com/docs/useTypeahead\n */\nfunction useTypeahead(context, props) {\n var _ref;\n const {\n open,\n dataRef\n } = context;\n const {\n listRef,\n activeIndex,\n onMatch: unstable_onMatch,\n onTypingChange: unstable_onTypingChange,\n enabled = true,\n findMatch = null,\n resetMs = 750,\n ignoreKeys = [],\n selectedIndex = null\n } = props;\n const timeoutIdRef = React.useRef(-1);\n const stringRef = React.useRef('');\n const prevIndexRef = React.useRef((_ref = selectedIndex != null ? selectedIndex : activeIndex) != null ? _ref : -1);\n const matchIndexRef = React.useRef(null);\n const onMatch = useEffectEvent(unstable_onMatch);\n const onTypingChange = useEffectEvent(unstable_onTypingChange);\n const findMatchRef = useLatestRef(findMatch);\n const ignoreKeysRef = useLatestRef(ignoreKeys);\n useModernLayoutEffect(() => {\n if (open) {\n clearTimeoutIfSet(timeoutIdRef);\n matchIndexRef.current = null;\n stringRef.current = '';\n }\n }, [open]);\n useModernLayoutEffect(() => {\n // Sync arrow key navigation but not typeahead navigation.\n if (open && stringRef.current === '') {\n var _ref2;\n prevIndexRef.current = (_ref2 = selectedIndex != null ? selectedIndex : activeIndex) != null ? _ref2 : -1;\n }\n }, [open, selectedIndex, activeIndex]);\n const setTypingChange = useEffectEvent(value => {\n if (value) {\n if (!dataRef.current.typing) {\n dataRef.current.typing = value;\n onTypingChange(value);\n }\n } else {\n if (dataRef.current.typing) {\n dataRef.current.typing = value;\n onTypingChange(value);\n }\n }\n });\n const onKeyDown = useEffectEvent(event => {\n function getMatchingIndex(list, orderedList, string) {\n const str = findMatchRef.current ? findMatchRef.current(orderedList, string) : orderedList.find(text => (text == null ? void 0 : text.toLocaleLowerCase().indexOf(string.toLocaleLowerCase())) === 0);\n return str ? list.indexOf(str) : -1;\n }\n const listContent = listRef.current;\n if (stringRef.current.length > 0 && stringRef.current[0] !== ' ') {\n if (getMatchingIndex(listContent, listContent, stringRef.current) === -1) {\n setTypingChange(false);\n } else if (event.key === ' ') {\n stopEvent(event);\n }\n }\n if (listContent == null || ignoreKeysRef.current.includes(event.key) ||\n // Character key.\n event.key.length !== 1 ||\n // Modifier key.\n event.ctrlKey || event.metaKey || event.altKey) {\n return;\n }\n if (open && event.key !== ' ') {\n stopEvent(event);\n setTypingChange(true);\n }\n\n // Bail out if the list contains a word like \"llama\" or \"aaron\". TODO:\n // allow it in this case, too.\n const allowRapidSuccessionOfFirstLetter = listContent.every(text => {\n var _text$, _text$2;\n return text ? ((_text$ = text[0]) == null ? void 0 : _text$.toLocaleLowerCase()) !== ((_text$2 = text[1]) == null ? void 0 : _text$2.toLocaleLowerCase()) : true;\n });\n\n // Allows the user to cycle through items that start with the same letter\n // in rapid succession.\n if (allowRapidSuccessionOfFirstLetter && stringRef.current === event.key) {\n stringRef.current = '';\n prevIndexRef.current = matchIndexRef.current;\n }\n stringRef.current += event.key;\n clearTimeoutIfSet(timeoutIdRef);\n timeoutIdRef.current = window.setTimeout(() => {\n stringRef.current = '';\n prevIndexRef.current = matchIndexRef.current;\n setTypingChange(false);\n }, resetMs);\n const prevIndex = prevIndexRef.current;\n const index = getMatchingIndex(listContent, [...listContent.slice((prevIndex || 0) + 1), ...listContent.slice(0, (prevIndex || 0) + 1)], stringRef.current);\n if (index !== -1) {\n onMatch(index);\n matchIndexRef.current = index;\n } else if (event.key !== ' ') {\n stringRef.current = '';\n setTypingChange(false);\n }\n });\n const reference = React.useMemo(() => ({\n onKeyDown\n }), [onKeyDown]);\n const floating = React.useMemo(() => {\n return {\n onKeyDown,\n onKeyUp(event) {\n if (event.key === ' ') {\n setTypingChange(false);\n }\n }\n };\n }, [onKeyDown, setTypingChange]);\n return React.useMemo(() => enabled ? {\n reference,\n floating\n } : {}, [enabled, reference, floating]);\n}\n\nfunction getArgsWithCustomFloatingHeight(state, height) {\n return {\n ...state,\n rects: {\n ...state.rects,\n floating: {\n ...state.rects.floating,\n height\n }\n }\n };\n}\n/**\n * Positions the floating element such that an inner element inside of it is\n * anchored to the reference element.\n * @see https://floating-ui.com/docs/inner\n * @deprecated\n */\nconst inner = props => ({\n name: 'inner',\n options: props,\n async fn(state) {\n const {\n listRef,\n overflowRef,\n onFallbackChange,\n offset: innerOffset = 0,\n index = 0,\n minItemsVisible = 4,\n referenceOverflowThreshold = 0,\n scrollRef,\n ...detectOverflowOptions\n } = evaluate(props, state);\n const {\n rects,\n platform,\n elements: {\n floating\n }\n } = state;\n const item = listRef.current[index];\n const scrollEl = (scrollRef == null ? void 0 : scrollRef.current) || floating;\n\n // Valid combinations:\n // 1. Floating element is the scrollRef and has a border (default)\n // 2. Floating element is not the scrollRef, floating element has a border\n // 3. Floating element is not the scrollRef, scrollRef has a border\n // Floating > {...getFloatingProps()} wrapper > scrollRef > items is not\n // allowed as VoiceOver doesn't work.\n const clientTop = floating.clientTop || scrollEl.clientTop;\n const floatingIsBordered = floating.clientTop !== 0;\n const scrollElIsBordered = scrollEl.clientTop !== 0;\n const floatingIsScrollEl = floating === scrollEl;\n if (process.env.NODE_ENV !== \"production\") {\n if (!state.placement.startsWith('bottom')) {\n warn('`placement` side must be \"bottom\" when using the `inner`', 'middleware.');\n }\n }\n if (!item) {\n return {};\n }\n const nextArgs = {\n ...state,\n ...(await offset(-item.offsetTop - floating.clientTop - rects.reference.height / 2 - item.offsetHeight / 2 - innerOffset).fn(state))\n };\n const overflow = await platform.detectOverflow(getArgsWithCustomFloatingHeight(nextArgs, scrollEl.scrollHeight + clientTop + floating.clientTop), detectOverflowOptions);\n const refOverflow = await platform.detectOverflow(nextArgs, {\n ...detectOverflowOptions,\n elementContext: 'reference'\n });\n const diffY = max(0, overflow.top);\n const nextY = nextArgs.y + diffY;\n const isScrollable = scrollEl.scrollHeight > scrollEl.clientHeight;\n const rounder = isScrollable ? v => v : round;\n const maxHeight = rounder(max(0, scrollEl.scrollHeight + (floatingIsBordered && floatingIsScrollEl || scrollElIsBordered ? clientTop * 2 : 0) - diffY - max(0, overflow.bottom)));\n scrollEl.style.maxHeight = maxHeight + \"px\";\n scrollEl.scrollTop = diffY;\n\n // There is not enough space, fallback to standard anchored positioning\n if (onFallbackChange) {\n const shouldFallback = scrollEl.offsetHeight < item.offsetHeight * min(minItemsVisible, listRef.current.length) - 1 || refOverflow.top >= -referenceOverflowThreshold || refOverflow.bottom >= -referenceOverflowThreshold;\n ReactDOM.flushSync(() => onFallbackChange(shouldFallback));\n }\n if (overflowRef) {\n overflowRef.current = await platform.detectOverflow(getArgsWithCustomFloatingHeight({\n ...nextArgs,\n y: nextY\n }, scrollEl.offsetHeight + clientTop + floating.clientTop), detectOverflowOptions);\n }\n return {\n y: nextY\n };\n }\n});\n/**\n * Changes the `inner` middleware's `offset` upon a `wheel` event to\n * expand the floating element's height, revealing more list items.\n * @see https://floating-ui.com/docs/inner\n * @deprecated\n */\nfunction useInnerOffset(context, props) {\n const {\n open,\n elements\n } = context;\n const {\n enabled = true,\n overflowRef,\n scrollRef,\n onChange: unstable_onChange\n } = props;\n const onChange = useEffectEvent(unstable_onChange);\n const controlledScrollingRef = React.useRef(false);\n const prevScrollTopRef = React.useRef(null);\n const initialOverflowRef = React.useRef(null);\n React.useEffect(() => {\n if (!enabled) return;\n function onWheel(e) {\n if (e.ctrlKey || !el || overflowRef.current == null) {\n return;\n }\n const dY = e.deltaY;\n const isAtTop = overflowRef.current.top >= -0.5;\n const isAtBottom = overflowRef.current.bottom >= -0.5;\n const remainingScroll = el.scrollHeight - el.clientHeight;\n const sign = dY < 0 ? -1 : 1;\n const method = dY < 0 ? 'max' : 'min';\n if (el.scrollHeight <= el.clientHeight) {\n return;\n }\n if (!isAtTop && dY > 0 || !isAtBottom && dY < 0) {\n e.preventDefault();\n ReactDOM.flushSync(() => {\n onChange(d => d + Math[method](dY, remainingScroll * sign));\n });\n } else if (/firefox/i.test(getUserAgent())) {\n // Needed to propagate scrolling during momentum scrolling phase once\n // it gets limited by the boundary. UX improvement, not critical.\n el.scrollTop += dY;\n }\n }\n const el = (scrollRef == null ? void 0 : scrollRef.current) || elements.floating;\n if (open && el) {\n el.addEventListener('wheel', onWheel);\n\n // Wait for the position to be ready.\n requestAnimationFrame(() => {\n prevScrollTopRef.current = el.scrollTop;\n if (overflowRef.current != null) {\n initialOverflowRef.current = {\n ...overflowRef.current\n };\n }\n });\n return () => {\n prevScrollTopRef.current = null;\n initialOverflowRef.current = null;\n el.removeEventListener('wheel', onWheel);\n };\n }\n }, [enabled, open, elements.floating, overflowRef, scrollRef, onChange]);\n const floating = React.useMemo(() => ({\n onKeyDown() {\n controlledScrollingRef.current = true;\n },\n onWheel() {\n controlledScrollingRef.current = false;\n },\n onPointerMove() {\n controlledScrollingRef.current = false;\n },\n onScroll() {\n const el = (scrollRef == null ? void 0 : scrollRef.current) || elements.floating;\n if (!overflowRef.current || !el || !controlledScrollingRef.current) {\n return;\n }\n if (prevScrollTopRef.current !== null) {\n const scrollDiff = el.scrollTop - prevScrollTopRef.current;\n if (overflowRef.current.bottom < -0.5 && scrollDiff < -1 || overflowRef.current.top < -0.5 && scrollDiff > 1) {\n ReactDOM.flushSync(() => onChange(d => d + scrollDiff));\n }\n }\n\n // [Firefox] Wait for the height change to have been applied.\n requestAnimationFrame(() => {\n prevScrollTopRef.current = el.scrollTop;\n });\n }\n }), [elements.floating, onChange, overflowRef, scrollRef]);\n return React.useMemo(() => enabled ? {\n floating\n } : {}, [enabled, floating]);\n}\n\nfunction getNodeChildren(nodes, id, onlyOpenChildren) {\n if (onlyOpenChildren === void 0) {\n onlyOpenChildren = true;\n }\n const directChildren = nodes.filter(node => {\n var _node$context;\n return node.parentId === id && (!onlyOpenChildren || ((_node$context = node.context) == null ? void 0 : _node$context.open));\n });\n return directChildren.flatMap(child => [child, ...getNodeChildren(nodes, child.id, onlyOpenChildren)]);\n}\n\nfunction isPointInPolygon(point, polygon) {\n const [x, y] = point;\n let isInside = false;\n const length = polygon.length;\n for (let i = 0, j = length - 1; i < length; j = i++) {\n const [xi, yi] = polygon[i] || [0, 0];\n const [xj, yj] = polygon[j] || [0, 0];\n const intersect = yi >= y !== yj >= y && x <= (xj - xi) * (y - yi) / (yj - yi) + xi;\n if (intersect) {\n isInside = !isInside;\n }\n }\n return isInside;\n}\nfunction isInside(point, rect) {\n return point[0] >= rect.x && point[0] <= rect.x + rect.width && point[1] >= rect.y && point[1] <= rect.y + rect.height;\n}\n/**\n * Generates a safe polygon area that the user can traverse without closing the\n * floating element once leaving the reference element.\n * @see https://floating-ui.com/docs/useHover#safepolygon\n */\nfunction safePolygon(options) {\n if (options === void 0) {\n options = {};\n }\n const {\n buffer = 0.5,\n blockPointerEvents = false,\n requireIntent = true\n } = options;\n const timeoutRef = {\n current: -1\n };\n let hasLanded = false;\n let lastX = null;\n let lastY = null;\n let lastCursorTime = typeof performance !== 'undefined' ? performance.now() : 0;\n function getCursorSpeed(x, y) {\n const currentTime = performance.now();\n const elapsedTime = currentTime - lastCursorTime;\n if (lastX === null || lastY === null || elapsedTime === 0) {\n lastX = x;\n lastY = y;\n lastCursorTime = currentTime;\n return null;\n }\n const deltaX = x - lastX;\n const deltaY = y - lastY;\n const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY);\n const speed = distance / elapsedTime; // px / ms\n\n lastX = x;\n lastY = y;\n lastCursorTime = currentTime;\n return speed;\n }\n const fn = _ref => {\n let {\n x,\n y,\n placement,\n elements,\n onClose,\n nodeId,\n tree\n } = _ref;\n return function onMouseMove(event) {\n function close() {\n clearTimeoutIfSet(timeoutRef);\n onClose();\n }\n clearTimeoutIfSet(timeoutRef);\n if (!elements.domReference || !elements.floating || placement == null || x == null || y == null) {\n return;\n }\n const {\n clientX,\n clientY\n } = event;\n const clientPoint = [clientX, clientY];\n const target = getTarget(event);\n const isLeave = event.type === 'mouseleave';\n const isOverFloatingEl = contains(elements.floating, target);\n const isOverReferenceEl = contains(elements.domReference, target);\n const refRect = elements.domReference.getBoundingClientRect();\n const rect = elements.floating.getBoundingClientRect();\n const side = placement.split('-')[0];\n const cursorLeaveFromRight = x > rect.right - rect.width / 2;\n const cursorLeaveFromBottom = y > rect.bottom - rect.height / 2;\n const isOverReferenceRect = isInside(clientPoint, refRect);\n const isFloatingWider = rect.width > refRect.width;\n const isFloatingTaller = rect.height > refRect.height;\n const left = (isFloatingWider ? refRect : rect).left;\n const right = (isFloatingWider ? refRect : rect).right;\n const top = (isFloatingTaller ? refRect : rect).top;\n const bottom = (isFloatingTaller ? refRect : rect).bottom;\n if (isOverFloatingEl) {\n hasLanded = true;\n if (!isLeave) {\n return;\n }\n }\n if (isOverReferenceEl) {\n hasLanded = false;\n }\n if (isOverReferenceEl && !isLeave) {\n hasLanded = true;\n return;\n }\n\n // Prevent overlapping floating element from being stuck in an open-close\n // loop: https://github.com/floating-ui/floating-ui/issues/1910\n if (isLeave && isElement(event.relatedTarget) && contains(elements.floating, event.relatedTarget)) {\n return;\n }\n\n // If any nested child is open, abort.\n if (tree && getNodeChildren(tree.nodesRef.current, nodeId).length) {\n return;\n }\n\n // If the pointer is leaving from the opposite side, the \"buffer\" logic\n // creates a point where the floating element remains open, but should be\n // ignored.\n // A constant of 1 handles floating point rounding errors.\n if (side === 'top' && y >= refRect.bottom - 1 || side === 'bottom' && y <= refRect.top + 1 || side === 'left' && x >= refRect.right - 1 || side === 'right' && x <= refRect.left + 1) {\n return close();\n }\n\n // Ignore when the cursor is within the rectangular trough between the\n // two elements. Since the triangle is created from the cursor point,\n // which can start beyond the ref element's edge, traversing back and\n // forth from the ref to the floating element can cause it to close. This\n // ensures it always remains open in that case.\n let rectPoly = [];\n switch (side) {\n case 'top':\n rectPoly = [[left, refRect.top + 1], [left, rect.bottom - 1], [right, rect.bottom - 1], [right, refRect.top + 1]];\n break;\n case 'bottom':\n rectPoly = [[left, rect.top + 1], [left, refRect.bottom - 1], [right, refRect.bottom - 1], [right, rect.top + 1]];\n break;\n case 'left':\n rectPoly = [[rect.right - 1, bottom], [rect.right - 1, top], [refRect.left + 1, top], [refRect.left + 1, bottom]];\n break;\n case 'right':\n rectPoly = [[refRect.right - 1, bottom], [refRect.right - 1, top], [rect.left + 1, top], [rect.left + 1, bottom]];\n break;\n }\n function getPolygon(_ref2) {\n let [x, y] = _ref2;\n switch (side) {\n case 'top':\n {\n const cursorPointOne = [isFloatingWider ? x + buffer / 2 : cursorLeaveFromRight ? x + buffer * 4 : x - buffer * 4, y + buffer + 1];\n const cursorPointTwo = [isFloatingWider ? x - buffer / 2 : cursorLeaveFromRight ? x + buffer * 4 : x - buffer * 4, y + buffer + 1];\n const commonPoints = [[rect.left, cursorLeaveFromRight ? rect.bottom - buffer : isFloatingWider ? rect.bottom - buffer : rect.top], [rect.right, cursorLeaveFromRight ? isFloatingWider ? rect.bottom - buffer : rect.top : rect.bottom - buffer]];\n return [cursorPointOne, cursorPointTwo, ...commonPoints];\n }\n case 'bottom':\n {\n const cursorPointOne = [isFloatingWider ? x + buffer / 2 : cursorLeaveFromRight ? x + buffer * 4 : x - buffer * 4, y - buffer];\n const cursorPointTwo = [isFloatingWider ? x - buffer / 2 : cursorLeaveFromRight ? x + buffer * 4 : x - buffer * 4, y - buffer];\n const commonPoints = [[rect.left, cursorLeaveFromRight ? rect.top + buffer : isFloatingWider ? rect.top + buffer : rect.bottom], [rect.right, cursorLeaveFromRight ? isFloatingWider ? rect.top + buffer : rect.bottom : rect.top + buffer]];\n return [cursorPointOne, cursorPointTwo, ...commonPoints];\n }\n case 'left':\n {\n const cursorPointOne = [x + buffer + 1, isFloatingTaller ? y + buffer / 2 : cursorLeaveFromBottom ? y + buffer * 4 : y - buffer * 4];\n const cursorPointTwo = [x + buffer + 1, isFloatingTaller ? y - buffer / 2 : cursorLeaveFromBottom ? y + buffer * 4 : y - buffer * 4];\n const commonPoints = [[cursorLeaveFromBottom ? rect.right - buffer : isFloatingTaller ? rect.right - buffer : rect.left, rect.top], [cursorLeaveFromBottom ? isFloatingTaller ? rect.right - buffer : rect.left : rect.right - buffer, rect.bottom]];\n return [...commonPoints, cursorPointOne, cursorPointTwo];\n }\n case 'right':\n {\n const cursorPointOne = [x - buffer, isFloatingTaller ? y + buffer / 2 : cursorLeaveFromBottom ? y + buffer * 4 : y - buffer * 4];\n const cursorPointTwo = [x - buffer, isFloatingTaller ? y - buffer / 2 : cursorLeaveFromBottom ? y + buffer * 4 : y - buffer * 4];\n const commonPoints = [[cursorLeaveFromBottom ? rect.left + buffer : isFloatingTaller ? rect.left + buffer : rect.right, rect.top], [cursorLeaveFromBottom ? isFloatingTaller ? rect.left + buffer : rect.right : rect.left + buffer, rect.bottom]];\n return [cursorPointOne, cursorPointTwo, ...commonPoints];\n }\n }\n }\n if (isPointInPolygon([clientX, clientY], rectPoly)) {\n return;\n }\n if (hasLanded && !isOverReferenceRect) {\n return close();\n }\n if (!isLeave && requireIntent) {\n const cursorSpeed = getCursorSpeed(event.clientX, event.clientY);\n const cursorSpeedThreshold = 0.1;\n if (cursorSpeed !== null && cursorSpeed < cursorSpeedThreshold) {\n return close();\n }\n }\n if (!isPointInPolygon([clientX, clientY], getPolygon([x, y]))) {\n close();\n } else if (!hasLanded && requireIntent) {\n timeoutRef.current = window.setTimeout(close, 40);\n }\n };\n };\n fn.__options = {\n blockPointerEvents\n };\n return fn;\n}\n\nexport { Composite, CompositeItem, FloatingArrow, FloatingDelayGroup, FloatingFocusManager, FloatingList, FloatingNode, FloatingOverlay, FloatingPortal, FloatingTree, NextFloatingDelayGroup, inner, safePolygon, useClick, useClientPoint, useDelayGroup, useDelayGroupContext, useDismiss, useFloating, useFloatingNodeId, useFloatingParentNodeId, useFloatingPortalNode, useFloatingRootContext, useFloatingTree, useFocus, useHover, useId, useInnerOffset, useInteractions, useListItem, useListNavigation, useMergeRefs, useNextDelayGroup, useRole, useTransitionStatus, useTransitionStyles, useTypeahead };\n","import React, { useEffect } from \"react\";\nimport { createPortal } from \"react-dom\";\nimport {\n autoUpdate,\n flip,\n offset as fOffset,\n shift,\n size,\n useFloating,\n type Placement,\n} from \"@floating-ui/react\";\n\ninterface PopoverProps {\n open: boolean;\n anchorEl: HTMLElement | null;\n onClose: () => void;\n placement?: Placement;\n offset?: number;\n sameWidth?: boolean;\n maxHeight?: number | string;\n zIndex?: number;\n className?: string;\n children: React.ReactNode;\n shouldIgnoreClose?: (target: Node) => boolean;\n}\n\nexport const Popover: React.FC<PopoverProps> = ({\n open,\n anchorEl,\n onClose,\n placement = \"bottom-start\",\n offset = 8,\n sameWidth = false,\n maxHeight,\n zIndex = 1000,\n className,\n children,\n shouldIgnoreClose,\n}) => {\n const { refs, floatingStyles, update } = useFloating({\n placement,\n whileElementsMounted: autoUpdate,\n middleware: [\n fOffset(offset),\n flip({ padding: 8 }),\n shift({ padding: 8 }),\n size({\n apply({ rects, elements, availableHeight, availableWidth }) {\n const el = elements.floating as HTMLElement;\n if (!el) return;\n if (sameWidth) {\n el.style.width = `${rects.reference.width}px`;\n }\n if (maxHeight != null) {\n el.style.maxHeight =\n typeof maxHeight === \"number\"\n ? `${maxHeight}px`\n : String(maxHeight);\n } else {\n el.style.maxHeight = `${availableHeight}px`;\n }\n if (availableWidth != null) {\n el.style.maxWidth = `${availableWidth}px`;\n }\n },\n }),\n ],\n });\n\n // Attach the reference programmatically\n useEffect(() => {\n if (anchorEl) refs.setReference(anchorEl);\n // Force an update when anchor changes\n if (open && update) update();\n }, [anchorEl, open, refs, update]);\n\n // Close on outside click and Escape\n useEffect(() => {\n if (!open) return;\n const onMouseDown = (e: MouseEvent) => {\n const t = e.target as Node;\n if (shouldIgnoreClose && shouldIgnoreClose(t)) return;\n const floating = refs.floating.current;\n if (!floating) return;\n if (\n (anchorEl && anchorEl.contains(t)) ||\n (floating && floating.contains(t))\n ) {\n return; // inside\n }\n onClose();\n };\n const onKeyDown = (e: KeyboardEvent) => {\n if (e.key === \"Escape\") onClose();\n };\n document.addEventListener(\"mousedown\", onMouseDown);\n document.addEventListener(\"keydown\", onKeyDown);\n return () => {\n document.removeEventListener(\"mousedown\", onMouseDown);\n document.removeEventListener(\"keydown\", onKeyDown);\n };\n }, [open, onClose, refs.floating, anchorEl]);\n\n if (!open || !anchorEl) return null;\n\n return createPortal(\n <div\n ref={refs.setFloating}\n data-popover-root=\"true\"\n style={{\n ...floatingStyles,\n zIndex,\n position: floatingStyles.position as any,\n overflowX: \"hidden\",\n }}\n className={className}\n >\n {children}\n </div>,\n document.body\n );\n};\n\nexport default Popover;\n","import {\n memo,\n useState,\n useRef,\n useEffect,\n ReactNode,\n ChangeEvent,\n useMemo,\n} from \"react\";\nimport {\n Search,\n Download,\n Filter,\n X,\n FileText,\n Database,\n Table,\n Settings,\n Eye,\n EyeOff,\n MoreHorizontal,\n Trash2,\n Copy,\n Edit,\n Archive,\n LocateFixed,\n} from \"../icons\";\nimport { ColumnFilterSelector } from \"./ColumnFilterSelector\";\nimport Popover from \"./Popover\";\nimport type {\n Density,\n BulkActionOption,\n SavedFilter,\n ExportFormat,\n} from \"../types\";\n\n// SearchMode removed along with UI\n\ninterface ColumnVisibility {\n [columnKey: string]: boolean;\n}\n\ninterface SearchToolbarProps {\n globalFilter: string;\n filteredDataLength: number;\n totalDataLength: number;\n paginationMode?: \"client\" | \"server\";\n totalRows?: number;\n selectedRowsCount?: number;\n selectedRows?: Set<string | number>;\n showExport?: boolean;\n showRefresh?: boolean;\n showColumnToggle?: boolean;\n showBulkActions?: boolean;\n showSavedFilters?: boolean;\n columns?: Array<{\n key: string;\n header: string;\n visible?: boolean;\n filterOptions?: Array<{ label: string; value: string | number }>;\n filterType?: \"text\" | \"select\" | \"multiselect\";\n filterable?: any;\n }>;\n columnVisibility?: ColumnVisibility;\n columnFilters?: Record<string, any>;\n savedFilters?: SavedFilter[];\n bulkActions?: BulkActionOption[];\n loading?: boolean;\n exportOptions?: {\n enabled: boolean;\n formats?: ExportFormat[];\n filename?: string;\n onExport?: (format: ExportFormat, exportSelected: boolean) => void;\n };\n onGlobalFilterChange: (e: ChangeEvent<HTMLInputElement>) => void;\n onClearFilters?: () => void;\n onRefresh?: () => void;\n onColumnVisibilityChange?: (columnKey: string, visible: boolean) => void;\n onColumnFilter?: (columnKey: string, filter: any) => void;\n onSaveFilter?: (filter: Omit<SavedFilter, \"id\">) => void;\n onLoadFilter?: (filter: SavedFilter) => void;\n onDeleteFilter?: (filterId: string) => void;\n onRowSelect?: (selectedRows: number[]) => void;\n onToggleFilters?: (show: boolean) => void;\n onResetColumns?: () => void;\n // New: reorder support\n columnOrder?: string[];\n onColumnOrderChange?: (order: string[]) => void;\n pinnedColumns?: Set<string>;\n // Scroll to a specific column in the grid\n onScrollToColumn?: (columnKey: string) => void;\n // Density controls\n density?: Density;\n onDensityChange?: (density: Density) => void;\n showDensityControl?: boolean;\n // Custom content slots\n customLeftContent?: ReactNode;\n customRightContent?: ReactNode;\n}\n\nconst SearchToolbarComponent = ({\n globalFilter,\n filteredDataLength,\n selectedRowsCount = 0,\n selectedRows = new Set(),\n showExport = true,\n showColumnToggle = true,\n showBulkActions = true,\n columns = [],\n columnVisibility = {},\n columnFilters = {},\n bulkActions = [],\n exportOptions,\n onGlobalFilterChange,\n onClearFilters,\n onColumnVisibilityChange,\n onColumnFilter,\n onResetColumns,\n columnOrder = [],\n onColumnOrderChange,\n pinnedColumns,\n onScrollToColumn,\n density = \"md\",\n onDensityChange,\n showDensityControl = false,\n customLeftContent,\n customRightContent,\n}: SearchToolbarProps) => {\n const [showExportMenu, setShowExportMenu] = useState(false);\n const [showFilters, setShowFilters] = useState(false);\n const [showBulkActionsMenu, setShowBulkActionsMenu] = useState(false);\n const [showColumnMenu, setShowColumnMenu] = useState(false);\n const [columnSearch, setColumnSearch] = useState(\"\");\n // DnD state for in-menu reordering\n const [draggingKey, setDraggingKey] = useState<string | null>(null);\n const [dragOver, setDragOver] = useState<{\n key: string;\n position: \"before\" | \"after\";\n } | null>(null);\n\n const searchInputRef = useRef<HTMLInputElement>(null);\n const exportMenuRef = useRef<HTMLDivElement>(null);\n const bulkActionsRef = useRef<HTMLDivElement>(null);\n const columnMenuRef = useRef<HTMLDivElement>(null);\n const filtersMenuRef = useRef<HTMLDivElement>(null);\n const filtersAnchorRef = useRef<HTMLButtonElement | null>(null);\n const exportAnchorRef = useRef<HTMLButtonElement | null>(null);\n const bulkActionsAnchorRef = useRef<HTMLButtonElement | null>(null);\n const columnAnchorRef = useRef<HTMLButtonElement | null>(null);\n\n // Close menus when clicking outside\n useEffect(() => {\n const handleClickOutside = (event: MouseEvent) => {\n // If clicking inside any portal popover root, do nothing here.\n const isInAnyPopover = (target: any): boolean => {\n let node: any = target;\n while (node) {\n if (\n (node.getAttribute &&\n node.getAttribute(\"data-popover-root\") === \"true\") ||\n (node.dataset && (node.dataset as any).popoverRoot === \"true\")\n )\n return true;\n node = node.parentNode;\n }\n return false;\n };\n\n if (isInAnyPopover(event.target)) return;\n // Helper: detect if click occurred inside a MUI Date Picker popup so we don't treat it as outside\n const isInMuiDatePicker = (target: any): boolean => {\n let node: any = target;\n while (node) {\n if (node.classList) {\n const cls = Array.from(node.classList).join(\" \");\n if (/MuiPickers|MuiDatePicker|MuiPickersPopper/.test(cls))\n return true;\n }\n // Some pickers add role=\"dialog\"\n if (node.getAttribute && node.getAttribute(\"role\") === \"dialog\") {\n const cls = node.className?.toString() || \"\";\n if (/MuiPickers|MuiDatePicker/.test(cls)) return true;\n }\n node = node.parentNode;\n }\n return false;\n };\n\n if (\n exportMenuRef.current &&\n !exportMenuRef.current.contains(event.target as Node)\n ) {\n setShowExportMenu(false);\n }\n if (\n bulkActionsRef.current &&\n !bulkActionsRef.current.contains(event.target as Node)\n ) {\n setShowBulkActionsMenu(false);\n }\n if (\n columnMenuRef.current &&\n !columnMenuRef.current.contains(event.target as Node)\n ) {\n setShowColumnMenu(false);\n }\n if (\n filtersMenuRef.current &&\n !filtersMenuRef.current.contains(event.target as Node) &&\n !isInMuiDatePicker(event.target)\n ) {\n setShowFilters(false);\n }\n };\n\n document.addEventListener(\"mousedown\", handleClickOutside);\n return () => document.removeEventListener(\"mousedown\", handleClickOutside);\n }, []);\n\n const exportFormats = exportOptions?.formats || [\"xlsx\"];\n const hasActiveFilters =\n (globalFilter?.length ?? 0) > 0 ||\n Object.keys(columnFilters || {}).length > 0;\n const hasSelectedRows = selectedRowsCount > 0;\n const visibleColumnsCount = columns.filter(\n (col) => columnVisibility[col.key] !== false,\n ).length;\n\n // Build ordered list based on columnOrder, append any missing, then filter by search\n const orderedAll = (() => {\n const fromOrder = columnOrder\n .map((k) => columns.find((c) => c.key === k))\n .filter(Boolean) as typeof columns;\n const missing = columns.filter((c) => !columnOrder.includes(c.key));\n return [...fromOrder, ...missing];\n })();\n\n const filteredColumns = orderedAll.filter((c) =>\n c.header?.toLowerCase()?.includes(columnSearch?.toLowerCase()),\n );\n\n // Search mode UI removed per request; default behavior remains in parent handlers.\n\n const getExportIcon = (format: ExportFormat) => {\n switch (format) {\n case \"csv\":\n return <Table size={18} />;\n case \"json\":\n return <Database size={18} />;\n case \"xlsx\":\n return <FileText size={18} />;\n default:\n return <Download size={18} />;\n }\n };\n\n const getBulkActionIcon = (action: string) => {\n switch (action) {\n case \"delete\":\n return <Trash2 size={18} />;\n case \"archive\":\n return <Archive size={18} />;\n case \"copy\":\n return <Copy size={18} />;\n case \"edit\":\n return <Edit size={18} />;\n case \"export\":\n return <Download size={18} />;\n default:\n return <MoreHorizontal size={18} />;\n }\n };\n\n const getFormatLabel = (format: ExportFormat) => {\n switch (format) {\n case \"csv\":\n return \"CSV\";\n case \"json\":\n return \"JSON\";\n case \"xlsx\":\n return \"Excel\";\n default:\n return format;\n }\n };\n\n const handleExport = (\n format: ExportFormat,\n exportSelected: boolean = false,\n ) => {\n exportOptions?.onExport?.(format, exportSelected);\n setShowExportMenu(false);\n };\n\n const handleBulkAction = (action: BulkActionOption) => {\n if (!action.disabled) {\n action.onClick(selectedRows);\n setShowBulkActionsMenu(false);\n }\n };\n\n const handleColumnToggle = (columnKey: string) => {\n const isVisible = columnVisibility[columnKey] !== false;\n onColumnVisibilityChange?.(columnKey, !isVisible);\n };\n\n // DnD handlers for reordering within menu\n const handleDragStart = (\n columnKey: string,\n e: React.DragEvent<HTMLLabelElement>,\n ) => {\n setDraggingKey(columnKey);\n e.dataTransfer.effectAllowed = \"move\";\n e.dataTransfer.setData(\"text/plain\", columnKey);\n };\n\n const handleDragOver = (\n targetKey: string,\n e: React.DragEvent<HTMLLabelElement>,\n ) => {\n e.preventDefault();\n e.dataTransfer.dropEffect = \"move\";\n const rect = (e.currentTarget as HTMLLabelElement).getBoundingClientRect();\n const midpoint = rect.top + rect.height / 2;\n const position = e.clientY < midpoint ? \"before\" : \"after\";\n setDragOver({ key: targetKey, position });\n };\n\n const handleDrop = (targetKey: string) => {\n const sourceKey = draggingKey;\n if (!sourceKey || sourceKey === targetKey) return;\n\n // respect pinned vs unpinned if provided\n if (pinnedColumns) {\n const sPinned = pinnedColumns.has(sourceKey);\n const tPinned = pinnedColumns.has(targetKey);\n if (sPinned !== tPinned) {\n setDraggingKey(null);\n setDragOver(null);\n return;\n }\n }\n\n const before =\n dragOver?.key === targetKey ? dragOver.position === \"before\" : true;\n const base = (\n columnOrder && columnOrder.length\n ? columnOrder\n : columns.map((c) => c.key)\n ).filter((k) => k !== sourceKey);\n let idx = base.indexOf(targetKey);\n if (idx === -1) {\n onColumnOrderChange?.(base);\n setDraggingKey(null);\n setDragOver(null);\n return;\n }\n if (!before) idx += 1;\n base.splice(idx, 0, sourceKey);\n onColumnOrderChange?.(base);\n setDraggingKey(null);\n setDragOver(null);\n };\n\n const handleDragEnd = () => {\n setDraggingKey(null);\n setDragOver(null);\n };\n\n // Search mode handler removed with UI\n\n const handleResetColumns = () => {\n columns.forEach((column) => {\n onColumnVisibilityChange?.(column.key, column.visible !== false);\n });\n onColumnOrderChange?.(columns.map((column) => column.key));\n onResetColumns?.();\n };\n\n const hasFilterableColumns = useMemo(\n () => columns.some((col) => col.filterable),\n [columns],\n );\n\n return (\n <div\n className=\"bg-white dark:bg-gray-900 border-b border-gray-200 dark:border-gray-700\"\n role=\"toolbar\"\n aria-label=\"Data grid toolbar\"\n >\n {/* Screen reader status region */}\n <div\n id=\"search-results-status\"\n className=\"sr-only\"\n role=\"status\"\n aria-live=\"polite\"\n aria-atomic=\"true\"\n >\n {hasActiveFilters\n ? `Showing ${filteredDataLength} of ${filteredDataLength} rows`\n : `${filteredDataLength} total rows`}\n {hasSelectedRows &&\n `, ${selectedRowsCount} row${\n selectedRowsCount !== 1 ? \"s\" : \"\"\n } selected`}\n </div>\n\n {/* Main Toolbar */}\n <div className=\"px-3 py-2\">\n <div className=\"flex flex-wrap items-center justify-between gap-2 sm:gap-4\">\n {/* Left Section - Actions */}\n <div className=\"order-1 flex items-center flex-wrap gap-2 sm:gap-3\">\n {/* Filter Toggle */}\n <div className=\"relative\" ref={filtersMenuRef}>\n {hasFilterableColumns && (\n <button\n ref={(el) => {\n filtersAnchorRef.current = el;\n }}\n onClick={() => setShowFilters(!showFilters)}\n className={`flex cursor-pointer items-center gap-2 px-3 py-2 border rounded-lg transition-colors ${\n showFilters\n ? \"bg-blue-50 dark:bg-blue-900/40 border-blue-200 dark:border-blue-600 text-blue-700 dark:text-blue-300\"\n : \"border-gray-300 dark:border-gray-600 text-gray-600 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-800\"\n }`}\n title=\"Toggle column filters (Ctrl+K)\"\n aria-label=\"Toggle column filters\"\n aria-haspopup=\"menu\"\n aria-expanded={showFilters}\n aria-controls=\"filters-menu\"\n aria-keyshortcuts=\"Control+K\"\n >\n <Filter className=\"w-4 h-4\" />\n <span className=\"hidden sm:inline\">Filters</span>\n {Object.keys(columnFilters).length > 0 && (\n <button\n type=\"button\"\n onClick={(e) => {\n e.stopPropagation();\n onClearFilters?.();\n }}\n className=\"bg-red-500 cursor-pointer hover:bg-red-600 text-white text-xs px-1.5 py-0.5 rounded-full min-w-5 h-5 flex items-center justify-center transition-all group relative\"\n title=\"Clear all filters\"\n >\n <span className=\"group-hover:hidden\">\n {Object.keys(columnFilters).length}\n </span>\n <X className=\"w-3 h-3 hidden group-hover:block absolute\" />\n </button>\n )}\n </button>\n )}\n <Popover\n open={showFilters}\n anchorEl={filtersAnchorRef.current}\n onClose={() => setShowFilters(false)}\n placement=\"bottom-start\"\n offset={8}\n zIndex={1000}\n maxHeight={520}\n className=\"w-88 sm:w-88 max-w-[90vw] bg-white border border-gray-200 rounded-lg shadow-xl overflow-y-auto min-h-100\"\n shouldIgnoreClose={(target) => {\n // Ignore clicks inside MUI pickers (often portal-rooted)\n let node: any = target;\n while (node) {\n if (node.classList) {\n const cls = Array.from(node.classList).join(\" \");\n if (/MuiPickers|MuiDatePicker|MuiPickersPopper/.test(cls))\n return true;\n }\n if (\n node.getAttribute &&\n node.getAttribute(\"role\") === \"dialog\"\n ) {\n const cls = node.className?.toString() || \"\";\n if (/MuiPickers|MuiDatePicker/.test(cls)) return true;\n }\n node = node.parentNode;\n }\n return false;\n }}\n >\n <div className=\"flex items-center justify-between px-2\">\n <div className=\"p-3 border-b border-gray-100\">\n <h3 className=\"font-medium text-gray-900\">\n Column Filters\n </h3>\n <p className=\"text-xs text-gray-500 mt-1\">\n Filter data by column values\n </p>\n </div>\n <button\n onClick={onClearFilters}\n className=\"px-3 py-1.5 text-sm text-gray-600 border border-gray-300 rounded-md hover:bg-gray-50 transition-colors\"\n >\n Clear All\n </button>\n </div>\n <div className=\"p-3 space-y-3\">\n <ColumnFilterSelector\n columns={columns}\n columnFilters={columnFilters}\n onColumnFilter={onColumnFilter}\n />\n </div>\n <div className=\"flex items-center justify-between p-3 border-t border-gray-200\">\n <div className=\"text-sm text-gray-600\">\n {Object.keys(columnFilters).length > 0 && (\n <span>\n {Object.keys(columnFilters).length} filter\n {Object.keys(columnFilters).length !== 1\n ? \"s\"\n : \"\"}{\" \"}\n applied\n </span>\n )}\n </div>\n </div>\n </Popover>\n </div>\n\n {/* Custom Left Content Slot */}\n {customLeftContent}\n </div>\n\n {/* Right Section - Actions */}\n <div className=\"order-2 flex items-center gap-2 sm:gap-3 flex-wrap sm:flex-nowrap\">\n {/* Custom Right Content Slot */}\n {customRightContent}\n {/* Search mode option removed */}\n\n {/* Bulk Actions */}\n {showBulkActions && hasSelectedRows && bulkActions.length > 0 && (\n <div className=\"relative\" ref={bulkActionsRef}>\n <button\n ref={(el) => {\n bulkActionsAnchorRef.current = el;\n }}\n onClick={() => setShowBulkActionsMenu(!showBulkActionsMenu)}\n className=\"flex items-center gap-2 px-3 py-2.5 bg-orange-600 text-white rounded-lg hover:bg-orange-700 transition-colors\"\n title=\"Bulk actions\"\n >\n <MoreHorizontal className=\"w-4 h-4\" />\n <span className=\"hidden sm:inline text-sm font-medium\">\n Actions ({selectedRowsCount})\n </span>\n </button>\n <Popover\n open={showBulkActionsMenu}\n anchorEl={bulkActionsAnchorRef.current}\n onClose={() => setShowBulkActionsMenu(false)}\n placement=\"bottom-end\"\n offset={8}\n zIndex={1000}\n className=\"w-56 bg-white border border-gray-200 rounded-lg shadow-xl\"\n >\n <div className=\"p-3 border-b border-gray-100\">\n <h3 className=\"font-medium text-gray-900\">Bulk Actions</h3>\n <p className=\"text-xs text-gray-500 mt-1\">\n {selectedRowsCount} row\n {selectedRowsCount !== 1 ? \"s\" : \"\"} selected\n </p>\n </div>\n <div className=\"p-2\">\n {bulkActions.map((action) => (\n <button\n key={action.id}\n onClick={() => handleBulkAction(action)}\n disabled={action.disabled}\n className={`w-full flex items-center gap-3 px-3 py-2 text-sm rounded-md transition-colors ${\n action.disabled\n ? \"text-gray-400 cursor-not-allowed\"\n : action.destructive\n ? \"text-red-700 hover:bg-red-50\"\n : \"text-gray-700 hover:bg-gray-50\"\n }`}\n >\n {getBulkActionIcon(action.id)}\n {action.label}\n </button>\n ))}\n </div>\n </Popover>\n </div>\n )}\n\n {/* Column Visibility Toggle */}\n {showColumnToggle && columns.length > 0 && (\n <div className=\"relative\" ref={columnMenuRef}>\n <button\n ref={(el) => {\n columnAnchorRef.current = el;\n }}\n onClick={() => setShowColumnMenu(!showColumnMenu)}\n className=\"flex items-center gap-2 px-3 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors\"\n title=\"Column visibility\"\n aria-label={`Column visibility. ${visibleColumnsCount} of ${columns.length} columns visible`}\n aria-haspopup=\"menu\"\n aria-expanded={showColumnMenu}\n aria-controls=\"column-visibility-menu\"\n >\n <Settings className=\"w-4 h-4\" />\n <span className=\"hidden sm:inline text-sm font-medium\">\n Columns\n </span>\n <span className=\"hidden sm:inline text-xs text-gray-500\">\n ({visibleColumnsCount}/{columns.length})\n </span>\n </button>\n\n {/* Column Visibility Dropdown */}\n <Popover\n open={showColumnMenu}\n anchorEl={columnAnchorRef.current}\n onClose={() => setShowColumnMenu(false)}\n placement=\"bottom-end\"\n offset={8}\n zIndex={1000}\n className=\"w-[90vw] sm:w-72 max-w-[90vw] bg-white border border-gray-200 rounded-lg shadow-xl\"\n >\n <div className=\"p-3 border-b border-gray-100\">\n <h3 className=\"font-medium text-gray-900\">\n Show/Hide Columns\n </h3>\n <div className=\"relative mt-2\">\n <Search className=\"absolute left-2 top-1/2 -translate-y-1/2 text-gray-400 w-4 h-4\" />\n <input\n type=\"text\"\n placeholder=\"Search columns...\"\n className=\"w-full pl-8 pr-2 py-1.5 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-sm\"\n value={columnSearch}\n onChange={(e) => setColumnSearch(e.target.value)}\n />\n </div>\n </div>\n <div className=\"max-h-60 overflow-y-auto p-2\">\n {filteredColumns.map((column) => {\n const isVisible = columnVisibility[column.key] !== false;\n return (\n <label\n key={column.key}\n className={`flex items-center gap-3 p-2 hover:bg-gray-50 rounded-md cursor-grab relative ${\n draggingKey === column.key ? \"opacity-60\" : \"\"\n }`}\n draggable\n onDragStart={(e) => handleDragStart(column.key, e)}\n onDragOver={(e) => handleDragOver(column.key, e)}\n onDrop={() => handleDrop(column.key)}\n onDragEnd={handleDragEnd}\n >\n {dragOver?.key === column.key && (\n <span\n className=\"absolute left-2 right-2 h-0.5 bg-blue-600\"\n style={{\n top:\n dragOver.position === \"before\"\n ? 0\n : undefined,\n bottom:\n dragOver.position === \"after\" ? 0 : undefined,\n }}\n />\n )}\n <input\n type=\"checkbox\"\n checked={isVisible}\n onChange={() => handleColumnToggle(column.key)}\n className=\"rounded border-gray-300 text-blue-600 focus:ring-blue-500\"\n />\n {isVisible ? (\n <Eye className=\"w-4 h-4 text-green-600\" />\n ) : (\n <EyeOff className=\"w-4 h-4 text-gray-400\" />\n )}\n <span className=\"text-sm text-gray-700\">\n {column.header}\n </span>\n <button\n type=\"button\"\n onClick={(e) => {\n e.preventDefault();\n e.stopPropagation();\n // Ensure column is visible before scrolling\n if (!isVisible) {\n onColumnVisibilityChange?.(column.key, true);\n // Wait for visibility update to render before scrolling\n requestAnimationFrame(() =>\n onScrollToColumn?.(column.key),\n );\n } else {\n onScrollToColumn?.(column.key);\n }\n }}\n className=\"ml-auto p-1 text-gray-400 hover:text-blue-600\"\n title=\"Scroll to this column\"\n aria-label={`Scroll to column ${column.header}`}\n >\n <LocateFixed className=\"w-4 h-4\" />\n </button>\n </label>\n );\n })}\n </div>\n <div className=\"p-2 border-t border-gray-100\">\n <div className=\"flex items-center justify-between\">\n <label className=\"flex items-center gap-2 text-sm text-gray-600 hover:text-gray-900 cursor-pointer hover:bg-gray-50 px-3 py-1.5 rounded transition-colors min-h-9\">\n <input\n type=\"checkbox\"\n checked={filteredColumns.every(\n (col) => columnVisibility[col.key] !== false,\n )}\n onChange={(e) => {\n filteredColumns.forEach((column) => {\n onColumnVisibilityChange?.(\n column.key,\n e.target.checked,\n );\n });\n }}\n className=\"rounded border-gray-300 text-blue-600 focus:ring-blue-500\"\n />\n <span>Select All</span>\n </label>\n <button\n className=\"text-sm text-gray-600 hover:text-gray-900 hover:bg-gray-50 px-3 py-1.5 rounded transition-colors min-h-9\"\n onClick={() => {\n handleResetColumns();\n setShowColumnMenu(false);\n }}\n >\n Reset Columns\n </button>\n </div>\n {columnSearch && (\n <button\n className=\"text-xs text-blue-600 hover:underline mt-2\"\n onClick={() => setColumnSearch(\"\")}\n >\n Clear Search\n </button>\n )}\n </div>\n </Popover>\n </div>\n )}\n\n {/* Density Selector */}\n {showDensityControl && (\n <div className=\"flex items-center\">\n <div\n className=\"flex items-center gap-1 border border-gray-300 rounded-lg p-1\"\n title=\"Row density\"\n >\n {([\"sm\", \"md\", \"lg\"] as Density[]).map((d) => (\n <button\n key={d}\n className={`px-2 py-1 text-xs rounded-md ${\n density === d\n ? \"bg-blue-600 text-white\"\n : \"text-gray-700 hover:bg-gray-100\"\n }`}\n onClick={() => onDensityChange?.(d)}\n >\n {d.toUpperCase()}\n </button>\n ))}\n </div>\n </div>\n )}\n\n {/* Enhanced Search Panel - Right aligned */}\n <div className=\"flex items-center gap-2 order-3 w-full sm:order-0 sm:w-auto flex-1 min-w-0\">\n {/* Search Input with integrated match type */}\n <div className=\"relative\">\n <Search\n className=\"absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4\"\n aria-hidden=\"true\"\n />\n <input\n ref={searchInputRef}\n type=\"text\"\n placeholder={`Search...`}\n className=\"w-full sm:w-64 pl-10 pr-10 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-800 dark:text-gray-200 transition-colors\"\n value={globalFilter}\n onChange={onGlobalFilterChange}\n aria-label=\"Search all columns\"\n aria-keyshortcuts=\"Control+F\"\n aria-describedby=\"search-results-status\"\n />\n {globalFilter && (\n <button\n onClick={() =>\n onGlobalFilterChange({\n target: { value: \"\" },\n } as ChangeEvent<HTMLInputElement>)\n }\n className=\"absolute right-2 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600 transition-colors\"\n title=\"Clear search\"\n >\n <X className=\"w-4 h-4\" />\n </button>\n )}\n </div>\n </div>\n\n {/* Export Icon Button */}\n {showExport && exportOptions?.enabled && (\n <div className=\"relative\" ref={exportMenuRef}>\n <button\n ref={(el) => {\n exportAnchorRef.current = el;\n }}\n onClick={() => setShowExportMenu(!showExportMenu)}\n className=\"p-2.5 cursor-pointer border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800 text-gray-700 dark:text-gray-300 transition-colors\"\n aria-label={`Export data${\n hasSelectedRows\n ? ` (${selectedRowsCount} rows selected)`\n : ` (${filteredDataLength} rows)`\n }`}\n aria-haspopup=\"menu\"\n aria-expanded={showExportMenu}\n aria-controls=\"export-menu\"\n aria-keyshortcuts=\"Control+E\"\n title=\"Export data (Ctrl+E)\"\n >\n <Download className=\"w-4 h-4\" />\n </button>\n <Popover\n open={showExportMenu}\n anchorEl={exportAnchorRef.current}\n onClose={() => setShowExportMenu(false)}\n placement=\"bottom-end\"\n offset={8}\n zIndex={1000}\n className=\"w-[90vw] sm:w-64 max-w-[90vw] bg-white border border-gray-200 rounded-lg shadow-xl\"\n >\n <div className=\"p-3 border-b border-gray-100\">\n <h3 className=\"font-medium text-gray-900\">Export Data</h3>\n <p className=\"text-xs text-gray-500 mt-1\">\n Choose format and data scope\n </p>\n </div>\n\n <div className=\"p-2\">\n {/* Export All */}\n <div className=\"mb-3\">\n <p className=\"text-xs font-medium text-gray-700 mb-2 px-2\">\n Export All Data\n </p>\n <div className=\"space-y-1\">\n {exportFormats.map((format) => (\n <button\n key={`all-${format}`}\n onClick={() => handleExport(format, false)}\n className=\" cursor-pointer w-full flex items-center gap-3 px-3 py-2 text-sm text-gray-700 hover:bg-gray-50 rounded-md transition-colors\"\n >\n {getExportIcon(format)}\n <span>Export as {getFormatLabel(format)}</span>\n <span className=\"ml-auto text-xs text-gray-500\">\n {filteredDataLength.toLocaleString()} rows\n </span>\n </button>\n ))}\n </div>\n </div>\n\n {/* Export Selected */}\n {hasSelectedRows && (\n <div>\n <p className=\"text-xs font-medium text-gray-700 mb-2 px-2\">\n Export Selected\n </p>\n <div className=\"space-y-1\">\n {exportFormats.map((format) => (\n <button\n key={`selected-${format}`}\n onClick={() => handleExport(format, true)}\n className=\"w-full flex items-center gap-3 px-3 py-2 text-sm text-blue-700 hover:bg-blue-50 rounded-md transition-colors\"\n >\n {getExportIcon(format)}\n <span>Export as {getFormatLabel(format)}</span>\n <span className=\"ml-auto text-xs text-blue-500\">\n {selectedRowsCount} rows\n </span>\n </button>\n ))}\n </div>\n </div>\n )}\n </div>\n </Popover>\n </div>\n )}\n </div>\n </div>\n </div>\n </div>\n );\n};\n\nSearchToolbarComponent.displayName = \"SearchToolbar\";\nexport const SearchToolbar = /*#__PURE__*/ memo(SearchToolbarComponent);\n","import {\n useState,\n useMemo,\n useCallback,\n useDeferredValue,\n useRef,\n useTransition,\n} from \"react\";\nimport {\n GridRow,\n GridColumn,\n ActiveFilters,\n ColumnFilterValue,\n} from \"../types\";\n\ninterface UseAdvancedFilteringProps {\n data: GridRow[];\n columns: GridColumn[];\n}\n\nexport const useAdvancedFiltering = ({\n data,\n columns,\n}: UseAdvancedFilteringProps) => {\n const [globalFilterState, setGlobalFilterState] = useState<string>(\"\");\n const [columnFilters, setColumnFilters] = useState<ActiveFilters>({});\n\n const [isFilterPending, startFilterTransition] = useTransition();\n const [, startColumnFilterTransition] = useTransition();\n\n // Public setter wraps update in a transition so the input field never lags\n const setGlobalFilter = useCallback((value: string) => {\n startFilterTransition(() => setGlobalFilterState(value));\n }, []);\n\n const deferredGlobalFilter = useDeferredValue(globalFilterState);\n\n const applyColumnFilter = useCallback(\n (\n row: GridRow,\n columnKey: string,\n filter: ColumnFilterValue,\n precomputed?: { filterTs?: number; secondTs?: number },\n ): boolean => {\n const value = row[columnKey];\n\n switch (filter.type) {\n case \"text\": {\n const textValue = String(value || \"\").toLowerCase();\n const filterText = String(filter.value || \"\").toLowerCase();\n switch (filter.operator) {\n case \"contains\":\n return textValue.includes(filterText);\n case \"equals\":\n return textValue === filterText;\n case \"startsWith\":\n return textValue.startsWith(filterText);\n case \"endsWith\":\n return textValue.endsWith(filterText);\n default:\n return textValue.includes(filterText);\n }\n }\n case \"number\": {\n const numValue = parseFloat(value);\n const filterNum = parseFloat(String(filter.value));\n if (isNaN(numValue) || isNaN(filterNum)) return false;\n switch (filter.operator) {\n case \"equals\":\n return numValue === filterNum;\n case \"gt\":\n return numValue > filterNum;\n case \"gte\":\n return numValue >= filterNum;\n case \"lt\":\n return numValue < filterNum;\n case \"lte\":\n return numValue <= filterNum;\n case \"between\": {\n const secondNum = parseFloat(String(filter.secondValue ?? \"\"));\n return (\n !isNaN(secondNum) &&\n numValue >= filterNum &&\n numValue <= secondNum\n );\n }\n default:\n return numValue === filterNum;\n }\n }\n case \"date\": {\n // Use pre-parsed timestamps when available (avoids O(n) Date allocations)\n const filterTs = precomputed?.filterTs;\n const secondTs = precomputed?.secondTs;\n if (filterTs === undefined || isNaN(filterTs)) return false;\n\n const raw = new Date(value);\n if (isNaN(raw.getTime())) return false;\n const rowTs = new Date(\n raw.getFullYear(),\n raw.getMonth(),\n raw.getDate(),\n ).getTime();\n\n switch (filter.operator) {\n case \"equals\":\n return rowTs === filterTs;\n case \"gt\":\n return rowTs > filterTs;\n case \"gte\":\n return rowTs >= filterTs;\n case \"lt\":\n return rowTs < filterTs;\n case \"lte\":\n return rowTs <= filterTs;\n case \"between\":\n return (\n secondTs !== undefined &&\n !isNaN(secondTs) &&\n rowTs >= filterTs &&\n rowTs <= secondTs\n );\n default:\n return rowTs === filterTs;\n }\n }\n case \"boolean\":\n return Boolean(value) === Boolean(filter.value);\n\n case \"multiselect\": {\n const filterValues = Array.isArray(filter.value)\n ? filter.value\n : [filter.value];\n const normalizeBlank = (val: any) =>\n val === null ||\n val === undefined ||\n val === \"\" ||\n (typeof val === \"string\" && val.trim() === \"\")\n ? null\n : val;\n return filterValues\n .map(normalizeBlank)\n .includes(normalizeBlank(value));\n }\n default:\n return true;\n }\n },\n [],\n );\n\n // Optimized search cache with size limits for large datasets\n const rowSearchCacheRef = useRef<WeakMap<GridRow, string>>(new WeakMap());\n const cacheSizeRef = useRef(0);\n const maxCacheSize = 5000;\n\n const clearCacheIfNeeded = useCallback(() => {\n if (cacheSizeRef.current > maxCacheSize) {\n rowSearchCacheRef.current = new WeakMap();\n cacheSizeRef.current = 0;\n }\n }, []);\n\n const filteredData = useMemo(() => {\n clearCacheIfNeeded();\n\n const hasColumnFilters = Object.keys(columnFilters).length > 0;\n const hasGlobal = !!deferredGlobalFilter;\n if (!hasColumnFilters && !hasGlobal) return data;\n\n const lowerGlobal = deferredGlobalFilter.toLowerCase();\n const cache = rowSearchCacheRef.current!;\n let working = data;\n\n // Apply column filters first (usually more selective).\n // For date filters: pre-parse the filter timestamps ONCE here so that\n // applyColumnFilter doesn't create new Date() objects per row (O(n) allocs).\n if (hasColumnFilters) {\n for (const [columnKey, filter] of Object.entries(columnFilters)) {\n if (!filter) continue;\n\n // Pre-compute date timestamps for date-type filters\n let precomputed: { filterTs?: number; secondTs?: number } | undefined;\n if (filter.type === \"date\") {\n const fd =\n filter.value instanceof Date\n ? filter.value\n : new Date(String(filter.value ?? \"\"));\n const filterTs = isNaN(fd.getTime())\n ? NaN\n : new Date(fd.getFullYear(), fd.getMonth(), fd.getDate()).getTime();\n let secondTs: number | undefined;\n if (filter.secondValue) {\n const sd =\n filter.secondValue instanceof Date\n ? filter.secondValue\n : new Date(String(filter.secondValue ?? \"\"));\n secondTs = isNaN(sd.getTime())\n ? NaN\n : new Date(\n sd.getFullYear(),\n sd.getMonth(),\n sd.getDate(),\n ).getTime();\n }\n precomputed = { filterTs, secondTs };\n }\n\n working = working.filter((row) =>\n applyColumnFilter(row, columnKey, filter, precomputed),\n );\n if (working.length === 0) break;\n }\n }\n\n // Apply global filter with cache\n if (hasGlobal && working.length > 0) {\n const visibleColumns = columns.filter((col) => col.visible !== false);\n working = working.filter((row) => {\n let packed = cache.get(row);\n if (packed == null) {\n packed = visibleColumns\n .map((c) => {\n const v = row[c.key];\n if (v == null) return \"\";\n if (typeof v === \"string\") return v.toLowerCase();\n if (typeof v === \"number\" || typeof v === \"boolean\")\n return String(v).toLowerCase();\n const s = String(v);\n return s.length > 100 ? s.slice(0, 100) : s;\n })\n .join(\"|\");\n if (cacheSizeRef.current < maxCacheSize) {\n cache.set(row, packed);\n cacheSizeRef.current++;\n }\n }\n return packed.includes(lowerGlobal);\n });\n }\n\n return working;\n }, [\n data,\n columnFilters,\n deferredGlobalFilter,\n columns,\n applyColumnFilter,\n clearCacheIfNeeded,\n ]);\n\n const setColumnFilter = useCallback(\n (columnKey: string, filter: ColumnFilterValue | null) => {\n // Column filter changes also go through a transition so the grid stays\n // responsive while the filter dropdown is still open\n startColumnFilterTransition(() => {\n setColumnFilters((prev) => {\n const next = { ...prev };\n if (filter) {\n next[columnKey] = filter;\n } else {\n delete next[columnKey];\n }\n return next;\n });\n });\n },\n [],\n );\n\n const clearColumnFilter = useCallback(\n (columnKey: string) => {\n setColumnFilter(columnKey, null);\n },\n [setColumnFilter],\n );\n\n const clearAllFilters = useCallback(() => {\n startFilterTransition(() => setGlobalFilterState(\"\"));\n startColumnFilterTransition(() => setColumnFilters({}));\n rowSearchCacheRef.current = new WeakMap();\n cacheSizeRef.current = 0;\n }, []);\n\n const getActiveFilterCount = useCallback(() => {\n let count = 0;\n if (deferredGlobalFilter) count++;\n return count + Object.keys(columnFilters).length;\n }, [deferredGlobalFilter, columnFilters]);\n\n return {\n globalFilter: globalFilterState,\n setGlobalFilter,\n columnFilters,\n filteredData,\n setColumnFilter,\n clearColumnFilter,\n clearAllFilters,\n getActiveFilterCount,\n /** True while a filter transition is in-flight — use to show a loading indicator */\n isFilterPending,\n };\n};\n","import { useCallback, useEffect, useRef } from \"react\";\n\ntype SortCfg = { key: string; direction: \"asc\" | \"desc\" } | null;\n\n/**\n * Inline worker factory — serialised to a Blob so no external .ts file is\n * referenced at runtime. Avoids the \"Could not resolve entry module\" error\n * that occurs when downstream bundlers follow new URL(..., import.meta.url)\n * from a published npm package.\n */\nfunction workerFactory() {\n const ctx = self as any;\n\n const processData = (\n rows: any[],\n sort?: { key: string; direction: \"asc\" | \"desc\" } | null,\n ) => {\n if (!rows || rows.length === 0) return rows;\n if (!sort?.key) return rows;\n const { key, direction } = sort;\n const dir = direction === \"asc\" ? 1 : -1;\n return [...rows].sort((a, b) => {\n const av = a?.[key];\n const bv = b?.[key];\n if (av == null && bv == null) return 0;\n if (av == null) return -1 * dir;\n if (bv == null) return 1 * dir;\n if (typeof av === \"number\" && typeof bv === \"number\")\n return (av - bv) * dir;\n return String(av).localeCompare(String(bv)) * dir;\n });\n };\n\n ctx.onmessage = (e: MessageEvent) => {\n const msg = e.data;\n if (!msg || msg.type !== \"process\") return;\n try {\n const { rows, sort } = msg.payload;\n ctx.postMessage({\n type: \"result\",\n payload: { rows: processData(rows, sort ?? null) },\n });\n } catch {\n ctx.postMessage({\n type: \"result\",\n payload: { rows: msg.payload?.rows ?? [] },\n });\n }\n };\n}\n\n/** Lazily-created worker singleton per hook instance. */\nexport function useDataWorker(options?: { enabled?: boolean }) {\n const enabled = options?.enabled ?? true;\n const workerRef = useRef<Worker | null>(null);\n /** Holds both the resolve AND reject so we can cancel in-flight calls. */\n const resolverRef = useRef<{\n resolve: (rows: any[]) => void;\n reject: (reason?: any) => void;\n } | null>(null);\n const enabledRef = useRef(enabled);\n\n // Keep enabledRef in sync without affecting process() identity\n useEffect(() => {\n enabledRef.current = enabled;\n // If disabled after being enabled, terminate any live worker\n if (!enabled && workerRef.current) {\n workerRef.current.terminate();\n workerRef.current = null;\n if (resolverRef.current) {\n resolverRef.current.reject(\n new DOMException(\"Worker disabled\", \"AbortError\"),\n );\n resolverRef.current = null;\n }\n }\n }, [enabled]);\n\n /**\n * ensureWorker is kept in a ref so that `process` below never needs it in\n * its dependency array — giving `process` a permanently stable identity.\n * Without this, every time `useCallback` re-creates ensureWorker (e.g. when\n * `enabled` changes), `process` also gets a new reference, which triggers\n * the sort useEffect in DataGrid.tsx and causes an unnecessary re-sort.\n */\n const ensureWorkerRef = useRef<() => Worker | null>(() => null);\n\n ensureWorkerRef.current = () => {\n if (!enabledRef.current) return null;\n if (workerRef.current) return workerRef.current;\n\n const code = `(${workerFactory.toString()})()`;\n const blob = new Blob([code], { type: \"application/javascript\" });\n const blobUrl = URL.createObjectURL(blob);\n const w = new Worker(blobUrl);\n // Revoke immediately — browser has already parsed the script at this point.\n // The Worker thread holds its own internal reference, so this is safe and\n // prevents the object URL from leaking until the tab is closed.\n URL.revokeObjectURL(blobUrl);\n\n w.onmessage = (e: MessageEvent) => {\n if (e.data?.type === \"result\") {\n resolverRef.current?.resolve(e.data.payload.rows);\n resolverRef.current = null;\n }\n };\n\n workerRef.current = w;\n return w;\n };\n\n useEffect(() => {\n return () => {\n workerRef.current?.terminate();\n workerRef.current = null;\n if (resolverRef.current) {\n resolverRef.current.reject(new DOMException(\"Unmounted\", \"AbortError\"));\n resolverRef.current = null;\n }\n };\n }, []);\n\n /**\n * `process` has an EMPTY dependency array — it is stable for the entire\n * lifetime of the component. This means the sort useEffect in DataGrid.tsx\n * (which lists `workerProcess` as a dep) will NEVER fire due to a changed\n * process identity — only when the data/sort config actually changes.\n */\n const process = useCallback(\n (rows: any[], sort: SortCfg): Promise<any[]> => {\n if (!enabledRef.current) return Promise.resolve(rows);\n\n const w = ensureWorkerRef.current();\n if (!w) return Promise.resolve(rows);\n\n return new Promise<any[]>((resolve, reject) => {\n // Cancel any in-flight call — its promise is rejected with AbortError\n // so the caller can safely ignore it (e.g. .catch(() => {}) or check error.name)\n if (resolverRef.current) {\n resolverRef.current.reject(\n new DOMException(\"Superseded by newer sort\", \"AbortError\"),\n );\n }\n resolverRef.current = { resolve, reject };\n w.postMessage({ type: \"process\", payload: { rows, sort } });\n });\n },\n [], // ← stable forever: reads enabled via ref, worker via ref\n );\n\n return { process };\n}\n","import { useCallback } from \"react\";\nimport { GridRow, GridColumn, ExportFormat } from \"../types\";\n\ninterface UseExportProps {\n data: GridRow[];\n columns: GridColumn[];\n selectedRows?: Set<string | number>;\n filename?: string;\n columnVisibility?: Record<string, boolean>;\n}\n\nexport const useExport = ({\n data,\n columns,\n selectedRows,\n filename = \"data\",\n columnVisibility,\n}: UseExportProps) => {\n // Filter only visible columns (computed inline — no extra state)\n const getVisibleColumns = useCallback(\n () =>\n columnVisibility\n ? columns.filter((col) => columnVisibility[col.key] !== false)\n : columns,\n [columns, columnVisibility],\n );\n\n const downloadFile = useCallback(\n (content: string, fileName: string, mimeType: string) => {\n const blob = new Blob([content], { type: mimeType });\n const url = URL.createObjectURL(blob);\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = fileName;\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n URL.revokeObjectURL(url);\n },\n [],\n );\n\n const exportToCSV = useCallback(\n (exportData: GridRow[], exportFilename: string) => {\n const visibleColumns = getVisibleColumns();\n const headers = visibleColumns.map((col) => col.header).join(\",\");\n const rows = exportData.map((row) =>\n visibleColumns\n .map((col) => {\n const value = row[col.key];\n const s = String(value ?? \"\");\n return s.includes(\",\") || s.includes('\"')\n ? `\"${s.replace(/\"/g, '\"\"')}\"`\n : s;\n })\n .join(\",\"),\n );\n downloadFile(\n [headers, ...rows].join(\"\\n\"),\n `${exportFilename}.csv`,\n \"text/csv\",\n );\n },\n [getVisibleColumns, downloadFile],\n );\n\n const exportToJSON = useCallback(\n (exportData: GridRow[], exportFilename: string) => {\n const visibleColumns = getVisibleColumns();\n const jsonData = exportData.map((row) => {\n const out: Record<string, any> = {};\n for (const col of visibleColumns) out[col.header] = row[col.key];\n return out;\n });\n downloadFile(\n JSON.stringify(jsonData, null, 2),\n `${exportFilename}.json`,\n \"application/json\",\n );\n },\n [getVisibleColumns, downloadFile],\n );\n\n /**\n * XLSX export uses dynamic imports so that ExcelJS (~600 KB) and file-saver\n * are NEVER included in the initial bundle. They are only fetched when the\n * user actually requests an xlsx export.\n */\n const exportToXLSX = useCallback(\n async (exportData: GridRow[], exportFilename: string) => {\n const visibleColumns = getVisibleColumns();\n\n // Lazy-load heavy dependencies — won't appear in the main bundle\n const [{ default: ExcelJS }, { saveAs }] = await Promise.all([\n import(\"exceljs\"),\n import(\"file-saver\"),\n ]);\n\n const workbook = new ExcelJS.Workbook();\n const sheet = workbook.addWorksheet(\"Data\");\n\n const SAMPLE_COUNT = 50;\n const sampled = exportData.slice(0, SAMPLE_COUNT);\n\n const coerceValue = (v: any) => {\n if (v == null) return \"\";\n if (\n typeof v === \"number\" ||\n typeof v === \"boolean\" ||\n v instanceof Date\n )\n return v;\n const s = String(v);\n if (/[a-zA-Z]/.test(s)) return s;\n if (/^-?[\\d,]+\\.?\\d*$/.test(s.trim())) {\n const n = Number(s.replace(/,/g, \"\"));\n if (Number.isFinite(n)) return n;\n }\n return s;\n };\n\n sheet.columns = visibleColumns.map((col) => {\n const header = col.header || col.key;\n let maxLen = header?.length || 10;\n for (const row of sampled) {\n const s = row[col.key] == null ? \"\" : String(row[col.key]);\n if (s.length > maxLen) maxLen = s.length;\n }\n return {\n header,\n key: col.key,\n width: Math.max(8, Math.min(50, Math.ceil(maxLen * 1.1))),\n };\n });\n\n for (const row of exportData) {\n const obj: Record<string, any> = {};\n for (const col of visibleColumns)\n obj[col.key] = coerceValue(row[col.key]);\n sheet.addRow(obj);\n }\n\n const headerRow = sheet.getRow(1);\n headerRow.font = { bold: true };\n sheet.autoFilter = {\n from: { row: 1, column: 1 },\n to: { row: Math.max(1, sheet.rowCount), column: visibleColumns.length },\n };\n\n const buffer = await workbook.xlsx.writeBuffer();\n saveAs(\n new Blob([buffer], {\n type: \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\",\n }),\n `${exportFilename}.xlsx`,\n );\n },\n [getVisibleColumns],\n );\n\n const exportData = useCallback(\n (format: ExportFormat, exportSelected = false) => {\n const rows =\n exportSelected && selectedRows && selectedRows.size > 0\n ? data.filter((row) => selectedRows.has(row.id))\n : data;\n\n const name =\n exportSelected && selectedRows && selectedRows.size > 0\n ? `${filename}_selected_${selectedRows.size}_rows`\n : filename;\n\n switch (format) {\n case \"csv\":\n exportToCSV(rows, name);\n break;\n case \"json\":\n exportToJSON(rows, name);\n break;\n case \"xlsx\":\n void exportToXLSX(rows, name);\n break;\n default:\n console.warn(`[KDGrid] Unsupported export format: ${format}`);\n }\n },\n [data, selectedRows, filename, exportToCSV, exportToJSON, exportToXLSX],\n );\n\n return {\n exportData,\n canExportSelected: !!(selectedRows && selectedRows.size > 0),\n selectedCount: selectedRows?.size ?? 0,\n };\n};\n","import { useState, useMemo, useEffect } from \"react\";\nimport { GridRow, GroupConfig, GridColumn } from \"../types\";\n\ninterface UseGroupingProps {\n data: GridRow[];\n columns: GridColumn[];\n}\n\nconst UNKNOWN = \"Unknown\";\nconst buildPath = (parts: string[]) => parts.join(\"|\");\n\n/**\n * Shared utility — walks the grouped tree and collects every group path into `acc`.\n * Used by: auto-expand useEffect, expandAllGroups.\n */\nconst gatherGroupPaths = (\n rows: GridRow[],\n keys: string[],\n level: number,\n parts: string[],\n acc: Set<string>,\n): void => {\n const colKey = keys[level];\n const map = new Map<string, GridRow[]>();\n for (const r of rows) {\n const str = String((r as any)[colKey] ?? UNKNOWN);\n const arr = map.get(str);\n if (arr) arr.push(r);\n else map.set(str, [r]);\n }\n for (const [value, groupRows] of map.entries()) {\n const seg = `${colKey}=${value}`;\n const next = [...parts, seg];\n acc.add(buildPath(next));\n if (level < keys.length - 1) gatherGroupPaths(groupRows, keys, level + 1, next, acc);\n }\n};\n\n/**\n * Module-level aggregate computation — extracted from inside displayData useMemo\n * so it is not redeclared on every evaluation. `columns` is now passed explicitly,\n * which also means it can be listed as a proper useMemo dependency.\n */\nconst computeAggregates = (rows: GridRow[], columns: GridColumn[]): Record<string, any> => {\n const result: Record<string, any> = {};\n for (const col of columns) {\n if (!col.aggregate) continue;\n const values = rows.map((r) => (r as any)[col.key]);\n let aggVal: any = null;\n if (typeof col.aggregate === \"function\") {\n try {\n aggVal = col.aggregate(values);\n } catch (_) {\n aggVal = null;\n }\n } else {\n const isDateLike = (s: string) => {\n if (/^\\d{4}-\\d{2}-\\d{2}$/.test(s)) return true;\n if (/^\\d{2}-\\d{2}-\\d{4}$/.test(s)) return true;\n if (/^\\d{4}\\/\\d{2}\\/\\d{2}$/.test(s)) return true;\n if (/^\\d{2}\\/\\d{2}\\/\\d{4}$/.test(s)) return true;\n if ((s.includes(\"-\") || s.includes(\"/\")) && Number.isFinite(Date.parse(s))) return true;\n return false;\n };\n const nums = values\n .map((v) => {\n if (typeof v === \"number\") return v;\n if (v == null) return NaN;\n const sv = String(v);\n if (isDateLike(sv)) return NaN;\n const n = parseFloat(sv.replace(/,/g, \"\"));\n return Number.isFinite(n) ? n : NaN;\n })\n .filter((n) => Number.isFinite(n)) as number[];\n const tryDateNumbers = () =>\n values\n .map((v) => {\n if (v instanceof Date) return v.getTime();\n if (typeof v === \"string\" || typeof v === \"number\") {\n const t = Date.parse(String(v));\n return Number.isFinite(t) ? t : NaN;\n }\n return NaN;\n })\n .filter((t) => Number.isFinite(t)) as number[];\n\n if (col.aggregate === \"sum\" || col.aggregate === \"avg\") {\n if (nums.length) {\n aggVal = col.aggregate === \"sum\"\n ? nums.reduce((a, b) => a + b, 0)\n : nums.reduce((a, b) => a + b, 0) / nums.length;\n }\n } else if (col.aggregate === \"min\" || col.aggregate === \"max\") {\n if (nums.length) {\n aggVal = col.aggregate === \"min\" ? Math.min(...nums) : Math.max(...nums);\n } else {\n const dateNums = tryDateNumbers();\n if (dateNums.length) {\n const picked = col.aggregate === \"min\" ? Math.min(...dateNums) : Math.max(...dateNums);\n aggVal = new Date(picked);\n }\n }\n }\n }\n if (aggVal !== null && aggVal !== undefined) {\n result[col.key] = aggVal;\n }\n }\n return result;\n};\n\nexport const useGrouping = ({ data, columns }: UseGroupingProps) => {\n const [groupConfig, setGroupConfig] = useState<GroupConfig>({\n columnKeys: [],\n expanded: new Set<string>(),\n });\n\n type FlatRow = GridRow & {\n _isGroupHeader?: boolean;\n _groupKey?: string;\n _groupCount?: number;\n _groupLevel?: number;\n _groupColumnKey?: string;\n _groupValue?: string;\n _groupRows?: GridRow[];\n _isGroupFooter?: boolean;\n _groupAgg?: Record<string, any>;\n };\n\n // Build flattened rows with nested group headers based on columnKeys.\n // `columns` is listed as a dep so that aggregate function changes are picked up.\n const displayData = useMemo<FlatRow[]>(() => {\n const keys = groupConfig.columnKeys;\n if (!keys.length) return data as FlatRow[];\n\n const flat: FlatRow[] = [];\n\n const recurse = (rows: GridRow[], level: number, pathParts: string[]) => {\n const colKey = keys[level];\n const map = new Map<string, GridRow[]>();\n for (const r of rows) {\n const str = String((r as any)[colKey] ?? UNKNOWN);\n const arr = map.get(str);\n if (arr) arr.push(r);\n else map.set(str, [r]);\n }\n const entries = Array.from(map.entries()).sort(([a], [b]) => a.localeCompare(b));\n for (const [value, groupRows] of entries) {\n const seg = `${colKey}=${value}`;\n const nextPath = [...pathParts, seg];\n const pathStr = buildPath(nextPath);\n flat.push({\n id: `group-${pathStr}`,\n _isGroupHeader: true,\n _groupKey: pathStr,\n _groupCount: groupRows.length,\n _groupLevel: level,\n _groupColumnKey: colKey,\n _groupValue: value,\n _groupRows: groupRows,\n } as FlatRow);\n\n const isExpanded = groupConfig.expanded.has(pathStr);\n if (!isExpanded) continue;\n if (level < keys.length - 1) {\n recurse(groupRows, level + 1, nextPath);\n } else {\n for (const r of groupRows) flat.push(r);\n }\n\n // Append footer with aggregates for this group\n const agg = computeAggregates(groupRows, columns);\n flat.push({\n id: `group-footer-${pathStr}`,\n _isGroupFooter: true,\n _groupKey: pathStr,\n _groupLevel: level,\n _groupAgg: agg,\n } as FlatRow);\n }\n };\n\n recurse(data, 0, []);\n return flat;\n }, [data, columns, groupConfig.columnKeys, groupConfig.expanded]);\n\n // Always keep groups expanded by default when grouping is active.\n useEffect(() => {\n if (!groupConfig.columnKeys.length) return;\n const allPaths = new Set<string>();\n gatherGroupPaths(data, groupConfig.columnKeys, 0, [], allPaths);\n let differs = false;\n if (allPaths.size !== groupConfig.expanded.size) differs = true;\n else {\n for (const p of allPaths)\n if (!groupConfig.expanded.has(p)) { differs = true; break; }\n }\n if (differs) setGroupConfig((prev) => ({ ...prev, expanded: allPaths }));\n }, [groupConfig.columnKeys, data]);\n\n const handleGroupBy = (columnKey: string | null) => {\n setGroupConfig({ columnKeys: columnKey ? [columnKey] : [], expanded: new Set() });\n };\n\n const addGroupKey = (columnKey: string) => {\n setGroupConfig((prev) =>\n prev.columnKeys.includes(columnKey)\n ? prev\n : { ...prev, columnKeys: [...prev.columnKeys, columnKey] },\n );\n };\n\n const removeGroupKey = (columnKey: string) => {\n setGroupConfig((prev) => {\n const nextKeys = prev.columnKeys.filter((k) => k !== columnKey);\n const nextExpanded = new Set<string>();\n for (const p of prev.expanded)\n if (!p.includes(`${columnKey}=`)) nextExpanded.add(p);\n return { columnKeys: nextKeys, expanded: nextExpanded };\n });\n };\n\n const setGroupKeys = (columnKeys: string[]) => {\n setGroupConfig({ columnKeys: [...columnKeys], expanded: new Set() });\n };\n\n const toggleGroupExpansion = (groupPath: string) => {\n setGroupConfig((prev) => {\n const next = new Set(prev.expanded);\n if (next.has(groupPath)) next.delete(groupPath);\n else next.add(groupPath);\n return { ...prev, expanded: next };\n });\n };\n\n const expandAllGroups = () => {\n const keys = groupConfig.columnKeys;\n if (!keys.length) return;\n const acc = new Set<string>();\n gatherGroupPaths(data, keys, 0, [], acc);\n setGroupConfig((prev) => ({ ...prev, expanded: acc }));\n };\n\n const collapseAllGroups = () => {\n setGroupConfig((prev) => ({ ...prev, expanded: new Set<string>() }));\n };\n\n return {\n groupConfig,\n displayData,\n handleGroupBy,\n addGroupKey,\n removeGroupKey,\n setGroupKeys,\n toggleGroupExpansion,\n expandAllGroups,\n collapseAllGroups,\n isGrouped: groupConfig.columnKeys.length > 0,\n };\n};\n","import { useState, useMemo, useCallback, useEffect } from \"react\";\nimport { PaginationConfig, GridRow } from \"../types\";\n\ninterface UsePaginationProps {\n data: GridRow[];\n pagination?: {\n enabled?: boolean;\n mode?: \"client\" | \"server\";\n pageSize?: number;\n showPageSizeSelector?: boolean;\n pageSizeOptions?: number[];\n serverConfig?: {\n enabled: boolean;\n onPageChange: (page: number, pageSize: number) => Promise<void> | void;\n onPageSizeChange?: (pageSize: number) => Promise<void> | void;\n loading?: boolean;\n totalRows: number;\n };\n };\n}\n\nexport const usePagination = ({ data, pagination }: UsePaginationProps) => {\n const [currentPage, setCurrentPage] = useState(1);\n const [pageSize, setPageSize] = useState(pagination?.pageSize || 50);\n const [isServerLoading, setIsServerLoading] = useState(false);\n\n // Sync pageSize when the prop changes externally (e.g. user preferences loaded async).\n // Reset to page 1 to avoid an out-of-bounds page after the resize.\n useEffect(() => {\n const next = pagination?.pageSize;\n if (next && next !== pageSize) {\n setPageSize(next);\n setCurrentPage(1);\n }\n // We intentionally only track pagination?.pageSize, not pageSize itself\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [pagination?.pageSize]);\n\n const resetPage = useCallback(() => {\n setCurrentPage(1);\n }, []);\n\n const paginationConfig: PaginationConfig = useMemo(() => {\n const isEnabled = pagination?.enabled !== false;\n const mode = pagination?.mode || \"client\";\n const totalRows =\n mode === \"server\"\n ? pagination?.serverConfig?.totalRows || 0\n : data.length;\n const totalPages = Math.ceil(totalRows / pageSize);\n\n return {\n enabled: isEnabled,\n pageSize,\n currentPage,\n totalPages,\n totalRows,\n showPageSizeSelector: pagination?.showPageSizeSelector !== false,\n pageSizeOptions: pagination?.pageSizeOptions || [25, 50, 100, 200, 500],\n };\n }, [pagination, pageSize, currentPage, data.length]);\n\n const paginatedData = useMemo(() => {\n if (!paginationConfig.enabled || pagination?.mode === \"server\") {\n return data;\n }\n\n const startIndex = (currentPage - 1) * pageSize;\n const endIndex = startIndex + pageSize;\n return data.slice(startIndex, endIndex);\n }, [data, currentPage, pageSize, paginationConfig.enabled, pagination?.mode]);\n\n const handlePageChange = useCallback(\n async (page: number) => {\n if (\n pagination?.mode === \"server\" &&\n pagination?.serverConfig?.onPageChange\n ) {\n setIsServerLoading(true);\n try {\n await pagination.serverConfig.onPageChange(page, pageSize);\n } finally {\n setIsServerLoading(false);\n }\n }\n setCurrentPage(page);\n },\n [pagination, pageSize],\n );\n\n const handlePageSizeChange = useCallback(\n async (newPageSize: number) => {\n if (\n pagination?.mode === \"server\" &&\n pagination?.serverConfig?.onPageSizeChange\n ) {\n setIsServerLoading(true);\n try {\n await pagination.serverConfig.onPageSizeChange(newPageSize);\n } finally {\n setIsServerLoading(false);\n }\n }\n setPageSize(newPageSize);\n setCurrentPage(1);\n },\n [pagination],\n );\n\n return {\n currentPage,\n resetPage,\n paginationConfig,\n paginatedData,\n isServerLoading,\n handlePageChange,\n handlePageSizeChange,\n };\n};\n","import { useState, useCallback, useEffect, useMemo } from \"react\";\nimport { GridRow } from \"../types\";\n\ninterface UseSelectionProps {\n data: GridRow[];\n selectedRowIds?: Iterable<string | number> | null;\n onRowSelect?: (row: GridRow) => void;\n getRowId?: (row: GridRow) => string | number;\n}\n\nconst areSetsEqual = (a: Set<string | number>, b: Set<string | number>) => {\n if (a.size !== b.size) return false;\n for (const value of a) {\n if (!b.has(value)) return false;\n }\n return true;\n};\n\nexport const useSelection = ({\n data,\n selectedRowIds,\n onRowSelect,\n getRowId,\n}: UseSelectionProps) => {\n // Extract row IDs based on getRowId or fallback to row.id\n const extractRowId = useCallback(\n (row: GridRow, rowIndex?: number): string | number => {\n if (getRowId) {\n return getRowId(row);\n }\n if (row.id !== undefined) {\n return row.id;\n }\n // Fallback: use row index\n if (process.env.NODE_ENV === \"development\" && rowIndex === 0) {\n console.warn(\n \"[KDGrid] No row IDs found. Either:\\n\" +\n \" 1. Add 'id' property to each row object, or\\n\" +\n \" 2. Provide 'getRowId' prop to extract a unique identifier.\\n\" +\n \" Using row index as fallback ID, but this may cause issues with pagination/filtering.\",\n );\n }\n return rowIndex ?? 0;\n },\n [getRowId],\n );\n\n const [selectedRows, setSelectedRows] = useState<Set<string | number>>(\n () => new Set(selectedRowIds ? Array.from(selectedRowIds) : []),\n );\n\n // Sync with external selectedRowIds prop\n useEffect(() => {\n if (!selectedRowIds) return;\n setSelectedRows((prev) => {\n const next = new Set(Array.from(selectedRowIds));\n if (areSetsEqual(prev, next)) return prev;\n return next;\n });\n }, [selectedRowIds]);\n\n // Pre-build rowId → row map for O(1) lookup in handleRowSelect.\n // Replaces per-click data.find() which was O(n) — painful at 100K rows.\n const rowByIdMap = useMemo(() => {\n const m = new Map<string | number, GridRow>();\n data.forEach((row, idx) => m.set(extractRowId(row, idx), row));\n return m;\n }, [data, extractRowId]);\n\n // Prune selected IDs that no longer exist in data (e.g. after filtering).\n // Guards with early-exit conditions to avoid the expensive Set rebuild on\n // every filter keypress when the selection is unchanged.\n useEffect(() => {\n if (selectedRows.size === 0) return; // nothing selected — nothing to prune\n\n // Check if any selected ID would be invalid — only then build the full Set\n let needsPrune = false;\n for (const id of selectedRows) {\n if (!rowByIdMap.has(id)) {\n needsPrune = true;\n break;\n }\n }\n if (!needsPrune) return;\n\n setSelectedRows((prev) => {\n const next = new Set<string | number>();\n prev.forEach((id) => {\n if (rowByIdMap.has(id)) next.add(id);\n });\n if (areSetsEqual(prev, next)) return prev;\n return next;\n });\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [rowByIdMap]);\n\n const handleRowSelect = useCallback(\n (rowId: string | number, isSelected: boolean) => {\n setSelectedRows((prev) => {\n const newSet = new Set(prev);\n if (isSelected) {\n newSet.add(rowId);\n } else {\n newSet.delete(rowId);\n }\n return newSet;\n });\n\n if (onRowSelect) {\n // O(1) lookup via the pre-built Map instead of O(n) data.find()\n const row = rowByIdMap.get(rowId);\n if (row) onRowSelect(row);\n }\n },\n [rowByIdMap, onRowSelect],\n );\n\n const handleSelectAll = useCallback(\n (isSelected: boolean) => {\n if (isSelected) {\n setSelectedRows(\n new Set(data.map((row, idx) => extractRowId(row, idx))),\n );\n } else {\n setSelectedRows(new Set());\n }\n },\n [data, extractRowId],\n );\n\n return {\n selectedRows,\n handleRowSelect,\n handleSelectAll,\n };\n};\n","import {\n useState,\n useMemo,\n useCallback,\n useEffect,\n useRef,\n UIEvent,\n} from \"react\";\nimport { VirtualizedRange, GridRow } from \"../types\";\n\ninterface UseVirtualizationProps {\n data: GridRow[];\n virtualized?: boolean;\n rowHeight?: number;\n overscan?: number;\n height: number;\n}\n\nexport const useVirtualization = ({\n data,\n virtualized = true,\n rowHeight = 40,\n overscan = 10,\n height,\n}: UseVirtualizationProps) => {\n const scrollRef = useRef<HTMLDivElement>(null);\n const [scrollTop, setScrollTop] = useState(0);\n const rafIdRef = useRef<number | null>(null);\n const pendingScrollTopRef = useRef<number>(0);\n // Initialise from the prop; ResizeObserver will keep it accurate afterwards\n const [containerHeight, setContainerHeight] = useState(height);\n\n // Track the scroll container's actual height via ResizeObserver.\n // This is more reliable than the `height` prop for flex/grid layouts where\n // the container may resize without the prop ever changing.\n useEffect(() => {\n const el = scrollRef.current;\n if (!el) return;\n const ro = new ResizeObserver(([entry]) => {\n const h = entry.contentRect.height;\n if (h > 0) setContainerHeight(h);\n });\n ro.observe(el);\n // Seed from the element's initial size\n const initial = el.clientHeight;\n if (initial > 0) setContainerHeight(initial);\n return () => ro.disconnect();\n }, []); // empty — scrollRef.current is stable after first render\n\n // Fallback: also sync when the height prop changes (e.g. explicit resize from parent)\n useEffect(() => {\n if (height > 0) setContainerHeight(height);\n }, [height]);\n\n const virtualizedRange = useMemo((): VirtualizedRange => {\n if (!virtualized) {\n return {\n startIndex: 0,\n endIndex: data.length - 1,\n offsetY: 0,\n };\n }\n\n // Dynamic overscan scaled by viewport height (rows in view)\n const rowsInView = Math.max(1, Math.ceil(containerHeight / rowHeight));\n const dynamicOverscan = Math.max(\n overscan,\n Math.max(8, Math.min(rowsInView * 2, 50)),\n );\n\n const startIndex = Math.max(\n 0,\n Math.floor(scrollTop / rowHeight) - dynamicOverscan,\n );\n const visibleCount = Math.ceil(containerHeight / rowHeight);\n const endIndex = Math.min(\n data.length - 1,\n startIndex + visibleCount + dynamicOverscan * 2,\n );\n\n const offsetY = startIndex * rowHeight;\n return { startIndex, endIndex, offsetY };\n }, [\n scrollTop,\n containerHeight,\n data.length,\n rowHeight,\n overscan,\n virtualized,\n ]);\n\n const visibleData = useMemo(() => {\n if (!virtualized) return data;\n return data.slice(\n virtualizedRange.startIndex,\n virtualizedRange.endIndex + 1,\n );\n }, [data, virtualizedRange, virtualized]);\n\n const totalHeight = data.length * rowHeight;\n\n const handleScroll = useCallback((e: UIEvent<HTMLDivElement>) => {\n const target = e.target as HTMLDivElement;\n const nextTop = target.scrollTop;\n pendingScrollTopRef.current = nextTop;\n if (rafIdRef.current == null) {\n rafIdRef.current = requestAnimationFrame(() => {\n rafIdRef.current = null;\n setScrollTop(pendingScrollTopRef.current);\n });\n }\n }, []);\n\n useEffect(() => {\n return () => {\n if (rafIdRef.current != null) cancelAnimationFrame(rafIdRef.current);\n };\n }, []);\n\n return {\n scrollRef,\n virtualizedRange,\n visibleData,\n totalHeight,\n handleScroll,\n };\n};\n","import {\n ChangeEvent,\n forwardRef,\n useCallback,\n useEffect,\n useImperativeHandle,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport { FooterAggregate } from \"../components/FooterAggregate\";\nimport { GridHeader } from \"../components/GridHeader\";\nimport { GridRows } from \"../components/GridRows\";\nimport { GroupBar } from \"../components/GroupBar\";\nimport { GroupHeader } from \"../components/GroupHeader\";\nimport { NoDataMessage } from \"../components/NoDataMessage\";\nimport { PaginationControls } from \"../components/PaginationControls\";\nimport { SearchToolbar } from \"../components/SearchToolbar\";\nimport { SELECT_COL_WIDTH } from \"../constants\";\nimport { useAdvancedFiltering } from \"../hooks/useAdvancedFiltering\";\nimport { useDataWorker } from \"../hooks/useDataWorker\";\nimport { useExport } from \"../hooks/useExport\";\nimport { useGrouping } from \"../hooks/useGrouping\";\nimport { usePagination } from \"../hooks/usePagination\";\nimport { useSelection } from \"../hooks/useSelection\";\nimport { useVirtualization } from \"../hooks/useVirtualization\";\nimport type { KDGridProps, KDGridRef, Density } from \"../types\";\n\n/** Stable default outside the component so it never recreates on every render */\nconst DEFAULT_CAN_SELECT_CELL = () => true;\n\nexport const KDGrid = /*#__PURE__*/ forwardRef<KDGridRef, KDGridProps>(\n function KDGrid(\n {\n data,\n columns,\n getRowId,\n height,\n density: densityProp = \"md\",\n headerDensity,\n headerHeight: headerHeightProp,\n onDensityChange,\n showDensityControl = false,\n onRowSelect,\n onSelectedRowsChange,\n selectable = false,\n isRowSelectable,\n showToolbar = true,\n showExport = false,\n filterable = true,\n groupable = false,\n virtualized = true,\n rowHeight: rowHeightProp,\n overscan = 6,\n rowStyle,\n onContextMenu,\n onRowDoubleClick,\n onRowClick,\n onCellClick,\n onCellContextMenu,\n cellFocusEnabled = false,\n onCellFocusChange,\n cellSelectionEnabled = false,\n canSelectCell = DEFAULT_CAN_SELECT_CELL,\n onCellSelectionChange,\n pagination = { enabled: false, mode: \"client\", pageSize: 50 },\n virtualizationThreshold = 300,\n loading = false,\n onFilterChange,\n onSort,\n onColumnConfigChange,\n initialColumnConfig,\n toolbarLeft,\n toolbarRight,\n groupBarVisibility = \"auto\",\n groupFooterVariant = \"chips\",\n onCopyCells,\n selectedRowIds,\n performanceConfig = {},\n exportOptions: exportOptionsProp,\n renderGroupActions,\n contextMenuItems,\n }: KDGridProps,\n ref,\n ) {\n // ==== Container width tracking (for column flex support) ====\n const containerRef = useRef<HTMLDivElement>(null);\n const [containerWidth, setContainerWidth] = useState<number>(0);\n useEffect(() => {\n const el = containerRef.current;\n if (!el) return;\n const update = () => setContainerWidth(el.clientWidth || 0);\n update();\n // ResizeObserver already fires on window resize — no need for redundant listener\n const ro = new ResizeObserver(() => update());\n ro.observe(el);\n return () => ro.disconnect();\n }, []);\n // ===== Cell focus & rectangular selection state =====\n const [focusedCell, setFocusedCell] = useState<{\n rowId: string | number;\n columnKey: string;\n } | null>(null);\n const [selectionAnchor, setSelectionAnchor] = useState<{\n rowIndex: number;\n colIndex: number;\n } | null>(null);\n const [selectionEnd, setSelectionEnd] = useState<{\n rowIndex: number;\n colIndex: number;\n } | null>(null);\n const isMouseDownRef = useRef(false);\n const lastMousePosRef = useRef<{ x: number; y: number } | null>(null);\n const autoScrollRafRef = useRef<number | null>(null);\n const [dragOverlay, setDragOverlay] = useState<{\n x: number;\n y: number;\n rows: number;\n cols: number;\n } | null>(null);\n\n // ===== Density management and effective row height =====\n const [density, setDensity] = useState<Density>(densityProp);\n useEffect(() => {\n // keep in sync if parent changes controlled prop\n setDensity(densityProp);\n }, [densityProp]);\n\n const densityMap: Record<Density, number> = useMemo(\n () => ({ sm: 28, md: 40, lg: 56 }),\n [],\n );\n const resolvedRowHeight = useMemo(\n () => (rowHeightProp != null ? rowHeightProp : densityMap[density]),\n [rowHeightProp, density, densityMap],\n );\n // Header height: explicit headerHeight > headerDensity > default md\n const resolvedHeaderHeight = useMemo(() => {\n if (headerHeightProp != null) return headerHeightProp;\n const d = headerDensity ?? \"md\";\n return densityMap[d];\n }, [headerHeightProp, headerDensity, densityMap]);\n // Use custom hooks for different concerns - OPTIMIZED\n const {\n globalFilter,\n columnFilters,\n filteredData,\n setGlobalFilter,\n setColumnFilter,\n clearAllFilters,\n } = useAdvancedFiltering({ data, columns });\n\n // Sorting state (tri-state: asc -> desc -> none)\n const [sortConfig, setSortConfig] = useState<{\n key: string | null;\n direction: \"asc\" | \"desc\" | null;\n }>({\n key: null,\n direction: null,\n });\n\n // Column widths state\n const [columnWidths, setColumnWidths] = useState<Record<string, number>>(\n () => {\n const initialWidths: Record<string, number> = {};\n columns.forEach((col) => {\n initialWidths[col.key] = col.width || 100;\n });\n return initialWidths;\n },\n );\n\n // Keep an immutable snapshot of initial widths for reset\n const initialWidthsRef = useRef<Record<string, number>>(\n columns.reduce(\n (acc, c) => {\n acc[c.key] = c.width || 100;\n return acc;\n },\n {} as Record<string, number>,\n ),\n );\n\n // Column order state + initial snapshot\n const initialOrderRef = useRef<string[]>(columns.map((c) => c.key));\n const [columnOrder, setColumnOrder] = useState<string[]>(() =>\n initialOrderRef.current.slice(),\n );\n\n // Column pinning state\n const [pinnedColumns, setPinnedColumns] = useState<Set<string>>(new Set());\n\n // Column visibility state\n const [columnVisibility, setColumnVisibility] = useState<\n Record<string, boolean>\n >(() => {\n const initialVisibility: Record<string, boolean> = {};\n columns.forEach((col) => {\n initialVisibility[col.key] = true;\n });\n return initialVisibility;\n });\n\n const handleSort = useCallback(\n (key: string) => {\n let nextKey: string | null = key;\n let nextDir: \"asc\" | \"desc\" | null = \"asc\";\n\n if (sortConfig.key !== key) {\n nextKey = key;\n nextDir = \"asc\";\n } else if (sortConfig.direction === \"asc\") {\n nextDir = \"desc\";\n } else if (sortConfig.direction === \"desc\") {\n // clear sorting\n nextKey = null;\n nextDir = null;\n } else {\n nextDir = \"asc\";\n }\n\n setSortConfig({ key: nextKey, direction: nextDir });\n\n // Server-side sorting: only call when a direction is active\n if (onSort && pagination?.mode === \"server\" && nextKey && nextDir) {\n onSort(nextKey, nextDir);\n }\n },\n [onSort, pagination?.mode, sortConfig.key, sortConfig.direction],\n );\n\n const handleColumnResize = useCallback(\n (columnKey: string, width: number) => {\n setColumnWidths((prev) => ({\n ...prev,\n [columnKey]: width,\n }));\n },\n [],\n );\n\n // Heuristic text width calc using character count; padding accounts for cell padding/icons\n const estimateWidthForText = useCallback((text: any) => {\n if (text == null) return 0;\n const s = typeof text === \"string\" ? text : String(text);\n const avgCharPx = 8; // conservative average for grid font\n return s.length * avgCharPx;\n }, []);\n\n const autosizeColumn = useCallback(\n (columnKey: string) => {\n const col = columns.find((c) => c.key === columnKey);\n if (!col) return;\n const headerWidth = estimateWidthForText(col.header);\n const sample = data.slice(0, 500); // limit for perf\n let maxCell = 0;\n for (const row of sample) {\n const value = row[columnKey];\n maxCell = Math.max(maxCell, estimateWidthForText(value));\n }\n const padding = 32; // cell padding + sort/menu affordance\n const computed = Math.max(\n 60,\n Math.min(500, Math.max(headerWidth, maxCell) + padding),\n );\n setColumnWidths((prev) => ({ ...prev, [columnKey]: computed }));\n },\n [columns, data, estimateWidthForText],\n );\n\n const autosizeAllColumns = useCallback(() => {\n columns.forEach((c) => autosizeColumn(c.key));\n }, [columns, autosizeColumn]);\n\n const resetColumns = useCallback(() => {\n // reset widths\n setColumnWidths({ ...initialWidthsRef.current });\n // clear pinning\n setPinnedColumns(new Set());\n // show all columns\n setColumnVisibility((prev) => {\n const next: Record<string, boolean> = {};\n Object.keys(prev).forEach((k) => (next[k] = true));\n return next;\n });\n // reset order\n setColumnOrder(initialOrderRef.current.slice());\n }, []);\n\n const headerScrollRef = useRef<HTMLDivElement>(null);\n const footerScrollRef = useRef<HTMLDivElement>(null);\n\n const handleColumnPin = useCallback(\n (columnKey: string, pinned: boolean) => {\n setPinnedColumns((prev) => {\n const newSet = new Set(prev);\n if (pinned) {\n newSet.add(columnKey);\n } else {\n newSet.delete(columnKey);\n }\n return newSet;\n });\n },\n [],\n );\n\n const handleColumnVisibilityChange = useCallback(\n (columnKey: string, visible: boolean) => {\n setColumnVisibility((prev) => ({\n ...prev,\n [columnKey]: visible,\n }));\n },\n [],\n );\n\n // Apply sorting, with optional worker offload for large datasets\n const { process: workerProcess } = useDataWorker({ enabled: true });\n const [sortedData, setSortedData] = useState<any[]>(filteredData);\n\n // Worker threshold: large datasets offloaded to background\n const workerThreshold =\n (performanceConfig as any)?.sortWorkerThreshold ?? 5000;\n\n useEffect(() => {\n let cancelled = false;\n if (!sortConfig.key) {\n setSortedData(filteredData);\n return;\n }\n const rows = filteredData;\n if (rows.length < workerThreshold) {\n // inline sort for small lists\n const dir = sortConfig.direction === \"asc\" ? 1 : -1;\n const out = [...rows].sort((a, b) => {\n const av = a?.[sortConfig.key!];\n const bv = b?.[sortConfig.key!];\n if (av == null && bv == null) return 0;\n if (av == null) return -1 * dir;\n if (bv == null) return 1 * dir;\n if (typeof av === \"number\" && typeof bv === \"number\")\n return (av - bv) * dir;\n return String(av).localeCompare(String(bv)) * dir;\n });\n setSortedData(out);\n return;\n }\n workerProcess(rows, {\n key: sortConfig.key!,\n direction: sortConfig.direction as any,\n }).then((out) => {\n if (!cancelled) setSortedData(out);\n });\n return () => {\n cancelled = true;\n };\n }, [filteredData, sortConfig, workerProcess, workerThreshold]);\n\n const {\n paginationConfig,\n paginatedData,\n isServerLoading,\n handlePageChange,\n handlePageSizeChange,\n resetPage,\n currentPage,\n } = usePagination({ data: sortedData, pagination });\n\n // Unified loading state for header loader with smooth finish animation\n const loadingOverall = loading || isServerLoading;\n const [showLoader, setShowLoader] = useState<boolean>(loadingOverall);\n const [finishingLoader, setFinishingLoader] = useState<boolean>(false);\n const [loaderTop, setLoaderTop] = useState<number>(0);\n useEffect(() => {\n if (loadingOverall) {\n setShowLoader(true);\n setFinishingLoader(false);\n return;\n }\n if (showLoader) {\n setFinishingLoader(true);\n const t = setTimeout(() => {\n setShowLoader(false);\n setFinishingLoader(false);\n }, 200);\n return () => clearTimeout(t);\n }\n }, [loadingOverall]);\n\n const handleGlobalFilterChange = useCallback(\n (e: ChangeEvent<HTMLInputElement>) => {\n setGlobalFilter(e.target.value);\n },\n [setGlobalFilter],\n );\n\n // Grouping functionality\n const {\n groupConfig,\n displayData: groupedDisplayData,\n handleGroupBy,\n addGroupKey,\n removeGroupKey,\n setGroupKeys,\n toggleGroupExpansion,\n isGrouped,\n expandAllGroups,\n collapseAllGroups,\n } = useGrouping({ data: sortedData, columns });\n\n // Expose imperative grouping controls to parent components\n useImperativeHandle(\n ref,\n () => ({\n setGroupKeys,\n addGroupKey,\n removeGroupKey,\n expandAllGroups,\n collapseAllGroups,\n toggleGroupExpansion,\n getGroupConfig: () => groupConfig,\n // Filter methods\n setColumnFilter: (\n columnKey: string,\n filter: import(\"../types\").ColumnFilterValue | null,\n ) => {\n setColumnFilter(columnKey, filter);\n },\n clearColumnFilter: (columnKey: string) => {\n setColumnFilter(columnKey, null);\n },\n clearAllFilters: () => {\n clearAllFilters();\n },\n setGlobalFilter: (value: string) => {\n setGlobalFilter(value);\n },\n }),\n [groupConfig, setColumnFilter, clearAllFilters, setGlobalFilter],\n );\n\n // Do NOT pin grouped columns; only respect explicit pins.\n const effectivePinnedColumns = useMemo(() => {\n return new Set(pinnedColumns);\n }, [pinnedColumns]);\n\n const finalDisplayData = pagination?.enabled\n ? pagination.mode === \"server\"\n ? data\n : paginatedData\n : sortedData;\n\n const dataToDisplay = isGrouped ? groupedDisplayData : finalDisplayData;\n\n const { selectedRows, handleRowSelect, handleSelectAll } = useSelection({\n data: dataToDisplay,\n onRowSelect,\n selectedRowIds,\n getRowId,\n });\n\n // Keep stable ref for onSelectedRowsChange to avoid effect re-running on every parent render\n const onSelectedRowsChangeRef = useRef(onSelectedRowsChange);\n useEffect(() => {\n onSelectedRowsChangeRef.current = onSelectedRowsChange;\n }, [onSelectedRowsChange]);\n\n useEffect(() => {\n if (onSelectedRowsChangeRef.current) {\n onSelectedRowsChangeRef.current(selectedRows);\n }\n }, [selectedRows]);\n\n // Update export hook with selected rows\n const { exportData: exportDataWithSelection } = useExport({\n // Export the currently rendered dataset. In server mode this is the fetched page.\n data: finalDisplayData,\n columns,\n selectedRows,\n filename:\n (exportOptionsProp && exportOptionsProp.filename) || \"grid-data\",\n columnVisibility,\n });\n\n // Decide how to export: client (default) vs server callback\n const handleToolbarExport = useCallback(\n (format: any, exportSelected: boolean) => {\n const selectedIds = Array.from(selectedRows || []);\n if (\n exportOptionsProp?.exportMode === \"server\" &&\n typeof exportOptionsProp?.onServerExport === \"function\"\n ) {\n exportOptionsProp.onServerExport(format, exportSelected, selectedIds);\n } else {\n // Client mode: export only the data available in memory (filtered/paginated set)\n exportDataWithSelection(format, exportSelected);\n }\n },\n [\n exportOptionsProp?.exportMode,\n exportOptionsProp?.onServerExport,\n exportDataWithSelection,\n selectedRows,\n ],\n );\n\n const handleClearFilters = useCallback(() => {\n clearAllFilters();\n }, [clearAllFilters]);\n\n const handleSetDensity = useCallback(\n (d: Density) => {\n setDensity(d);\n if (onDensityChange) onDensityChange(d);\n },\n [onDensityChange],\n );\n\n const effectiveVirtualized = useMemo(() => {\n if (!virtualized) return false;\n return dataToDisplay.length > virtualizationThreshold;\n }, [virtualized, dataToDisplay.length, virtualizationThreshold]);\n\n // Performance configuration with defaults\n const perfConfig = useMemo(\n () => ({\n enableHorizontalVirtualization: true,\n horizontalVirtualizationThreshold: 50,\n sortWorkerThreshold: 5000,\n maxFilterCacheSize: 5000,\n enableAggressiveMemoization: true,\n ...performanceConfig,\n }),\n [performanceConfig],\n );\n\n const { scrollRef, virtualizedRange, visibleData, handleScroll } =\n useVirtualization({\n data: dataToDisplay,\n virtualized: effectiveVirtualized,\n rowHeight: resolvedRowHeight,\n overscan,\n height: height || 400,\n });\n\n // Position the loader bar just below the sticky header, regardless of horizontal scroll\n useEffect(() => {\n const update = () => {\n const el = scrollRef.current;\n if (!el) return;\n // offsetTop is relative to the closest positioned ancestor (the relative grid container)\n const top = (el.offsetTop || 0) + (resolvedHeaderHeight || 0) - 1;\n setLoaderTop(top);\n };\n update();\n const ro = new ResizeObserver(update);\n if (containerRef.current) ro.observe(containerRef.current);\n if (scrollRef.current) ro.observe(scrollRef.current);\n return () => ro.disconnect();\n }, [resolvedHeaderHeight]);\n\n // Horizontal virtualization state\n const [hScrollLeft, setHScrollLeft] = useState(0);\n const hScrollLeftRef = useRef(0);\n const hScrollRafRef = useRef<number | null>(null);\n const scheduleHScrollUpdate = useCallback((value: number) => {\n hScrollLeftRef.current = value;\n if (hScrollRafRef.current != null) return;\n hScrollRafRef.current = requestAnimationFrame(() => {\n hScrollRafRef.current = null;\n setHScrollLeft(hScrollLeftRef.current);\n });\n }, []);\n const [viewportWidth, setViewportWidth] = useState(0);\n useEffect(() => {\n const el = scrollRef.current;\n if (!el) return;\n const update = () => setViewportWidth(el.clientWidth || 0);\n update();\n const ro = new ResizeObserver(update);\n ro.observe(el);\n return () => ro.disconnect();\n }, [scrollRef]);\n\n // Notify parent of filter changes in server-side mode\n useEffect(() => {\n if (!onFilterChange) return;\n if (!(pagination?.enabled && pagination.mode === \"server\")) return;\n\n const filterableKeys = columns\n .filter((c) => !!c.filterable)\n .map((c) => c.key);\n\n onFilterChange({\n globalFilter,\n columnFilters,\n filterableKeys,\n });\n }, [globalFilter, columnFilters]);\n\n // Hydrate from initialColumnConfig on mount\n useEffect(() => {\n if (!initialColumnConfig) return;\n const existingKeys = new Set(columns.map((c) => c.key));\n\n if (initialColumnConfig.columnWidths) {\n const next = Object.fromEntries(\n Object.entries(initialColumnConfig.columnWidths).filter(([k]) =>\n existingKeys.has(k),\n ),\n );\n setColumnWidths((prev) => ({ ...prev, ...next }));\n }\n\n if (initialColumnConfig.columnVisibility) {\n const next = Object.fromEntries(\n Object.entries(initialColumnConfig.columnVisibility).filter(([k]) =>\n existingKeys.has(k),\n ),\n );\n setColumnVisibility((prev) => ({ ...prev, ...next }));\n }\n\n if (initialColumnConfig.pinnedColumns) {\n const pins = initialColumnConfig.pinnedColumns.filter((k) =>\n existingKeys.has(k),\n );\n setPinnedColumns(new Set(pins));\n }\n\n if (initialColumnConfig.sortConfig) {\n const dir =\n initialColumnConfig.sortConfig.direction === \"asc\" ||\n initialColumnConfig.sortConfig.direction === \"desc\"\n ? initialColumnConfig.sortConfig.direction\n : null;\n const key = dir ? initialColumnConfig.sortConfig.key : null;\n setSortConfig({ key, direction: dir });\n }\n\n if (initialColumnConfig.filters) {\n setGlobalFilter(initialColumnConfig.filters.globalFilter || \"\");\n const entries = Object.entries(\n initialColumnConfig.filters.columnFilters || {},\n ).filter(([k]) => existingKeys.has(k));\n for (const [k, v] of entries)\n setColumnFilter(k, v as import(\"../types\").ColumnFilterValue);\n }\n\n if (\n initialColumnConfig.columnOrder &&\n initialColumnConfig.columnOrder.length\n ) {\n const filtered = initialColumnConfig.columnOrder.filter((k) =>\n existingKeys.has(k),\n );\n // append any new columns not in saved order at the end, by original order\n const remaining = columns\n .map((c) => c.key)\n .filter((k) => !filtered.includes(k));\n setColumnOrder([...filtered, ...remaining]);\n }\n\n if (\n initialColumnConfig.groupConfig?.columnKeys &&\n initialColumnConfig.groupConfig.columnKeys.length\n ) {\n setGroupKeys(initialColumnConfig.groupConfig.columnKeys);\n }\n if (initialColumnConfig.density) {\n setDensity(initialColumnConfig.density as Density);\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n // Emit onColumnConfigChange when relevant state updates (debounced)\n useEffect(() => {\n if (!onColumnConfigChange) return;\n const timer = setTimeout(() => {\n onColumnConfigChange({\n columnWidths,\n columnVisibility,\n pinnedColumns: Array.from(pinnedColumns),\n sortConfig,\n groupConfig: { columnKeys: groupConfig.columnKeys },\n filters: { globalFilter, columnFilters },\n columnOrder,\n density,\n });\n }, 200);\n return () => clearTimeout(timer);\n }, [\n onColumnConfigChange,\n columnWidths,\n columnVisibility,\n pinnedColumns,\n sortConfig,\n groupConfig,\n globalFilter,\n columnFilters,\n columnOrder,\n density,\n ]);\n\n // Sync horizontal scroll between header, body, and footer\n // (moved scroll sync effect below after columnsWithWidths is defined)\n\n // Create columns with updated widths and handle pinning order - OPTIMIZED\n const columnsWithWidths = useMemo(() => {\n // Early return if no columns\n if (columns.length === 0) return [];\n\n // order columns by columnOrder first\n const orderIndex = new Map<string, number>(\n columnOrder.map((k, i) => [k, i] as const),\n );\n\n // Batch process columns more efficiently\n const visibleColumns = columns.filter(\n (col) => columnVisibility[col.key] !== false,\n );\n\n // Pre-sort and process in one pass\n const base = visibleColumns\n .sort(\n (a, b) => (orderIndex.get(a.key) || 0) - (orderIndex.get(b.key) || 0),\n )\n .map((col) => {\n const candidate = columnWidths[col.key] ?? col.width;\n const width = Number.isFinite(Number(candidate))\n ? Number(candidate)\n : 100;\n // Enforce default sortable=true unless explicitly false\n const sortable = col.sortable !== false;\n return { ...col, width, sortable } as typeof col & {\n width: number;\n sortable: boolean;\n };\n });\n\n // Optimized flex calculation - only if needed\n const viewportW = Math.max(\n 0,\n containerWidth - (selectable ? SELECT_COL_WIDTH : 0),\n );\n const baseTotal = base.reduce((sum, c) => sum + c.width, 0);\n\n if (viewportW > baseTotal) {\n const flexCols = base.filter((c) => c.flex);\n if (flexCols.length > 0) {\n const extra = viewportW - baseTotal;\n const totalWeight = flexCols.reduce((acc, c) => {\n const weight =\n c.flex === true ? 1 : typeof c.flex === \"number\" ? c.flex : 1;\n return acc + Math.max(0, weight);\n }, 0);\n\n if (totalWeight > 0) {\n // Batch update flex columns\n for (const col of flexCols) {\n const weight =\n col.flex === true\n ? 1\n : typeof col.flex === \"number\"\n ? col.flex\n : 1;\n const increment = (extra * weight) / totalWeight;\n const minW = col.minWidth ?? 0;\n const maxW = col.maxWidth ?? Number.POSITIVE_INFINITY;\n col.width = Math.max(minW, Math.min(maxW, col.width + increment));\n }\n }\n }\n }\n\n // Separate pinned and unpinned columns efficiently\n const pinned: typeof base = [];\n const unpinned: typeof base = [];\n\n for (const col of base) {\n if (effectivePinnedColumns.has(col.key)) {\n pinned.push(col);\n } else {\n unpinned.push(col);\n }\n }\n\n // Sort unpinned columns by grouping if needed\n if (groupConfig.columnKeys && groupConfig.columnKeys.length > 0) {\n const groupIndex = new Map(\n groupConfig.columnKeys.map((k, i) => [k, i]),\n );\n unpinned.sort((a, b) => {\n const aIdx = groupIndex.get(a.key) ?? Number.POSITIVE_INFINITY;\n const bIdx = groupIndex.get(b.key) ?? Number.POSITIVE_INFINITY;\n return aIdx - bIdx;\n });\n }\n\n return [...pinned, ...unpinned];\n }, [\n columns,\n columnWidths,\n effectivePinnedColumns,\n columnVisibility,\n columnOrder,\n groupConfig.columnKeys,\n containerWidth,\n selectable,\n ]);\n\n // Horizontal virtualization for large column sets\n const needsHorizontalVirtualization = useMemo(() => {\n return (\n perfConfig.enableHorizontalVirtualization &&\n columnsWithWidths.length > perfConfig.horizontalVirtualizationThreshold\n );\n }, [\n columnsWithWidths.length,\n perfConfig.enableHorizontalVirtualization,\n perfConfig.horizontalVirtualizationThreshold,\n ]);\n\n // Pinned/unpinned memo + prefix sums for binary search slicing\n const pinnedAll = useMemo(\n () => columnsWithWidths.filter((c) => effectivePinnedColumns.has(c.key)),\n [columnsWithWidths, effectivePinnedColumns],\n );\n const unpinnedAll = useMemo(\n () => columnsWithWidths.filter((c) => !effectivePinnedColumns.has(c.key)),\n [columnsWithWidths, effectivePinnedColumns],\n );\n const unpinnedMeta = useMemo(() => {\n const widths = unpinnedAll.map((c) => (c.width as number) || 100);\n const prefix = new Array(widths.length + 1).fill(0) as number[];\n for (let i = 0; i < widths.length; i++)\n prefix[i + 1] = prefix[i] + widths[i];\n const totalWidth = prefix[widths.length] || 0;\n return { widths, prefix, totalWidth };\n }, [unpinnedAll]);\n\n const visibleColumns = useMemo(() => {\n if (!needsHorizontalVirtualization) return columnsWithWidths;\n\n const leftPad = selectable ? SELECT_COL_WIDTH : 0;\n const pinnedTotal = pinnedAll.reduce(\n (sum, c) => sum + ((c.width as number) || 100),\n 0,\n );\n\n const targetLeft = Math.max(0, hScrollLeft - 200);\n const targetRight = hScrollLeft + viewportWidth + 200;\n\n // Map into unpinned local coordinates\n const base = leftPad + pinnedTotal;\n const localLeft = Math.max(0, targetLeft - base);\n const localRight = Math.max(\n 0,\n Math.min(unpinnedMeta.totalWidth, targetRight - base),\n );\n\n // Binary search over prefix sums\n const firstIndexWithRightGte = (x: number): number => {\n if (!unpinnedMeta.widths.length) return 0;\n let lo = 0,\n hi = unpinnedMeta.widths.length - 1,\n ans = 0;\n while (lo <= hi) {\n const mid = (lo + hi) >> 1;\n const right = unpinnedMeta.prefix[mid + 1];\n if (right >= x) {\n ans = mid;\n hi = mid - 1;\n } else {\n lo = mid + 1;\n }\n }\n return Math.max(0, Math.min(ans, unpinnedMeta.widths.length - 1));\n };\n const lastIndexWithLeftLte = (x: number): number => {\n if (!unpinnedMeta.widths.length) return -1;\n let lo = 0,\n hi = unpinnedMeta.widths.length - 1,\n ans = unpinnedMeta.widths.length - 1;\n while (lo <= hi) {\n const mid = (lo + hi) >> 1;\n const left = unpinnedMeta.prefix[mid];\n if (left <= x) {\n ans = mid;\n lo = mid + 1;\n } else {\n hi = mid - 1;\n }\n }\n return Math.max(0, Math.min(ans, unpinnedMeta.widths.length - 1));\n };\n\n const startIdx = firstIndexWithRightGte(localLeft);\n const endIdx = lastIndexWithLeftLte(localRight);\n const sliced =\n endIdx >= startIdx && endIdx >= 0\n ? unpinnedAll.slice(startIdx, endIdx + 1)\n : [];\n return [...pinnedAll, ...sliced];\n }, [\n needsHorizontalVirtualization,\n columnsWithWidths,\n hScrollLeft,\n viewportWidth,\n selectable,\n pinnedAll,\n unpinnedAll,\n unpinnedMeta,\n ]);\n\n // Memoized hvPadLeft/Right for header and rows\n const unpinnedIndexByKey = useMemo(() => {\n const m = new Map<string, number>();\n unpinnedAll.forEach((c, i) => m.set(c.key, i));\n return m;\n }, [unpinnedAll]);\n const { hvPadLeftMemo, hvPadRightMemo } = useMemo(() => {\n if (!needsHorizontalVirtualization)\n return { hvPadLeftMemo: 0, hvPadRightMemo: 0 } as const;\n const visibleUnpinned = visibleColumns.filter(\n (c) => !effectivePinnedColumns.has(c.key),\n );\n if (!visibleUnpinned.length)\n return { hvPadLeftMemo: 0, hvPadRightMemo: 0 } as const;\n const firstIdx = unpinnedIndexByKey.get(visibleUnpinned[0].key);\n const lastIdx = unpinnedIndexByKey.get(\n visibleUnpinned[visibleUnpinned.length - 1].key,\n );\n if (firstIdx == null || lastIdx == null)\n return { hvPadLeftMemo: 0, hvPadRightMemo: 0 } as const;\n const left = unpinnedMeta.prefix[firstIdx];\n const right = unpinnedMeta.totalWidth - unpinnedMeta.prefix[lastIdx + 1];\n return { hvPadLeftMemo: left, hvPadRightMemo: right } as const;\n }, [\n needsHorizontalVirtualization,\n visibleColumns,\n effectivePinnedColumns,\n unpinnedIndexByKey,\n unpinnedMeta,\n ]);\n\n // Determine footer aggregate presence and keep scroll areas in sync (header/body/footer)\n const hasFooterAggregate = useMemo(\n () => columnsWithWidths.some((c) => c.footerAggregate),\n [columnsWithWidths],\n );\n\n useEffect(() => {\n const bodyElement = scrollRef.current;\n if (!bodyElement) return;\n\n let isBodyScrolling = false;\n\n const syncFromBody = () => {\n if (isBodyScrolling) return;\n isBodyScrolling = true;\n const footerEl = footerScrollRef.current;\n if (footerEl && footerEl.scrollLeft !== bodyElement.scrollLeft) {\n footerEl.scrollLeft = bodyElement.scrollLeft;\n }\n scheduleHScrollUpdate(bodyElement.scrollLeft);\n requestAnimationFrame(() => {\n isBodyScrolling = false;\n });\n };\n\n bodyElement.addEventListener(\"scroll\", syncFromBody, { passive: true });\n // align footer on mount\n if (footerScrollRef.current) {\n footerScrollRef.current.scrollLeft = bodyElement.scrollLeft;\n }\n\n return () => {\n bodyElement.removeEventListener(\"scroll\", syncFromBody);\n };\n }, [scrollRef, hasFooterAggregate]);\n\n // Column index lookup in current render order (pinned first)\n const colIndexByKey = useMemo(() => {\n const m = new Map<string, number>();\n columnsWithWidths.forEach((c, i) => m.set(c.key, i));\n return m;\n }, [columnsWithWidths]);\n\n const colByKey = useMemo(() => {\n const m = new Map<string, any>();\n columnsWithWidths.forEach((c) => m.set(c.key, c));\n return m;\n }, [columnsWithWidths]);\n\n // Flat list of data rows (exclude group headers) for selection math\n const flatRows = useMemo(\n () =>\n dataToDisplay.filter(\n (r: any) => !r._isGroupHeader && !r._isGroupFooter,\n ),\n [dataToDisplay],\n );\n const rowIndexById = useMemo(() => {\n const m = new Map<string | number, number>();\n flatRows.forEach((r, i) => m.set(r.id, i));\n return m;\n }, [flatRows]);\n\n const rowById = useMemo(() => {\n const m = new Map<string | number, any>();\n flatRows.forEach((r) => m.set(r.id, r));\n return m;\n }, [flatRows]);\n\n // Keep a stable reference to the latest onCellSelectionChange and a signature of last emitted selection\n const prevSelectionSignatureRef = useRef<string | null>(null);\n const onCellSelectionChangeRef = useRef(onCellSelectionChange);\n const onCopyCellsRef = useRef(onCopyCells);\n useEffect(() => {\n onCopyCellsRef.current = onCopyCells;\n }, [onCopyCells]);\n useEffect(() => {\n onCellSelectionChangeRef.current = onCellSelectionChange;\n }, [onCellSelectionChange]);\n // (onCopyCells handled separately above)\n\n // Derive a stable dependency for columns (by keys) to avoid re-running effects on width changes\n const columnKeys = useMemo(\n () => columnsWithWidths.map((c) => c.key),\n [columnsWithWidths],\n );\n\n // Selection predicates\n const isCellSelected = useMemo(\n () => (rowId: string | number, columnKey: string) => {\n if (!cellSelectionEnabled) return false;\n if (!selectionAnchor || !selectionEnd) return false;\n const r = rowIndexById.get(rowId);\n const c = colIndexByKey.get(columnKey);\n if (r == null || c == null) return false;\n const rowObj = rowById.get(rowId);\n const colObj = colByKey.get(columnKey);\n if (rowObj && colObj && !canSelectCell(rowObj, colObj)) return false;\n const rMin = Math.min(selectionAnchor.rowIndex, selectionEnd.rowIndex);\n const rMax = Math.max(selectionAnchor.rowIndex, selectionEnd.rowIndex);\n const cMin = Math.min(selectionAnchor.colIndex, selectionEnd.colIndex);\n const cMax = Math.max(selectionAnchor.colIndex, selectionEnd.colIndex);\n return r >= rMin && r <= rMax && c >= cMin && c <= cMax;\n },\n [\n cellSelectionEnabled,\n selectionAnchor,\n selectionEnd,\n rowIndexById,\n colIndexByKey,\n rowById,\n colByKey,\n canSelectCell,\n ],\n );\n\n const isCellFocused = useMemo(\n () => (rowId: string | number, columnKey: string) =>\n focusedCell?.rowId === rowId && focusedCell?.columnKey === columnKey,\n [focusedCell],\n );\n\n // Forward horizontal wheel/trackpad scrolls from header/footer to body to keep a single scroll source\n const forwardWheelToBody = useCallback(\n (e: React.WheelEvent<HTMLDivElement>) => {\n const bodyEl = scrollRef.current;\n if (!bodyEl) return;\n const primarilyHorizontal = Math.abs(e.deltaX) >= Math.abs(e.deltaY);\n const dx = primarilyHorizontal ? e.deltaX : e.deltaY;\n if (dx !== 0) {\n e.preventDefault();\n bodyEl.scrollBy({ left: dx, top: 0, behavior: \"auto\" });\n }\n },\n [],\n );\n\n // Mouse handlers for drag selection\n const handleCellMouseDown = useCallback(\n ({ row, column, event }: { row: any; column: any; event: any }) => {\n const rIndex = rowIndexById.get(row.id);\n const cIndex = colIndexByKey.get(column.key);\n\n // Always set focused cell when focus mode is enabled\n if (cellFocusEnabled && rIndex != null && cIndex != null) {\n // Don't update focus if modal is open\n if (!document.body.hasAttribute(\"data-modal-open\")) {\n setFocusedCell({ rowId: row.id, columnKey: column.key });\n if (onCellFocusChange) {\n onCellFocusChange({\n row,\n column,\n value: row[column.key],\n rowIndex: rIndex,\n colIndex: cIndex,\n });\n }\n }\n }\n\n // Handle rectangular selection only when enabled and left button\n if (!cellSelectionEnabled) return;\n if (!canSelectCell(row, column)) return;\n if (event.button !== 0) return; // left button only\n isMouseDownRef.current = true;\n lastMousePosRef.current = { x: event.clientX, y: event.clientY };\n if (rIndex == null || cIndex == null) return;\n setFocusedCell({ rowId: row.id, columnKey: column.key });\n setSelectionAnchor({ rowIndex: rIndex, colIndex: cIndex });\n setSelectionEnd({ rowIndex: rIndex, colIndex: cIndex });\n // Initialize overlay\n setDragOverlay({\n x: event.clientX,\n y: event.clientY,\n rows: 1,\n cols: 1,\n });\n },\n [\n cellFocusEnabled,\n onCellFocusChange,\n cellSelectionEnabled,\n canSelectCell,\n rowIndexById,\n colIndexByKey,\n ],\n );\n\n const handleCellMouseEnter = useCallback(\n ({ row, column, event }: { row: any; column: any; event: any }) => {\n if (!cellSelectionEnabled) return;\n if (!isMouseDownRef.current || !selectionAnchor) return;\n if (!canSelectCell(row, column)) return;\n const rIndex = rowIndexById.get(row.id);\n const cIndex = colIndexByKey.get(column.key);\n if (rIndex == null || cIndex == null) return;\n setSelectionEnd({ rowIndex: rIndex, colIndex: cIndex });\n // Update last mouse and overlay\n lastMousePosRef.current = { x: event.clientX, y: event.clientY };\n const rMin = Math.min(selectionAnchor.rowIndex, rIndex);\n const rMax = Math.max(selectionAnchor.rowIndex, rIndex);\n const cMin = Math.min(selectionAnchor.colIndex, cIndex);\n const cMax = Math.max(selectionAnchor.colIndex, cIndex);\n setDragOverlay({\n x: event.clientX,\n y: event.clientY,\n rows: rMax - rMin + 1,\n cols: cMax - cMin + 1,\n });\n },\n [\n cellSelectionEnabled,\n canSelectCell,\n selectionAnchor,\n rowIndexById,\n colIndexByKey,\n ],\n );\n\n useEffect(() => {\n const onUp = () => {\n isMouseDownRef.current = false;\n setDragOverlay(null);\n if (autoScrollRafRef.current) {\n cancelAnimationFrame(autoScrollRafRef.current);\n autoScrollRafRef.current = null;\n }\n };\n window.addEventListener(\"mouseup\", onUp);\n return () => window.removeEventListener(\"mouseup\", onUp);\n }, []);\n\n // Global mousemove to keep tracking position while dragging (even outside cells)\n useEffect(() => {\n const onMove = (e: MouseEvent) => {\n if (!isMouseDownRef.current) return;\n lastMousePosRef.current = { x: e.clientX, y: e.clientY };\n };\n window.addEventListener(\"mousemove\", onMove as any);\n return () => window.removeEventListener(\"mousemove\", onMove as any);\n }, []);\n\n // Auto-scroll while dragging near edges of the scroll container\n const ensureAutoScrollLoop = useCallback(() => {\n if (autoScrollRafRef.current != null) return;\n const step = () => {\n autoScrollRafRef.current = null;\n if (!isMouseDownRef.current) return;\n const el = scrollRef.current;\n const mp = lastMousePosRef.current;\n if (el && mp) {\n const rect = el.getBoundingClientRect();\n const margin = 24; // px\n const maxSpeed = 24; // px per frame approx\n let dx = 0;\n let dy = 0;\n if (mp.x < rect.left + margin) dx = -(rect.left + margin - mp.x);\n else if (mp.x > rect.right - margin)\n dx = mp.x - (rect.right - margin);\n if (mp.y < rect.top + margin) dy = -(rect.top + margin - mp.y);\n else if (mp.y > rect.bottom - margin)\n dy = mp.y - (rect.bottom - margin);\n // Normalize to maxSpeed\n const clamp = (v: number) =>\n Math.max(-maxSpeed, Math.min(maxSpeed, v));\n dx = clamp(dx);\n dy = clamp(dy);\n if (dx !== 0 || dy !== 0) {\n el.scrollBy({ left: dx, top: dy, behavior: \"auto\" });\n }\n }\n autoScrollRafRef.current = requestAnimationFrame(step);\n };\n autoScrollRafRef.current = requestAnimationFrame(step);\n }, []);\n\n // Kick the auto-scroll loop when we start a drag\n useEffect(() => {\n if (isMouseDownRef.current) {\n ensureAutoScrollLoop();\n }\n }, [ensureAutoScrollLoop, selectionAnchor]);\n\n // Keyboard: ESC clears selection; Shift+Arrows expands selection\n useEffect(() => {\n const onKey = (e: KeyboardEvent) => {\n if (e.key === \"Escape\") {\n setSelectionAnchor(null);\n setSelectionEnd(null);\n setFocusedCell(null);\n setDragOverlay(null);\n return;\n }\n const isShift = e.shiftKey;\n const arrow = [\n \"ArrowUp\",\n \"ArrowDown\",\n \"ArrowLeft\",\n \"ArrowRight\",\n ].includes(e.key);\n if (!isShift || !arrow || !cellSelectionEnabled) return;\n e.preventDefault();\n // Determine base cell\n let base = selectionEnd;\n if (!base) {\n if (focusedCell) {\n const r = rowIndexById.get(focusedCell.rowId);\n const c = colIndexByKey.get(focusedCell.columnKey);\n if (r != null && c != null) {\n setSelectionAnchor({ rowIndex: r, colIndex: c });\n base = { rowIndex: r, colIndex: c };\n } else {\n return;\n }\n } else {\n return;\n }\n }\n const maxRow = flatRows.length - 1;\n const maxCol = columnsWithWidths.length - 1;\n let nr = base.rowIndex;\n let nc = base.colIndex;\n if (e.key === \"ArrowUp\") nr = Math.max(0, nr - 1);\n if (e.key === \"ArrowDown\") nr = Math.min(maxRow, nr + 1);\n if (e.key === \"ArrowLeft\") nc = Math.max(0, nc - 1);\n if (e.key === \"ArrowRight\") nc = Math.min(maxCol, nc + 1);\n setSelectionEnd({ rowIndex: nr, colIndex: nc });\n // Update overlay near the scroll container center\n const el = scrollRef.current;\n if (el) {\n const rect = el.getBoundingClientRect();\n setDragOverlay({\n x: rect.right - 16,\n y: rect.bottom - 16,\n rows: Math.abs((selectionAnchor?.rowIndex ?? nr) - nr) + 1,\n cols: Math.abs((selectionAnchor?.colIndex ?? nc) - nc) + 1,\n });\n }\n };\n window.addEventListener(\"keydown\", onKey);\n return () => window.removeEventListener(\"keydown\", onKey);\n }, [\n cellSelectionEnabled,\n focusedCell,\n selectionAnchor,\n selectionEnd,\n rowIndexById,\n colIndexByKey,\n flatRows.length,\n columnsWithWidths.length,\n ]);\n\n // Keyboard navigation for focused cell\n useEffect(() => {\n if (!cellFocusEnabled) return;\n const bodyEl = scrollRef.current;\n const headerEl = headerScrollRef.current;\n\n const ensureVisible = (rowIndex: number, colIndex: number) => {\n if (!bodyEl) return;\n // Vertical\n const viewportH = bodyEl.clientHeight;\n const targetTop = rowIndex * resolvedRowHeight;\n const targetBottom = targetTop + resolvedRowHeight;\n if (targetTop < bodyEl.scrollTop) bodyEl.scrollTop = targetTop;\n else if (targetBottom > bodyEl.scrollTop + viewportH)\n bodyEl.scrollTop = targetBottom - viewportH;\n\n // Horizontal\n const colWidth = (columnsWithWidths[colIndex]?.width as number) || 100;\n let left = selectable ? SELECT_COL_WIDTH : 0;\n for (let i = 0; i < colIndex; i++) {\n left += (columnsWithWidths[i]?.width as number) || 100;\n }\n const right = left + colWidth;\n const viewportW = bodyEl.clientWidth;\n if (left < bodyEl.scrollLeft) {\n bodyEl.scrollLeft = left;\n } else if (right > bodyEl.scrollLeft + viewportW) {\n bodyEl.scrollLeft = right - viewportW;\n }\n if (headerEl) headerEl.scrollLeft = bodyEl.scrollLeft;\n };\n\n const handler = (e: KeyboardEvent) => {\n if (!focusedCell) return;\n // Don't handle keyboard navigation if modal is open\n if (document.body.hasAttribute(\"data-modal-open\")) return;\n const { key } = e;\n if (\n key !== \"ArrowLeft\" &&\n key !== \"ArrowRight\" &&\n key !== \"ArrowUp\" &&\n key !== \"ArrowDown\"\n )\n return;\n e.preventDefault();\n const currentRowIdx = rowIndexById.get(focusedCell.rowId);\n const currentColIdx = colIndexByKey.get(focusedCell.columnKey);\n if (currentRowIdx == null || currentColIdx == null) return;\n let nextRow = currentRowIdx;\n let nextCol = currentColIdx;\n if (e.key === \"ArrowLeft\") nextCol = Math.max(0, currentColIdx - 1);\n if (e.key === \"ArrowRight\")\n nextCol = Math.min(columnsWithWidths.length - 1, currentColIdx + 1);\n if (e.key === \"ArrowUp\") nextRow = Math.max(0, currentRowIdx - 1);\n if (e.key === \"ArrowDown\")\n nextRow = Math.min(flatRows.length - 1, currentRowIdx + 1);\n\n const row = flatRows[nextRow];\n const column = columnsWithWidths[nextCol];\n if (!row || !column) return;\n\n setFocusedCell({ rowId: row.id, columnKey: column.key });\n if (onCellFocusChange) {\n onCellFocusChange({\n row,\n column,\n value: row[column.key],\n rowIndex: nextRow,\n colIndex: nextCol,\n });\n }\n ensureVisible(nextRow, nextCol);\n };\n window.addEventListener(\"keydown\", handler);\n return () => window.removeEventListener(\"keydown\", handler);\n }, [\n cellFocusEnabled,\n focusedCell,\n flatRows,\n columnsWithWidths,\n resolvedRowHeight,\n selectable,\n rowIndexById,\n colIndexByKey,\n onCellFocusChange,\n ]);\n\n // Notify parent about selection rectangle (guarded to avoid redundant callbacks)\n useEffect(() => {\n if (!cellSelectionEnabled || !selectionAnchor || !selectionEnd) {\n const payload = { bounds: null as any, cells: [] as any[] };\n const sig = \"none\";\n if (sig !== prevSelectionSignatureRef.current) {\n prevSelectionSignatureRef.current = sig;\n onCellSelectionChangeRef.current?.(payload);\n }\n return;\n }\n\n const rowStart = Math.min(\n selectionAnchor.rowIndex,\n selectionEnd.rowIndex,\n );\n const rowEnd = Math.max(selectionAnchor.rowIndex, selectionEnd.rowIndex);\n const colStart = Math.min(\n selectionAnchor.colIndex,\n selectionEnd.colIndex,\n );\n const colEnd = Math.max(selectionAnchor.colIndex, selectionEnd.colIndex);\n\n const cells: Array<{\n row: any;\n column: any;\n value: any;\n rowIndex: number;\n colIndex: number;\n }> = [];\n for (let r = rowStart; r <= rowEnd; r++) {\n const row = flatRows[r];\n if (!row) continue;\n for (let c = colStart; c <= colEnd; c++) {\n const column = columnsWithWidths[c];\n if (!column) continue;\n if (!canSelectCell(row, column)) continue;\n cells.push({\n row,\n column,\n value: row[column.key],\n rowIndex: r,\n colIndex: c,\n });\n }\n }\n\n const payload = {\n bounds: { rowStart, rowEnd, colStart, colEnd },\n cells,\n };\n const sig = `${rowStart}-${rowEnd}-${colStart}-${colEnd}|len:${cells.length}`;\n if (sig === prevSelectionSignatureRef.current) return;\n prevSelectionSignatureRef.current = sig;\n onCellSelectionChangeRef.current?.(payload);\n }, [\n cellSelectionEnabled,\n selectionAnchor,\n selectionEnd,\n flatRows,\n columnKeys,\n canSelectCell,\n ]);\n\n // ================= COPY HANDLING (Ctrl/Cmd + C) =================\n useEffect(() => {\n // Enable custom copy when either rectangular selection or cell focus mode is active.\n if (!cellSelectionEnabled && !cellFocusEnabled) return;\n const onKeyDown = async (e: KeyboardEvent) => {\n const meta = e.metaKey || e.ctrlKey;\n if (!meta || e.key.toLowerCase() !== \"c\") return;\n const includeHeaders = !!e.shiftKey; // Hold Shift to include header row\n // Determine context\n const hasRect = !!(selectionAnchor && selectionEnd);\n const hasFocus = !!(cellFocusEnabled && focusedCell);\n if (!hasRect && !hasFocus) return; // nothing to do\n\n // If only focused cell (no rectangle) and user has an actual text selection or editing input, allow default behavior\n if (!hasRect && hasFocus) {\n const sel = window.getSelection();\n if (sel && sel.toString().length > 0) return; // user selected text manually\n const active = document.activeElement as HTMLElement | null;\n if (\n active &&\n (active.tagName === \"INPUT\" ||\n active.tagName === \"TEXTAREA\" ||\n active.isContentEditable)\n ) {\n return; // let native copy proceed inside editable fields\n }\n }\n\n // We'll handle copy ourselves now\n e.preventDefault();\n\n const collectCells = (): Array<{\n row: any;\n column: any;\n value: any;\n rowIndex: number;\n colIndex: number;\n }> => {\n const cells: Array<{\n row: any;\n column: any;\n value: any;\n rowIndex: number;\n colIndex: number;\n }> = [];\n if (hasRect && selectionAnchor && selectionEnd) {\n const rowStart = Math.min(\n selectionAnchor.rowIndex,\n selectionEnd.rowIndex,\n );\n const rowEnd = Math.max(\n selectionAnchor.rowIndex,\n selectionEnd.rowIndex,\n );\n const colStart = Math.min(\n selectionAnchor.colIndex,\n selectionEnd.colIndex,\n );\n const colEnd = Math.max(\n selectionAnchor.colIndex,\n selectionEnd.colIndex,\n );\n for (let r = rowStart; r <= rowEnd; r++) {\n const row = flatRows[r];\n if (!row) continue;\n for (let c = colStart; c <= colEnd; c++) {\n const column = columnsWithWidths[c];\n if (!column) continue;\n if (!canSelectCell(row, column)) continue;\n cells.push({\n row,\n column,\n value: row[column.key],\n rowIndex: r,\n colIndex: c,\n });\n }\n }\n } else if (hasFocus && focusedCell) {\n const rIndex = rowIndexById.get(focusedCell.rowId);\n const cIndex = colIndexByKey.get(focusedCell.columnKey);\n if (rIndex != null && cIndex != null) {\n const row = flatRows[rIndex];\n const column = columnsWithWidths[cIndex];\n if (row && column) {\n cells.push({\n row,\n column,\n value: row[column.key],\n rowIndex: rIndex,\n colIndex: cIndex,\n });\n }\n }\n }\n return cells;\n };\n\n const cells = collectCells();\n if (!cells.length) return;\n\n const escapeCell = (val: any): string => {\n const s = val == null ? \"\" : String(val);\n if (\n s.includes('\"') ||\n s.includes(\"\\t\") ||\n s.includes(\"\\n\") ||\n s.includes(\"\\r\")\n ) {\n return '\"' + s.replace(/\"/g, '\"\"') + '\"';\n }\n return s;\n };\n\n // Build tab / newline delimited text (Excel friendly)\n let text = \"\";\n if (hasRect && selectionAnchor && selectionEnd) {\n const rowStart = Math.min(\n selectionAnchor.rowIndex,\n selectionEnd.rowIndex,\n );\n const rowEnd = Math.max(\n selectionAnchor.rowIndex,\n selectionEnd.rowIndex,\n );\n const colStart = Math.min(\n selectionAnchor.colIndex,\n selectionEnd.colIndex,\n );\n const colEnd = Math.max(\n selectionAnchor.colIndex,\n selectionEnd.colIndex,\n );\n if (includeHeaders) {\n const headers: string[] = [];\n for (let c = colStart; c <= colEnd; c++) {\n const column = columnsWithWidths[c];\n if (!column) continue;\n headers.push(escapeCell((column as any).header ?? column.key));\n }\n text += headers.join(\"\\t\") + \"\\n\";\n }\n for (let r = rowStart; r <= rowEnd; r++) {\n const row = flatRows[r];\n if (!row) continue;\n const line: string[] = [];\n for (let c = colStart; c <= colEnd; c++) {\n const column = columnsWithWidths[c];\n if (!column) continue;\n if (!canSelectCell(row, column)) {\n line.push(\"\");\n continue;\n }\n const raw = row[column.key];\n line.push(escapeCell(raw));\n }\n text += line.join(\"\\t\");\n if (r < rowEnd) text += \"\\n\";\n }\n } else {\n // Single focused cell\n const cell = cells[0];\n text = escapeCell(cell.value);\n }\n\n try {\n await navigator.clipboard.writeText(text);\n } catch {\n console.warn(\"Failed to write to clipboard\");\n }\n\n // Fire optional callback if provided\n if (typeof onCopyCellsRef.current === \"function\") {\n const bounds =\n hasRect && selectionAnchor && selectionEnd\n ? {\n rowStart: Math.min(\n selectionAnchor.rowIndex,\n selectionEnd.rowIndex,\n ),\n rowEnd: Math.max(\n selectionAnchor.rowIndex,\n selectionEnd.rowIndex,\n ),\n colStart: Math.min(\n selectionAnchor.colIndex,\n selectionEnd.colIndex,\n ),\n colEnd: Math.max(\n selectionAnchor.colIndex,\n selectionEnd.colIndex,\n ),\n }\n : null;\n try {\n onCopyCellsRef.current({\n text,\n bounds,\n cells,\n isRectangular: !!bounds,\n isFocusedCell: !bounds,\n });\n } catch {\n /* swallow */\n }\n }\n };\n window.addEventListener(\"keydown\", onKeyDown);\n return () => window.removeEventListener(\"keydown\", onKeyDown);\n }, [\n cellSelectionEnabled,\n cellFocusEnabled,\n selectionAnchor,\n selectionEnd,\n focusedCell,\n flatRows,\n columnsWithWidths,\n canSelectCell,\n rowIndexById,\n colIndexByKey,\n ref,\n ]);\n\n const totalWidth = columnsWithWidths.reduce(\n (sum, col) => sum + (col.width || 100),\n 0,\n );\n\n useEffect(() => {\n if (currentPage !== 1) {\n // When filters change, reset pagination to the first page.\n // In server mode, also trigger a server fetch for page 1.\n if (pagination?.enabled && pagination.mode === \"server\") {\n handlePageChange(1);\n } else {\n resetPage();\n }\n }\n // Note: do not depend on currentPage or pagination props here,\n // to avoid resetting when the user simply navigates pages.\n // This effect should only respond to filter changes.\n }, [globalFilter, columnFilters]);\n\n return (\n <div\n ref={containerRef}\n className=\"border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden bg-white dark:bg-gray-900 h-full flex flex-col\"\n data-grid-container\n >\n {/* Search Toolbar */}\n {showToolbar && filterable && (\n <SearchToolbar\n globalFilter={globalFilter}\n filteredDataLength={filteredData.length}\n totalDataLength={paginationConfig.totalRows}\n paginationMode={pagination?.mode}\n selectedRowsCount={selectedRows.size}\n showExport={showExport}\n columns={columns}\n columnFilters={columnFilters}\n columnVisibility={columnVisibility}\n onResetColumns={resetColumns}\n exportOptions={{\n enabled: (exportOptionsProp?.enabled ?? true) && showExport,\n formats: exportOptionsProp?.formats ?? [\"xlsx\"],\n filename: exportOptionsProp?.filename ?? \"grid-data\",\n onExport: handleToolbarExport,\n }}\n customLeftContent={toolbarLeft}\n customRightContent={toolbarRight}\n onGlobalFilterChange={handleGlobalFilterChange}\n onClearFilters={handleClearFilters}\n onColumnFilter={setColumnFilter}\n onColumnVisibilityChange={handleColumnVisibilityChange}\n columnOrder={columnOrder}\n onColumnOrderChange={setColumnOrder}\n pinnedColumns={pinnedColumns}\n onScrollToColumn={(columnKey) => {\n const bodyEl = scrollRef.current;\n const headerEl = headerScrollRef.current;\n if (!bodyEl) return;\n // Find column index in current render order\n const idx = colIndexByKey.get(columnKey);\n if (idx == null) return;\n // Compute left position of the column by summing widths of previous columns\n const colWidth = (columnsWithWidths[idx]?.width as number) || 100;\n let left = selectable ? SELECT_COL_WIDTH : 0;\n for (let i = 0; i < idx; i++) {\n left += (columnsWithWidths[i]?.width as number) || 100;\n }\n const right = left + colWidth;\n const viewportW = bodyEl.clientWidth;\n // Scroll behavior: if already in view, minimal movement; otherwise align left\n if (left < bodyEl.scrollLeft) {\n bodyEl.scrollTo({ left, behavior: \"smooth\" });\n } else if (right > bodyEl.scrollLeft + viewportW) {\n bodyEl.scrollTo({\n left: right - viewportW,\n behavior: \"smooth\",\n });\n } else {\n // Nudge slightly to center it\n const center = Math.max(\n 0,\n left - Math.max(0, (viewportW - colWidth) / 2),\n );\n bodyEl.scrollTo({ left: center, behavior: \"smooth\" });\n }\n if (headerEl) headerEl.scrollLeft = bodyEl.scrollLeft;\n }}\n density={density}\n onDensityChange={handleSetDensity}\n showDensityControl={showDensityControl}\n />\n )}\n\n {/* Grid Container */}\n <div className=\"flex flex-col relative flex-1 min-h-50\">\n {/* Group Bar (drag columns here to group) */}\n {groupable &&\n (groupBarVisibility === \"visible\" ||\n (groupBarVisibility === \"auto\" &&\n groupConfig.columnKeys.length > 0)) && (\n <GroupBar\n columns={columns}\n groupedKeys={groupConfig.columnKeys}\n onRemove={removeGroupKey}\n onReorder={setGroupKeys}\n onDropColumnKey={addGroupKey}\n isAnyExpanded={groupConfig.expanded.size > 0}\n onToggleExpandAll={() => {\n if (groupConfig.expanded.size > 0) {\n collapseAllGroups();\n } else {\n expandAllGroups();\n }\n }}\n />\n )}\n {/* Header moved inside body scroll area as sticky for perfect sync */}\n\n {/* Body */}\n <div\n ref={scrollRef}\n className={`flex-1 overflow-auto relative [&::-webkit-scrollbar]:thin ${\n cellSelectionEnabled ? \"select-none\" : \"\"\n }`}\n onScroll={handleScroll}\n >\n {/* Sticky header inside the same scroll container */}\n <div className=\"sticky top-0 z-3\">\n <div\n style={{\n minWidth: `${\n totalWidth + (selectable ? SELECT_COL_WIDTH : 0)\n }px`,\n }}\n >\n {(() => {\n const headerPinned = pinnedAll;\n const headerUnpinned = visibleColumns.filter(\n (c) => !effectivePinnedColumns.has(c.key),\n );\n\n return (\n <GridHeader\n pinnedColumns={headerPinned}\n unpinnedColumns={headerUnpinned}\n hvPadLeft={hvPadLeftMemo}\n hvPadRight={hvPadRightMemo}\n headerHeight={resolvedHeaderHeight}\n sortConfig={sortConfig}\n columnFilters={columnFilters}\n selectable={selectable}\n selectedRows={selectedRows}\n totalRows={dataToDisplay.length}\n data={data}\n onSort={handleSort}\n onColumnFilter={setColumnFilter}\n onSelectAll={() =>\n handleSelectAll(\n selectedRows.size !== dataToDisplay.length,\n )\n }\n onColumnResize={handleColumnResize}\n pinnedKeySet={effectivePinnedColumns}\n onColumnPin={handleColumnPin}\n groupable={groupable}\n groupedByColumn={groupConfig.columnKeys[0] || null}\n groupedByColumns={groupConfig.columnKeys}\n onGroupToggle={(key, next) =>\n next ? addGroupKey(key) : removeGroupKey(key)\n }\n onGroupBy={handleGroupBy}\n onAutosizeColumn={autosizeColumn}\n onAutosizeAllColumns={autosizeAllColumns}\n onResetColumns={resetColumns}\n columnOrder={columnOrder}\n onColumnOrderChange={setColumnOrder}\n paginationMode={\n pagination?.enabled ? pagination.mode : null\n }\n />\n );\n })()}\n </div>\n </div>\n\n <div\n style={{\n minWidth: `${totalWidth + (selectable ? SELECT_COL_WIDTH : 0)}px`,\n height: effectiveVirtualized\n ? `${dataToDisplay.length * resolvedRowHeight}px`\n : \"auto\",\n }}\n >\n {/* Loading bar is rendered at the bottom of the sticky header above */}\n {/* Empty state: content area renders nothing; overlay is placed outside scrollRef */}\n {!loading && dataToDisplay.length === 0 ? (\n <></>\n ) : (\n <div\n style={{\n transform: `translateY(${\n effectiveVirtualized ? virtualizedRange.offsetY : 0\n }px)`,\n willChange: \"transform\",\n contain: \"content\",\n }}\n >\n {(() => {\n const nodes: React.ReactNode[] = [];\n let chunk: any[] = [];\n const flush = () => {\n if (!chunk.length) return;\n const key = `chunk-${chunk[0]?.id}-${chunk.length}-${virtualizedRange.offsetY}`;\n nodes.push(\n <div key={key} style={{ opacity: loading ? 0.5 : 1 }}>\n <GridRows\n data={chunk}\n columns={visibleColumns}\n selectedRows={selectedRows}\n virtualized={false}\n virtualizedRange={{\n startIndex: 0,\n endIndex: chunk.length - 1,\n offsetY: 0,\n }}\n rowHeight={resolvedRowHeight}\n selectable={selectable}\n isRowSelectable={isRowSelectable}\n onRowSelect={handleRowSelect}\n pinnedColumns={effectivePinnedColumns}\n hvPadLeft={hvPadLeftMemo}\n hvPadRight={hvPadRightMemo}\n rowStyle={rowStyle}\n globalFilter={globalFilter}\n onContextMenu={onContextMenu}\n onRowDoubleClick={onRowDoubleClick}\n onRowClick={onRowClick}\n onCellClick={onCellClick}\n onCellContextMenu={onCellContextMenu}\n isCellFocused={isCellFocused}\n isCellSelected={isCellSelected}\n onCellMouseDown={handleCellMouseDown}\n onCellMouseEnter={handleCellMouseEnter}\n contextMenuItems={contextMenuItems}\n getRowId={getRowId}\n />\n </div>,\n );\n chunk = [];\n };\n\n for (const row of visibleData) {\n if ((row as any)._isGroupHeader) {\n flush();\n nodes.push(\n <GroupHeader\n key={row.id}\n row={row}\n isExpanded={groupConfig.expanded.has(\n row._groupKey || \"\",\n )}\n onToggle={toggleGroupExpansion}\n viewportWidth={containerWidth}\n selectable={selectable}\n rowHeight={resolvedRowHeight}\n getHeaderLabel={(colKey) =>\n columns.find((c) => c.key === colKey)?.header ||\n colKey\n }\n getValueLabel={(colKey, raw) => {\n const col = columns.find((c) => c.key === colKey);\n if (col?.formatter) {\n try {\n return col.formatter(raw);\n } catch (_) {\n return String(raw ?? \"\");\n }\n }\n return String(raw ?? \"\");\n }}\n renderGroupActions={renderGroupActions}\n />,\n );\n } else if ((row as any)._isGroupFooter) {\n flush();\n // Use a consistent light blue theme for aggregate footers (with dark mode support)\n if (groupFooterVariant === \"chips\") {\n // Build chips for columns that requested aggregation and have a value\n const chips = columnsWithWidths\n .filter(\n (c) =>\n !!c.aggregate &&\n (row as any)._groupAgg &&\n (row as any)._groupAgg[c.key] !== undefined,\n )\n .map((c) => {\n const rawVal = (row as any)._groupAgg[c.key];\n const fmt = c.aggregateFormatter || c.formatter;\n const display = fmt\n ? (() => {\n try {\n return fmt(rawVal);\n } catch {\n return String(rawVal);\n }\n })()\n : String(rawVal);\n return (\n <span\n key={c.key}\n className={\n // Use static Tailwind classes to avoid JIT purge issues\n \"px-2.5 py-1 rounded-md bg-blue-50 dark:bg-blue-900/40 text-blue-700 dark:text-blue-200 text-xs font-medium\"\n }\n title={`${c.header}`}\n >\n {c.header}: {display}\n </span>\n );\n });\n\n nodes.push(\n <div\n key={row.id}\n className=\"sticky left-0 z-1\"\n style={{\n minWidth: `${\n totalWidth +\n (selectable ? SELECT_COL_WIDTH : 0)\n }px`,\n height: `${resolvedRowHeight}px`,\n }}\n >\n <div\n className={\n // Static Tailwind classes for 'blue' theme\n \"flex items-center justify-between h-full border-t border-blue-200 dark:border-blue-800 bg-blue-50/60 dark:bg-blue-900/20 px-4\"\n }\n role=\"contentinfo\"\n >\n <div className=\"flex items-center gap-2 flex-wrap overflow-hidden\">\n {chips.length ? (\n chips\n ) : (\n <span className=\"text-xs text-gray-500\">\n No aggregates\n </span>\n )}\n </div>\n <span className=\"text-[10px] uppercase tracking-wide text-blue-700 dark:text-blue-300\">\n Group Summary\n </span>\n </div>\n </div>,\n );\n } else {\n // columns variant: show aggregate values in-place under their respective columns\n nodes.push(\n <div\n key={row.id}\n className=\"sticky left-0 z-1 bg-blue-100 dark:bg-gray-900\"\n style={{\n minWidth: `${\n totalWidth +\n (selectable ? SELECT_COL_WIDTH : 0)\n }px`,\n height: `${resolvedRowHeight}px`,\n }}\n >\n <div\n className={\n // Static Tailwind classes matching the 'chips' variant theme\n \"flex h-full border-t border-blue-200 dark:border-blue-800 bg-blue-50/60 dark:bg-blue-900/20\"\n }\n role=\"contentinfo\"\n >\n {selectable && (\n <div\n style={{ width: SELECT_COL_WIDTH }}\n className=\"shrink-0\"\n />\n )}\n {columnsWithWidths.map((col) => {\n const width = (col.width as number) || 100;\n const rawVal = (row as any)._groupAgg\n ? (row as any)._groupAgg[col.key]\n : undefined;\n const fmt =\n col.aggregateFormatter || col.formatter;\n const raw =\n rawVal === undefined\n ? \"\"\n : fmt\n ? (() => {\n try {\n return fmt(rawVal);\n } catch {\n return rawVal;\n }\n })()\n : rawVal;\n\n // ensure final format is 2 decimals only for decimal numbers\n let display;\n if (typeof raw === \"number\") {\n display = Number.isInteger(raw)\n ? String(raw)\n : raw.toFixed(2);\n } else if (\n !isNaN(raw) &&\n raw !== \"\" &&\n raw !== null\n ) {\n // also handles when formatter returned string numbers\n const num = Number(raw);\n display = Number.isInteger(num)\n ? String(num)\n : num.toFixed(2);\n } else {\n display = String(raw ?? \"\");\n }\n return (\n <div\n key={`agg-cell-${(row as any)._groupKey}-${\n col.key\n }`}\n className=\"px-2 text-xs font-medium text-blue-800 dark:text-blue-200 flex items-center overflow-hidden\"\n style={{\n width,\n minWidth: width,\n maxWidth: width,\n }}\n title={\n display\n ? `${col.header}: ${display}`\n : undefined\n }\n >\n <span className=\"truncate w-full\">\n {display}\n </span>\n </div>\n );\n })}\n </div>\n </div>,\n );\n }\n } else {\n chunk.push(row);\n }\n }\n flush();\n return nodes;\n })()}\n </div>\n )}\n </div>\n </div>\n {/* Loading bar overlay (outside scroll area, like NoDataMessage) */}\n {showLoader && (\n <div\n className={`pointer-events-none absolute left-0 right-0 h-1 bg-gray-200 overflow-hidden z-30 ${\n finishingLoader\n ? \"opacity-0 transition-opacity duration-200\"\n : \"opacity-100\"\n }`}\n style={{ top: loaderTop }}\n >\n <div className=\"h-full w-1/3 bg-blue-500 animate-[slide_1.2s_linear_infinite]\" />\n </div>\n )}\n {/* Viewport overlay for NoDataMessage that does not scroll horizontally/vertically */}\n {!loading && dataToDisplay.length === 0 && (\n <div className=\"pointer-events-none absolute inset-0 z-0 flex items-center justify-center\">\n <div className=\"pointer-events-auto\">\n <NoDataMessage\n hasFilters={\n !!globalFilter || Object.keys(columnFilters).length > 0\n }\n hasData={data.length > 0}\n />\n </div>\n </div>\n )}\n </div>\n\n {/* Footer Aggregate */}\n {hasFooterAggregate && (\n <div\n ref={footerScrollRef}\n className=\"shrink-0 overflow-x-hidden overflow-y-visible [&::-webkit-scrollbar]:hidden\"\n style={{ scrollbarWidth: \"none\", msOverflowStyle: \"none\" }}\n onWheel={forwardWheelToBody}\n >\n <div\n className=\"bg-gray-50 dark:bg-gray-800 border-t border-gray-200 dark:border-gray-700\"\n style={{\n minWidth: `${totalWidth + (selectable ? SELECT_COL_WIDTH : 0)}px`,\n height: `${resolvedRowHeight}px`,\n }}\n >\n <FooterAggregate\n columns={columnsWithWidths}\n data={flatRows}\n selectable={selectable}\n rowHeight={resolvedRowHeight}\n pinnedColumns={effectivePinnedColumns}\n />\n </div>\n </div>\n )}\n\n {/* Pagination Footer */}\n\n <PaginationControls\n paginationConfig={paginationConfig}\n currentPage={paginationConfig.currentPage}\n isServerLoading={isServerLoading}\n selectedRowsCount={selectedRows.size}\n totalDataLength={data.length}\n filteredDataLength={\n pagination?.mode === \"server\"\n ? undefined // Don't pass filtered data length for server mode\n : filteredData.length\n }\n paginationMode={pagination.mode}\n onPageChange={handlePageChange}\n onPageSizeChange={handlePageSizeChange}\n />\n\n {/* Drag selection overlay (fixed near cursor) */}\n {dragOverlay && (\n <div\n className=\"fixed z-50 pointer-events-none select-none\"\n style={{ top: dragOverlay.y + 12, left: dragOverlay.x + 12 }}\n >\n <div className=\"px-2 py-1 rounded bg-gray-800 text-white text-xs shadow-lg opacity-90\">\n {dragOverlay.rows} × {dragOverlay.cols}\n </div>\n </div>\n )}\n </div>\n );\n },\n);\n\nexport default KDGrid;\n"],"names":["REACT_ELEMENT_TYPE","Symbol","for","REACT_FRAGMENT_TYPE","jsxProd","type","config","maybeKey","key","propName","$$typeof","ref","props","reactJsxRuntime_production","Fragment","jsx","jsxs","process","env","NODE_ENV","getComponentNameFromType","REACT_CLIENT_REFERENCE","displayName","name","REACT_PROFILER_TYPE","REACT_STRICT_MODE_TYPE","REACT_SUSPENSE_TYPE","REACT_SUSPENSE_LIST_TYPE","REACT_ACTIVITY_TYPE","tag","console","error","REACT_PORTAL_TYPE","REACT_CONTEXT_TYPE","REACT_CONSUMER_TYPE","_context","REACT_FORWARD_REF_TYPE","innerType","render","REACT_MEMO_TYPE","REACT_LAZY_TYPE","_payload","_init","x","testStringCoercion","value","checkKeyStringCoercion","JSCompiler_inline_result","e","JSCompiler_inline_result$jscomp$0","toStringTag","constructor","call","getTaskName","UnknownOwner","Error","elementRefGetterWithDeprecationWarning","componentName","this","didWarnAboutElementRef","jsxDEVImpl","isStaticChildren","debugStack","debugTask","dispatcher","children","isArrayImpl","length","validateChildKeys","Object","freeze","hasOwnProperty","keys","filter","k","join","didWarnAboutKeySpread","getter","getOwnPropertyDescriptor","get","isReactWarning","hasValidKey","warnAboutAccessingKey","specialPropKeyWarningShown","defineProperty","configurable","defineKeyPropWarningGetter","owner","refProp","_owner","enumerable","_store","writable","ReactElement","ReactSharedInternals","A","getOwner","node","isValidElement","validated","status","object","React","require$$0","__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE","prototype","Array","isArray","createTask","unknownOwnerDebugStack","react_stack_bottom_frame","callStackForError","bind","unknownOwnerDebugTask","reactJsxRuntime_development","trackActualOwner","recentlyCreatedOwnerStacks","jsxRuntimeModule","exports","require$$1","SELECT_COL_WIDTH","FooterAggregate","memo","columns","data","selectable","rowHeight","pinnedColumns","Set","aggregateValues","useMemo","result","columnsWithFooterAgg","col","footerAggregate","forEach","values","map","row","aggValue","warn","isDateLike","s","test","includes","Number","isFinite","Date","parse","nums","v","NaN","sv","String","n","parseFloat","replace","tryDateNumbers","getTime","t","reduce","a","b","Math","min","dateNums","max","some","totalWidth","sum","width","leftOffsetByPinnedKey","Map","pinnedKeysInOrder","c","has","acc","set","find","_jsxs","className","style","minWidth","height","_jsx","rawValue","hasAggregate","undefined","displayValue","formatter","footerAggregateFormatter","toString","toFixed","isPinned","leftOffset","noPadding","align","maxWidth","left","title","header","prev","next","getRowId","i","pc","nc","extractId","idx","id","prevFirst","nextFirst","prevLastIdx","nextLastIdx","prevLast","nextLast","size","Icon","xmlns","viewBox","fill","stroke","strokeWidth","strokeLinecap","strokeLinejoin","focusable","ChevronLeft","p","points","ChevronRight","ChevronDown","ChevronsLeft","ChevronsRight","ArrowUp","x1","y1","x2","y2","ArrowDown","ArrowUpDown","d","X","Check","Copy","y","rx","ry","Edit","Trash2","Archive","Download","Menu","Filter","FilterX","Settings","cx","cy","r","Pin","PinOff","Group","Ungroup","MoreHorizontal","Eye","EyeOff","Search","Database","FileText","Table","Users","LocateFixed","Loader2","TextFilter","onChange","placeholder","textValue","setTextValue","useState","operator","setOperator","newOperator","op","trim","handleOperatorChange","target","handleTextChange","newText","NumberFilter","numberValue","setNumberValue","secondValue","setSecondValue","handleValueChange","newValue","isSecond","numValue","numSecondValue","isNaN","DatePicker","label","toYMD","getFullYear","getMonth","padStart","getDate","fromYMD","m","split","toDMY","DateFilter","toDateObj","toStored","dateValue","setDateValue","secondDateValue","setSecondDateValue","useEffect","clampDate","date","minDate","maxDate","handleDateChange","newDate","nextSecond","maxForFirst","maxDateObj","clampedDate","minDateObj","end","MultiselectFilter","options","columnKey","searchText","setSearchText","selectedValues","setSelectedValues","availableOptions","opts","isBlankValue","val","normalizedValues","processedOptions","opt","isBlank","from","sort","localeCompare","filteredOptions","searchLower","toLowerCase","option","onClick","allValues","index","isSelected","optionValue","newSelected","delete","add","handleToggleValue","BooleanFilter","booleanValue","setBooleanValue","FilterContent","column","filterConfig","filterable","sampleValues","slice","firstValue","uniqueValues","GridHeaderComponent","unpinnedColumns","hvPadLeft","hvPadRight","headerHeight","sortConfig","columnFilters","selectedRows","totalRows","onSort","onColumnFilter","onSelectAll","onColumnResize","pinnedKeySet","onColumnPin","groupable","groupedByColumn","onGroupBy","groupedByColumns","onGroupToggle","onAutosizeColumn","onAutosizeAllColumns","onResetColumns","columnOrder","onColumnOrderChange","paginationMode","allColumns","activeColumnMenu","setActiveColumnMenu","menuPosition","setMenuPosition","isResizing","setIsResizing","startX","setStartX","startWidth","setStartWidth","activeTab","setActiveTab","tempFilter","setTempFilter","isTouchDevice","setIsTouchDevice","window","navigator","maxTouchPoints","matchMedia","matches","menuReorderDraggingKey","setMenuReorderDraggingKey","menuReorderDragOver","setMenuReorderDragOver","isAllSelected","isIndeterminate","handleColumnMenuClick","event","stopPropagation","rect","currentTarget","getBoundingClientRect","containerEl","closest","containerRect","DOMRect","innerWidth","innerHeight","PADDING","clampedLeft","right","top","bottom","handleApplyFilter","hasActiveFilter","handleResizeStart","preventDefault","clientX","handleResizeMove","newWidth","handleResizeEnd","draggingKey","setDraggingKey","dragOver","setDragOver","handleDragStart","dataTransfer","effectAllowed","setData","handleDragOver","targetKey","dropEffect","position","handleDrop","sourceKey","before","base","indexOf","splice","handleDragEnd","handleMenuReorderDragStart","handleMenuReorderDragOver","clientY","handleMenuReorderDrop","handleMenuReorderDragEnd","document","addEventListener","body","cursor","userSelect","removeEventListener","handleClickOutside","_Fragment","role","checked","el","indeterminate","onKeyDown","pinnedIndex","headerJustify","headerAlign","colSortable","sortable","draggable","onDragStart","onDragOver","onDrop","onDragEnd","direction","maxHeight","isGrouped","Boolean","isPinnedItem","onMouseDown","onDoubleClick","nextPinned","GridHeader","RowContextMenu","isVisible","onClose","menuItems","menuRef","useRef","current","contains","handleEscape","adjustedPosition","menuHeight","item","separator","viewportWidth","viewportHeight","menuWidth","transform","disabled","handleItemClick","icon","GridRowsComponent","virtualized","virtualizedRange","isRowSelectable","onRowSelect","rowStyle","globalFilter","onContextMenu","onRowDoubleClick","onRowClick","onCellClick","isCellFocused","isCellSelected","onCellContextMenu","onCellMouseDown","onCellMouseEnter","contextMenuItems","totalHeight","widthByKey","pinnedCount","ctxMenu","setCtxMenu","handleContextMenu","useCallback","closeCtxMenu","offsetY","actualIndex","startIndex","customRowStyles","rowId","rowIndex","extractRowId","defaultRowColor","selectedRowColor","handleDoubleClick","handleRowClick","tabIndex","colIndex","rawCell","renderedValue","cellRenderer","searchQuery","query","containsSearchQuery","text","lowerText","parts","lastIndex","searchIndex","keyCounter","push","margin","highlightText","alignClass","justifyClass","paddingClass","extraCellClass","extraCellStyle","cellStyle","cell","handleCellClick","_isGroupHeader","_isGroupFooter","onMouseEnter","wrapCellContent","areEqual","endIndex","GridRows","GroupBar","groupedKeys","onRemove","onReorder","onDropColumnKey","onToggleExpandAll","isAnyExpanded","dragKey","setDragKey","dragOverKey","setDragOverKey","dragOverBefore","setDragOverBefore","labelFor","handleChipDragStart","handleChipDragOver","getData","order","GroupHeader","isExpanded","onToggle","getHeaderLabel","getValueLabel","renderGroupActions","handleToggle","_groupKey","paddingLeft","_groupLevel","_groupColumnKey","_groupValue","_groupCount","groupKey","groupValue","rows","_groupRows","count","level","NoDataMessage","hasFilters","hasData","message","description","PaginationControlsComponent","paginationConfig","currentPage","isServerLoading","selectedRowsCount","totalDataLength","filteredDataLength","onPageChange","onPageSizeChange","start","total","effectiveTotal","enabled","pageSize","getCurrentPageRange","isFiltered","toLocaleString","showPageSizeSelector","pageSizeOptions","totalPages","_","page","pages","maxVisible","delta","floor","isActive","PaginationControls","CustomSelect","searchable","isOpen","setIsOpen","searchTerm","setSearchTerm","highlightedIndex","setHighlightedIndex","containerRef","inputRef","listRef","selectedOption","handleKeyDown","handleSelect","highlightedElement","scrollIntoView","block","behavior","setTimeout","focus","ColumnFilterSelector","filterableColumns","selectedColumn","setSelectedColumn","multiSearch","setMultiSearch","columnOptions","selectedColumnData","filterType","currentFilter","lowered","currentValues","newValues","selectOptions","parseInput","direct","asDate","primaryDate","secondDate","effectiveOperator","stored","renderFilterInput","entries","handleActiveFilterClick","formatDate","parsed","operatorLabel","equals","gt","gte","lt","lte","between","hasWindow","getNodeName","isNode","nodeName","getWindow","_node$ownerDocument","ownerDocument","defaultView","getDocumentElement","_ref","documentElement","Node","isElement","Element","isHTMLElement","HTMLElement","isShadowRoot","ShadowRoot","invalidOverflowDisplayValues","isOverflowElement","element","overflow","overflowX","overflowY","display","getComputedStyle","tableElements","isTableElement","topLayerSelectors","isTopLayer","selector","_e","transformProperties","willChangeValues","containValues","isContainingBlock","elementOrCss","webkit","isWebKit","css","containerType","backdropFilter","willChange","contain","CSS","supports","lastTraversableNodeNames","isLastTraversableNode","getNodeScroll","scrollLeft","scrollTop","scrollX","scrollY","getParentNode","assignedSlot","parentNode","host","getNearestOverflowAncestor","getOverflowAncestors","list","traverseIframes","_node$ownerDocument2","scrollableAncestor","isBody","win","frameElement","getFrameElement","concat","visualViewport","parent","getPrototypeOf","round","createCoords","oppositeSideMap","oppositeAlignmentMap","clamp","evaluate","param","getSide","placement","getAlignment","getOppositeAxis","axis","getAxisLength","yAxisSides","getSideAxis","getAlignmentAxis","getOppositeAlignmentPlacement","alignment","lrPlacement","rlPlacement","tbPlacement","btPlacement","getOppositePlacement","side","rectToClientRect","useLayoutEffect","useSafeInsertionEffect","useInsertionEffect","fn","computeCoordsFromPlacement","rtl","reference","floating","sideAxis","alignmentAxis","alignLength","isVertical","commonX","commonY","commonAlign","coords","async","detectOverflow","state","_await$platform$isEle","platform","rects","elements","strategy","boundary","rootBoundary","elementContext","altBoundary","padding","paddingObject","expandPaddingObject","getPaddingObject","clippingClientRect","getClippingRect","contextElement","offsetParent","getOffsetParent","offsetScale","getScale","elementClientRect","convertOffsetParentRelativeRectToViewportRelativeRect","originSides","getCssDimensions","getComputedStyle$1","hasOffset","offsetWidth","offsetHeight","shouldFallback","$","unwrapElement","domElement","noOffsets","getVisualOffsets","offsetLeft","offsetTop","includeScale","isFixedStrategy","clientRect","scale","visualOffsets","isFixed","floatingOffsetParent","shouldAddVisualOffsets","offsetWin","currentWin","currentIFrame","iframeScale","iframeRect","clientLeft","clientTop","paddingTop","getWindowScrollBarX","leftScroll","getHTMLOffset","scroll","htmlRect","absoluteOrFixed","getClientRectFromClippingAncestor","clippingAncestor","html","clientWidth","clientHeight","visualViewportBased","windowScrollbarX","doc","bodyStyles","bodyMarginInline","compatMode","marginLeft","marginRight","clippingStableScrollbarWidth","abs","getViewportRect","scrollWidth","scrollHeight","getDocumentRect","getInnerBoundingClientRect","hasFixedPositionAncestor","stopNode","getRectRelativeToOffsetParent","isOffsetParentAnElement","offsets","setLeftRTLScrollbarOffset","offsetRect","htmlOffset","isStaticPositioned","getTrueOffsetParent","polyfill","rawOffsetParent","svgOffsetParent","currentNode","getContainingBlock","topLayer","clippingAncestors","cache","cachedResult","currentContainingBlockComputedStyle","elementIsFixed","computedStyle","currentNodeIsContaining","ancestor","getClippingElementAncestors","_c","clippingRect","accRect","getElementRects","getOffsetParentFn","getDimensionsFn","getDimensions","floatingDimensions","getClientRects","isRTL","rectsAreEqual","autoUpdate","update","ancestorScroll","ancestorResize","elementResize","ResizeObserver","layoutShift","IntersectionObserver","animationFrame","referenceEl","ancestors","passive","cleanupIo","onMove","timeoutId","io","root","cleanup","_io","clearTimeout","disconnect","refresh","skip","threshold","elementRectForRootMargin","rootMargin","isFirstUpdate","handleObserve","ratio","intersectionRatio","observe","observeMove","frameId","reobserveFrame","resizeObserver","firstEntry","unobserve","cancelAnimationFrame","requestAnimationFrame","_resizeObserver","prevRefRect","frameLoop","nextRefRect","_resizeObserver2","offset","_middlewareData$offse","_middlewareData$arrow","middlewareData","diffCoords","mainAxisMulti","crossAxisMulti","mainAxis","crossAxis","convertValueToCoords","arrow","alignmentOffset","shift","checkMainAxis","checkCrossAxis","limiter","detectOverflowOptions","mainAxisCoord","crossAxisCoord","limitedCoords","flip","_middlewareData$flip","initialPlacement","fallbackPlacements","specifiedFallbackPlacements","fallbackStrategy","fallbackAxisSideDirection","flipAlignment","initialSideAxis","isBasePlacement","oppositePlacement","getExpandedPlacements","hasFallbackAxisSideDirection","isStart","getSideList","getOppositeAxisPlacements","placements","overflows","overflowsData","sides","mainAlignmentSide","getAlignmentSides","every","_middlewareData$flip2","_overflowsData$filter","nextIndex","nextPlacement","reset","resetPlacement","_overflowsData$filter2","currentSideAxis","_state$middlewareData","_state$middlewareData2","apply","isYAxis","heightSide","widthSide","maximumClippingHeight","maximumClippingWidth","availableHeight","availableWidth","xMin","xMax","yMin","yMax","nextDimensions","computePosition","mergedOptions","platformWithCache","middleware","validMiddleware","statefulPlacement","resetCount","_platform$detectOverf","nextX","nextY","computePosition$1","deepEqual","getDPR","devicePixelRatio","roundByDPR","dpr","useLatestRef","deps","offset$1","shift$1","size$1","SafeReact","serverHandoffComplete","genId","random","useId","setId","useModernLayoutEffect","devMessageSet","FloatingNodeContext","createContext","FloatingTreeContext","useFloating","nodeId","internalRootContext","open","onOpenChange","onOpenChangeProp","elementsProp","floatingId","dataRef","events","emit","_map$get","listener","on","off","_map$get2","createEventEmitter","nested","_React$useContext","useContext","optionDomReference","_devMessageSet3","_len2","arguments","messages","_key2","_devMessageSet4","positionReference","setPositionReference","callback","_len","args","_key","useEffectEvent","reason","openEvent","refs","domReference","useFloatingRootContext","rootContext","computedElements","_domReference","setDomReference","_setPositionReference","domReferenceRef","tree","externalReference","externalFloating","whileElementsMounted","isPositioned","latestMiddleware","setLatestMiddleware","_reference","_setReference","_floating","_setFloating","setReference","referenceRef","setFloating","floatingRef","floatingEl","hasWhileElementsMounted","whileElementsMountedRef","platformRef","openRef","then","fullData","isMountedRef","ReactDOM","flushSync","floatingStyles","initialStyles","useFloating$1","computedPositionReference","context","floatingContext","nodesRef","Popover$1","anchorEl","sameWidth","zIndex","shouldIgnoreClose","fOffset","flip$1","createPortal","SearchToolbarComponent","showExport","showColumnToggle","showBulkActions","columnVisibility","bulkActions","exportOptions","onGlobalFilterChange","onClearFilters","onColumnVisibilityChange","onScrollToColumn","density","onDensityChange","showDensityControl","customLeftContent","customRightContent","showExportMenu","setShowExportMenu","showFilters","setShowFilters","showBulkActionsMenu","setShowBulkActionsMenu","showColumnMenu","setShowColumnMenu","columnSearch","setColumnSearch","searchInputRef","exportMenuRef","bulkActionsRef","columnMenuRef","filtersMenuRef","filtersAnchorRef","exportAnchorRef","bulkActionsAnchorRef","columnAnchorRef","getAttribute","dataset","popoverRoot","isInAnyPopover","classList","cls","isInMuiDatePicker","exportFormats","formats","hasActiveFilters","hasSelectedRows","visibleColumnsCount","filteredColumns","getExportIcon","format","getBulkActionIcon","action","getFormatLabel","handleExport","exportSelected","onExport","hasFilterableColumns","Popover","handleBulkAction","destructive","handleColumnToggle","visible","toUpperCase","SearchToolbar","useAdvancedFiltering","globalFilterState","setGlobalFilterState","setColumnFilters","isFilterPending","startFilterTransition","useTransition","startColumnFilterTransition","setGlobalFilter","deferredGlobalFilter","useDeferredValue","applyColumnFilter","precomputed","filterText","startsWith","endsWith","filterNum","secondNum","filterTs","secondTs","raw","rowTs","normalizeBlank","rowSearchCacheRef","WeakMap","cacheSizeRef","clearCacheIfNeeded","filteredData","hasColumnFilters","hasGlobal","lowerGlobal","working","fd","sd","visibleColumns","packed","setColumnFilter","clearColumnFilter","clearAllFilters","getActiveFilterCount","workerFactory","ctx","self","processData","dir","av","bv","onmessage","msg","payload","postMessage","useDataWorker","workerRef","resolverRef","enabledRef","terminate","reject","DOMException","ensureWorkerRef","code","blob","Blob","blobUrl","URL","createObjectURL","w","Worker","revokeObjectURL","resolve","Promise","UNKNOWN","buildPath","gatherGroupPaths","colKey","str","arr","groupRows","computeAggregates","aggregate","aggVal","picked","usePagination","pagination","setCurrentPage","setPageSize","setIsServerLoading","resetPage","isEnabled","mode","serverConfig","ceil","paginatedData","handlePageChange","handlePageSizeChange","newPageSize","areSetsEqual","useSelection","selectedRowIds","setSelectedRows","rowByIdMap","needsPrune","handleRowSelect","newSet","handleSelectAll","useVirtualization","overscan","scrollRef","setScrollTop","rafIdRef","pendingScrollTopRef","containerHeight","setContainerHeight","ro","entry","h","contentRect","initial","rowsInView","dynamicOverscan","visibleCount","visibleData","handleScroll","DEFAULT_CAN_SELECT_CELL","KDGrid","forwardRef","densityProp","headerDensity","headerHeightProp","onSelectedRowsChange","showToolbar","rowHeightProp","cellFocusEnabled","onCellFocusChange","cellSelectionEnabled","canSelectCell","onCellSelectionChange","virtualizationThreshold","loading","onFilterChange","onColumnConfigChange","initialColumnConfig","toolbarLeft","toolbarRight","groupBarVisibility","groupFooterVariant","onCopyCells","performanceConfig","exportOptionsProp","containerWidth","setContainerWidth","focusedCell","setFocusedCell","selectionAnchor","setSelectionAnchor","selectionEnd","setSelectionEnd","isMouseDownRef","lastMousePosRef","autoScrollRafRef","dragOverlay","setDragOverlay","setDensity","densityMap","sm","md","lg","resolvedRowHeight","resolvedHeaderHeight","setSortConfig","columnWidths","setColumnWidths","initialWidths","initialWidthsRef","initialOrderRef","setColumnOrder","setPinnedColumns","setColumnVisibility","initialVisibility","handleSort","nextKey","nextDir","handleColumnResize","estimateWidthForText","autosizeColumn","headerWidth","sample","maxCell","computed","autosizeAllColumns","resetColumns","headerScrollRef","footerScrollRef","handleColumnPin","pinned","handleColumnVisibilityChange","workerProcess","sortedData","setSortedData","workerThreshold","sortWorkerThreshold","cancelled","out","loadingOverall","showLoader","setShowLoader","finishingLoader","setFinishingLoader","loaderTop","setLoaderTop","handleGlobalFilterChange","groupConfig","displayData","groupedDisplayData","handleGroupBy","addGroupKey","removeGroupKey","setGroupKeys","toggleGroupExpansion","expandAllGroups","collapseAllGroups","setGroupConfig","columnKeys","expanded","flat","recurse","pathParts","nextPath","pathStr","agg","_groupAgg","allPaths","differs","nextKeys","nextExpanded","groupPath","useGrouping","useImperativeHandle","getGroupConfig","effectivePinnedColumns","finalDisplayData","dataToDisplay","onSelectedRowsChangeRef","exportData","exportDataWithSelection","filename","getVisibleColumns","downloadFile","content","fileName","mimeType","url","link","createElement","href","download","appendChild","click","removeChild","exportToCSV","exportFilename","headers","exportToJSON","jsonData","JSON","stringify","exportToXLSX","default","ExcelJS","saveAs","all","import","workbook","Workbook","sheet","addWorksheet","sampled","coerceValue","maxLen","obj","addRow","getRow","font","bold","autoFilter","to","rowCount","buffer","xlsx","writeBuffer","canExportSelected","selectedCount","useExport","handleToolbarExport","selectedIds","exportMode","onServerExport","handleClearFilters","handleSetDensity","effectiveVirtualized","perfConfig","enableHorizontalVirtualization","horizontalVirtualizationThreshold","maxFilterCacheSize","enableAggressiveMemoization","hScrollLeft","setHScrollLeft","hScrollLeftRef","hScrollRafRef","scheduleHScrollUpdate","setViewportWidth","filterableKeys","existingKeys","fromEntries","pins","filters","filtered","remaining","timer","columnsWithWidths","orderIndex","candidate","viewportW","baseTotal","flexCols","flex","extra","totalWeight","POSITIVE_INFINITY","unpinned","groupIndex","needsHorizontalVirtualization","pinnedAll","unpinnedAll","unpinnedMeta","widths","prefix","leftPad","pinnedTotal","targetLeft","targetRight","localLeft","localRight","startIdx","lo","hi","ans","mid","firstIndexWithRightGte","endIdx","lastIndexWithLeftLte","sliced","unpinnedIndexByKey","hvPadLeftMemo","hvPadRightMemo","visibleUnpinned","firstIdx","lastIdx","hasFooterAggregate","bodyElement","isBodyScrolling","syncFromBody","footerEl","colIndexByKey","colByKey","flatRows","rowIndexById","rowById","prevSelectionSignatureRef","onCellSelectionChangeRef","onCopyCellsRef","rowObj","colObj","rMin","rMax","cMin","cMax","forwardWheelToBody","bodyEl","dx","deltaX","deltaY","scrollBy","handleCellMouseDown","rIndex","cIndex","hasAttribute","button","cols","handleCellMouseEnter","onUp","ensureAutoScrollLoop","step","mp","maxSpeed","dy","onKey","isShift","shiftKey","maxRow","maxCol","nr","headerEl","handler","currentRowIdx","currentColIdx","nextRow","nextCol","viewportH","targetTop","targetBottom","colWidth","ensureVisible","bounds","cells","sig","rowStart","rowEnd","colStart","colEnd","metaKey","ctrlKey","includeHeaders","hasRect","hasFocus","sel","getSelection","active","activeElement","tagName","isContentEditable","collectCells","escapeCell","line","clipboard","writeText","isRectangular","isFocusedCell","scrollTo","center","onScroll","headerPinned","headerUnpinned","nodes","chunk","flush","opacity","chips","rawVal","fmt","aggregateFormatter","isInteger","num","scrollbarWidth","msOverflowStyle","onWheel"],"mappings":"mYAWA,IAAIA,EAAqBC,OAAOC,IAAI,8BAClCC,EAAsBF,OAAOC,IAAI,kBACnC,SAASE,EAAQC,EAAMC,EAAQC,GAC7B,IAAIC,EAAM,KAGV,QAFK,IAAMD,IAAaC,EAAM,GAAKD,QAC9B,IAAMD,EAAOE,MAAQA,EAAM,GAAKF,EAAOE,KACxC,QAASF,EAEX,IAAK,IAAIG,KADTF,EAAW,CAAA,EACUD,EACnB,QAAUG,IAAaF,EAASE,GAAYH,EAAOG,SAChDF,EAAWD,EAElB,MAAO,CACLI,SAAUV,EACVK,KAAMA,EACNG,IAAKA,EAC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